String Literal vs String Object [duplicate] - java

This question already has answers here:
What is the difference between "text" and new String("text")?
(13 answers)
Closed 6 years ago.
I read a lot about String Literal vs String Object. I read that String literal is stored in a String pool and String object will create an object in the heap. I'm quite confused in an instance variable of a class that is initialized using "".
class A {
private String aStr = "ASTRING";
}
Will aStr will be added to String pool or will it create an object in the heap?

Whenever new Keyword is used then object is created in heap.
Here new Keyword is not used so string object is created in string pool.
For example:
String s1= new String("string object");
In the above example two objects are being created one is string object in string pool since it is in double quotes another is s1 which is created in heap as new keyword is used.

As Gaur93 said its true, but i would like to add some more points.
Lets take an example:
String s = "hello";
String s1 = new String("hello");
String objects are basically wrappers around string literals. Unique string objects are pooled to prevent unnecessary object creation, and the JVM decide to pool string literals internally.
When you use a literal, say
String str = "hello"
the object in the pool is used. If you use String str = new String("hello"); , a new object is created, but the existing string literal may be reused on either the JVM level or bytecode level (at compile time).
You can check this by using .equals() method of java .

Related

In Java what is the difference between two String initialization methods? [duplicate]

This question already has answers here:
Literal string creation vs String object creation
(3 answers)
Closed 3 years ago.
String str = "ABC";
String str2 = new String("ABC");
In both the methods if i am looking for hashcode it is giving same hashcode
I saw the explanation in the Toptal questions: https://www.toptal.com/java/interview-questions
"In general, String s = "Test" is more efficient to use than String s = new String("Test").
In the case of String s = "Test", a String with the value “Test” will be created in the String pool. If another String with the same value is then created (e.g., String s2 = "Test"), it will reference this same object in the String pool.
However, if you use String s = new String("Test"), in addition to creating a String with the value “Test” in the String pool, that String object will then be passed to the constructor of the String Object (i.e., new String("Test")) and will create another String object (not in the String pool) with that value. Each such call will therefore create an additional String object (e.g., String s2 = new String("Test") would create an addition String object, rather than just reusing the same String object from the String pool)."
Both expression gives you String object, but there is subtle difference between them. When you create String object using new() operator, it always create a new object in heap memory. On the other hand, if you create object using String literal syntax e.g. "Java", it may return an existing object from String pool (a cache of String object , which is now moved to heap space in recent Java release), if it's already exists. Otherwise it will create a new string object and put in string pool for future re-use.

Which String Object is accessed?

As we know that when we create new String object by new keyword like this:
String str = new String("New String Will Have Two Objects");
It will create two objects of, one on java heap memory and other on String pool.
So when we call access "str" which string object is accessed(heap object or string pool object)?
According to my understanding the string pool object is get accessed, if yes then what happens to heap object?
If you are creating the String object with new
String str = new String("New String Will Have Two Objects");
In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "New String Will Have Two Objects" will be placed in the string constant pool. The variable str will refer to the object in heap(non pool).
Method ‘intern()’ usage
This is best described by java docs
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
String str = new String("New String Will Have Two Objects");
str.intern();
new String creates a new string on heap. This string's reference gets assigned to str.
String literals always have a reference to them from the String Literal Pool. That means that they always have a reference to them and are, therefore, not eligible for garbage collection http://www.javaranch.com/journal/200409/ScjpTipLine-StringsLiterally.html

difference between two java String assignment types [duplicate]

