Because they are the same object.
When you start the JVM and load the classes, the String literals ("hello") are reused where they appear, so with:
String s1 = "Hola";
String s2 = "Hola";
String s3 = new String("Hola");
, s1
and s2
point to the same instance (defined by the compiler), and that's why s1 == s2
returns true
.
In contrast, s3
is a different instance, so s1 == s3
returns false
.
To complete the answer, the class String
includes an internal pool where "caches" strings to be reused. All literals are saved there, and with the method String.intern()
You can access the instance of a String that has been used for literals. So s1 == s3.intern()
returns true
.