Originally posted by leandro oliveira:
String s="string" ; //this creates a new allocated string
s="strings";// this also creates a new allocated string
The above strings are compile-time constants and they both exist in a pool of string constants when the program is loaded. The above two lines of code assign to reference variable s the reference value of the String constants that already exist in the constant pool.
The following line of code will create at run-time a new instance of a String object.
String s1 = new String("string");
The following line will create another instance of a String that contains the same value.
String s2 = new String("string");
If you compare the above strings, s1 and s2, using the equality operator, ==, then the result will be false because the references refer to unique instances. If you want both to refer to the same instance then you can invoke the intern() method on s1 and s2.
s1 = s1.intern();
s2 = s2.intern();
Both s1 and s2 now refer to the same String instance in the pool of constant strings.