This question already has answers here:
What is the difference between "text" and new String("text")?
(13 answers)
Difference between string object and string literal [duplicate]
(13 answers)
Closed 8 years ago.
what is the difference between these two implementations :
String s1 = "java";
and
String s2 = new String("java");
is s1 is able to perform all the functions that s2 will do?? like to uppercase, append etc..
The only Difference is String s1 = "java" will create a String Literal and it will be stored in a String Pool And for String s2 = new Sting("java") an Instance object will be created plus a String Literal in String pool.
For Second part Yes you can, Since its a Variable and variable can access library function using dot operator. so s1.toUpperCase() and s2.toUpperCase().
Ex.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String s1 = new String("java");
System.out.println(s1.toUpperCase());
String s2 = "java";
System.out.println(s2.toUpperCase());
}
}
Result : JAVA JAVA
For the first part of question, it has been asked many times and answered many times like here and I don't think we need a better answer there
For the second part of your question,
is s1 is able to perform all the functions that s2 will do?? like to
uppercase, append etc..
Absolutely yes! Try "hello".toUpperCase()
String s = "abc"; // creates one String object and one reference variable
In this simple case, "abc" will go in the pool and s will refer to it.
String s = new String("abc"); // creates two objects and one reference variable
In this case, because we used the new keyword, Java will create a new String object
in normal (nonpool) memory, and s will refer to it. In addition, the literal "abc" will
be placed in the poo
String s1="java" // will store in string pool
String s2=new String("java"); //will store in heap
so s1==s2 results in false.
if You want s2 also in pool then u have to call s2.intern(). After that s1==s2 results in true.

Creating a String object by "new"

Consider statement:
String s=new String("abc");
Will this statement creates two String objects namely "abc" and the one represented by 's'?
and if it creates two objects then will "abc" get stored in String pool or just discarded?
EDIT:
i am asking this question in reference to Difference between string object and string literal, where in the last two answers , creation of two objects is denied.
Avoid such kind of behavior , because "abc" is already a String and by making a new String, you are creating an unnecessary Object.
Instead go for String s = "abc";
This way, the String gets interned by the JVM and is added to a pool.
To answer your question, you are just creating an Object s that is referring to "abc".
So when you do say String t = new String("abc"); and then do s==t, will yield in false. Because they have their separate instances to abc.
String s = "HELLO";
Here "s" is a object reference variable of type String, which refers to the String literal object "Hello" which is added to the String Literal Pool.
String t = new String("Hello");
Here t is a object reference variable of type String, which refers to the String object "Hello" which is added to the String Pool.
Difference Between String Literal and String :
Assume
String s = "Hello";
String t = new String("Hello");
Now if following changes are done:
s = null;
t = null;
Hello String object associated with t will be a candidate for Garbage Collector, But Hello String Literal associated with s will NOT BE A CANDIDATE for Garbage Collector, as there will ALWAYS BE A REFERENCE FROM STRING LITERAL POOL to it.

Java String declaration [duplicate]

This question already has answers here:
What is the difference between "text" and new String("text")?
(13 answers)
Closed 2 years ago.
What is the difference between String str = new String("SOME") and String str="SOME"
Does these declarations gives performance variation.
String str = new String("SOME")
always create a new object on the heap
String str="SOME"
uses the String pool
Try this small example:
String s1 = new String("hello");
String s2 = "hello";
String s3 = "hello";
System.err.println(s1 == s2);
System.err.println(s2 == s3);
To avoid creating unnecesary objects on the heap use the second form.
There is a small difference between both.
Second declaration assignates the reference associated to the constant SOMEto the variable str
First declaration creates a new String having for value the value of the constant SOME and assignates its reference to the variable str.
In the first case, a second String has been created having the same value that SOME which implies more inititialization time. As a consequence, you should avoid it. Furthermore, at compile time, all constants SOMEare transformed into the same instance, which uses far less memory.
As a consequence, always prefer second syntax.
String s1 = "Welcome"; // Does not create a new instance
String s2 = new String("Welcome"); // Creates two objects and one reference variable
First one will create new String object in heap and str will refer it. In addition literal will also be placed in String pool. It means 2 objects will be created and 1 reference variable.
Second option will create String literal in pool only and str will refer it. So only 1 Object will be created and 1 reference. This option will use the instance from String pool always rather than creating new one each time it is executed.

Categories

Resources