From the Java Language Specification, Section 3.10.5 String Literals
Each string literal is a reference to an instance of the String class. String objects have a constant value. String literals, or, more generally, strings that are constant expression values, are βinternedβ to exchange unique instances using the String.intern method.
Thus, a test program consisting of a compilation unit:
package testPackage; class Test { public static void main(String[] args) { String hello = "Hello", lo = "lo"; System.out.print((hello == "Hello") + " "); System.out.print((Other.hello == hello) + " "); System.out.print((other.Other.hello == hello) + " "); System.out.print((hello == ("Hel"+"lo")) + " "); System.out.print((hello == ("Hel"+lo)) + " "); System.out.println(hello == ("Hel"+lo).intern()); } } class Other { static String hello = "Hello"; }
and compilation unit:
package other; public class Other { static String hello = "Hello"; }
outputs the result:
true true true true false true
This example illustrates six points:
- Literal strings in the same class in the same package link to the same string object.
- Literal strings in different classes in one package are references to the same String object.
- Literal strings in different classes in different packages are also references to the same String object.
- The lines computed by the expression constant are computed when the time is compiled, and then processed as if they were literals.
- Lines computed by concatenation at run time are newly created and therefore different.
- Result of Explicit Internment The calculated string is the same string as any pre-existing literal string with the same contents.
source share