One should distinguish what happens, when Java Virtual Machine allocates space for entities during compilation time (as in case of your example):
String s1 = "Hello world";
String s2 = "Hello world XXX";
and when space for strings is allocated during the runtime:
String s3 = new String("Hello world");
String s4 = new String("Hello world XXX");
In the first case, JVM structures all strings in memory in a heap. Every new occurence is compared with existing entries, if two values are the same, they point to the same address in memory space (in other words condition: s1 == s2
is true
). This is possible, because String in Java is immutable, so its hashcode is cached at the time of creation and it doesn’t need to be calculated again.
In the second case, using new
operator forces, JVM to allocate new space in memory model. This implies, that condition s1 == s3
is false
. That is why it is recommended to use for string comparisons method: String.equals()
, as it concerns about variable values, not memory addresses.