Pergunta

the following is true in Java

"abc"=="abc"

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

Foi útil?

Solução 3

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.

Outras dicas

An == operation on an non-primitive object in java will compare by memory location. As both of these strings are compile time constants the compiler will store them only once and therefore you will get the result you describe.

This is because of an optimization the Java compiler performs.

While compiling it sees that you have a constant string "abc", so when it encounters another constant string it checks and finds that it already has that string loaded in memory. So, it just uses the same object again.

The result is that they are the same exact object in memory.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top