Java Code
class Other {
static String hello = "Hello World";
}
public class Main {
public static void main(String[] args) {
String hello = "Hello World", world = "World";
System.out.println(Other.hello == hello); // Line1
System.out.println(hello == ("Hello " + "World")); // Line2
System.out.println(hello == ("Hello " + world)); // Line3
System.out.println(hello == ("Hello " + world).intern()); // Line4
System.out.println(Integer.toHexString(hello.hashCode()));
System.out.println(Integer.toHexString(("Hello " + "World").hashCode()));
System.out.println(Integer.toHexString(("Hello " + world).hashCode()));
System.out.println(Integer.toHexString(("Hello " + world).intern().hashCode()));
}
}
I expect Line3 to return true but it is returning false. Kindly help me.
Output
true true false true
42628b2 42628b2 42628b2 42628b2
>Solution :
Only string literals are automatically stored in the String Constant Pool.
The following is a string literal:
"Hello " + "world"
The following is not a string literal:
String world = "world";
"Hello " + world
This is specifically stated in the Java Language Specification:
A long string literal can always be broken up into shorter pieces and
written as a (possibly parenthesized) expression using the string
concatenation operator +
Why isn’t "Hello " + world in the string constant pool? Simply because the JLS says so. That’s what the language designers decided.