Reputation: 3710
I know that
String s1 = "test";
String s2 = new String("test");
System.out.println(s1==s2); // false
in above snippet "test" String Object is created inside the String pool in java (s1 will be passed its reference) and a new String Object will be created in the heap space of the memory (s2 will be in heap sapce).
so will s2 String object be referring to the String pool's "test" String object internally or s2 keeps an altogether different "test" String Object in memory ?
what will be the effect if we somehow "test" String Object in String constant pool is removed ? will s2 still be having the value "test" ?
I know this topic has been touched a lot but none of the previous answers which i checked clarifies it.
please mention any sources if that has a better explanation.
Thanks in advance !
Upvotes: 1
Views: 69
Reputation: 37
Here is the link to the Article by Corey McGlone
http://www.javaranch.com/journal/200409/Journal200409.jsp#a1
Upvotes: 1
Reputation: 140299
In the Java 8 source code, the String(String)
constructor reuses the value
field from the parameter.
Note that value
is a char[]
, though, so the two string instances use the same underlying array, but s2
is not using the "test"
itself internally, since that is a String
, not a char[]
.
Upvotes: 2