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

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.

Related

String Literal vs String Object [duplicate]

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 .

Every time I use String, does it create a new String object?

Let's say that I need to iteratively retrieve a value of the same key from a Java hashmap.
for(int i=0; i<INTEGER.MAX; i++)
map.get("KEY");
In this case, is the "KEY" string created every time I call map.get("KEY")? I was wondering if it's always better to have a String constant, or it doesn't matter.
No. String constants are interned automatically, so any identical string literals all reference the same object in memory.
Some more information on this: http://www.xyzws.com/Javafaq/what-is-string-literal-pool/3
An example of this:
String s1 = "Test";
String s2 = "Test";
String s3 = new String("Test");
s1 == s2;//Evaluates to true, because they are the same object (both created with string literals)
s1 == s3;//Evaluates to false, because they are different objects containing identical data
Yes/No Answer depends on how you create String Objects. Below are the four scenarios I can think of as of now.
Yes Cases
new String() always creates new Object. It is not internedn(Doesn't go to String pool) so you
can not take it back from memory.
Concatenation ( "a" + "b" ) always creates new String Object and it is not interned (Doesn't go to String pool).
No Cases
String a ="aa"; if already available it retrieves from the pool, when not available it creates a new object which is interned also (Goes to String pool as well)
new String().intern() or "aa".intern(); if already available it retrieves from pool , when not available it creates new object which
is interned also (Goes to String pool as well).
is the "KEY" string created every time I call map.get("KEY")?
No.
Java Strings are immutable, which allows the Java compiler to use a single instance for all string literals.
That is: all identical string literals in your program will reference a single string object.
In the rare cases you need identical strings to be wrapped in two separate objects, you must explicitly
instantiate a String object:
String s1 = "bla";
String s2 = "bla";
// s1 == s2
String s3 = new String ("bla");
// s1 != s3

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.

String object creation using new and its comparison with intern method

I read in Kathy Sierra book that when we create String using new operator like String s = new String("abc") 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, literal "abc" will be placed in the pool.
intern() says that if String pool already contains a string then the string from the pool is returned Otherwise, the String object is added to the pool and a reference to this String object is returned.
If string "abc" when created using new also placed the string in the pool, then wht does intern() says that string from the pool is returned if String pool contains the string otherwise the string object is added to the pool.
Also I want to know if we create a String using new then actually how many objects get created?
TL;DR: If you ever really need to do new String("abc"), you'll know you need to and you'll know why. It's so rare that it's almost valid to say you never need to. Just use "abc".
The long version:
When you have the code new String("abc") the following things occur at various times:
When the class containing that code is loaded, if a string with the characters "abc" is not already in the intern pool, it's created and put there.
When the new String("abc") code is run:
A reference to the "abc" string from the intern pool is passed into the String constructor.
A new String object is created and initialized by copying the characters from the String passed into the constructor.
The new String object is returned to you.
If string "abc" when created using new also placed the string in the pool, then why does intern() says that string from the pool is returned if String pool contains the string otherwise the string object is added to the pool.
Because that's what intern does. Note that calling intern on a string literal is a no-op; string literals are all interned automatically. E.g.:
String s1 = "abc"; // Get a reference to the string defined by the literal
String s2 = s1.intern(); // No-op
System.out.println(s1 == s2); // "true"
System.out.println(s1 == "abc"); // "true", all literals are interned automatically
Also I want to know if we create a String using new then actually how many objects get created?
You create at least one String object (the new, non-interned one), and possibly two (if the literal wasn't already in the pool; but again, that bit happens earlier, when the class file's literals are loaded):
String s1 = "abc"; // Get a reference to the string defined by the literal
String s2 = new String(s1); // Create a new `String` object (guaranteed)
System.out.println(s1 == s2); // "false"
String s3 = s2.intern(); // Get the interned version of the string with these characters
System.out.println(s1 == s3); // "true"
String Pool is a pool of string references. Objects are created in Heap only.
When using new String("abc").intern() or using method like String s = "abc"; String pool is checked if there is an reference existing which refers to "abc".
In case reference for "abc" already exists in pool and .intern() is called on the reference referencing to an String object created using new String("abc"), then object created by new String("abc") is eligible for garbage collection. See below code for more clarity.
public static void main(String[] args) {
String s = new String("abc");
String a = s;
System.out.println(s==a);// true
String b = "abc";
s = s.intern();
System.out.println(s==a);// false
}

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