javastring-interningobject-identity

The == operator in Java


the following is true in Java

"abc"=="abc"

Why? The two Strings are two different objects, they should not have the same object identity?


Solution

  • Java keeps all literals (strings placed in code) in special part of JVM memory. If there are two or more identical literals JVM just pointer to the same object instead of creating few strings with the same content.

    So:

    "ab" == "ab" // true - because they are the same objects
    

    but:

    "ab" == new String("ab") // false - because new String(...) is new String not literal
    

    You can get or move your String to the special memory by invoking intern() method.

        String ab1 = "ab";
        String ab2 = new String("ab");
        // ab1 == ab2 is false as described above
        ab2 = ab2.intern();
        // ab1 == ab2 but now it's true because ab2 pointers to "ab" in special part of memory.