Java doubt with equals () and with ==

3

Until a few years ago if I did in Java

  

"Hello" == "Hello"

gave me as a false result, today I saw a code in which they used it with JDK 10 and out of curiosity I went to check it, and it actually returns true, someone can explain why this happens if it is for the Java version or for something else.

    
asked by bruno Diaz martin 08.09.2018 в 20:30
source

1 answer

7

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 .

    
answered by 08.09.2018 / 20:41
source