String grima = "grima";
String gri = "grima";
if (grima == gri)
System.out.println("grima == gri"); // The message is displayed
Both variables refer to same "grima" in string constant pool.
String pndey = "pandey";
String pan = "pande";
pan = pan + "y"; // The value for pan will be resolved during runtime.
if (pndey == pan)
System.out.println("pndey == pan"); // The 2 references are different
Now in the second case if I change
pan = pan + "y";
to pan="pande" +"y"
, then "pndey == pan" message will be displayed, because the compiler resolves the literal during compilation time.
Now as per Java docs on string:
- Literal strings within the same class (§8 (Classes)) in the same package (§7 (Packages)) represent references to the same String object (§4.3.1).
- Literal strings within different classes in the same package represent references to the same String object.
- Literal strings within different classes in different packages likewise represent references to the same String object.
- Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
- Strings computed by concatenation at run time are newly created and therefore distinct.
- The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.
You read more here: https://codingninjaonline.com/2017/09/18/stringstring-constant-pool-in-java/