String x = "Hello!";
String y = "Hello!";
System.out.println( x == y );
How come this is still coming out true
, aren't they referring to different locations in heap memory?
String x = "Hello!";
String y = "Hello!";
System.out.println( x == y );
How come this is still coming out true
, aren't they referring to different locations in heap memory?
The JVM stores String literals in a pool for reuse. more information here: Reusability of Strings in java?
This is covered in JLS 3.10.5 (and 15.28, which 3.10.5 references):
A string literal is a reference to an instance of class
String
(§4.3.1, §4.3.3).Moreover, a string literal always refers to the same instance of class
String
. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the methodString.intern
.
NO . They aren't referring to different locations. Since its a String literal, It will not create a new object for y
, rather it will refer to the same object which is already created for x
in the string pool.