+ 1
In java what is the difference between String str="abc"; and String str=new String ("abc") ??
2 odpowiedzi
+ 10
//see Serena's answer
https://www.sololearn.com/Discuss/647021/?ref=app
+ 7
First some background info:
In java there is something called the 'String Constant Pool' or SCP. This is where String literal values are stored. The compiler checks the SCP for each String literal. If a String with the same value has already been created, then the new String will point to the old String's memory location to avoid having to actually create a new String. If a String with the same value has not been created, then we create a String and maintain its value in the SCP.
This works because Strings are immutable, you CANNOT modify the value of a String.
String a = "i";
a += "mameatball";
2 Different Strings are created here. "i", and "imameatball".
Back to the question:
The 1st one is a short hand way of creating a new String. The String literal is checked in the SCP.
The 2nd one will create a new String. It passes the String literal in the parenthesis to the constructor and creates the String. The String literal is checked in the SCP, though the new String with that value is still created.
So,
String a = new String("hi");
String b = new String("hi");
This created 2 different Strings. The references of 'a' and 'b' will be stored separately in the heap memory.
String a = "hi";
String b = "hi";
This created 1 String. 'b' and 'a' both point to the same memory location. "hi" was placed in the SCP, both Strings have the value "hi" so we don't need to keep making a new String.
The SCP happens at compilation time.
Hopefully that made sense. If I didn't explain it well maybe this person explained it better:
http://www.java67.com/2014/08/difference-between-string-literal-and-new-String-object-Java.html?m=1