public class Comparison {
public static void main(String[] args) {
String s = \"prova\";
String s2 = \"prova\";
System.
JLS, 3.10.5 => It is guaranteed that a literal string object will be reused by any other code running in the same virtual machine that happens to contain the same string literal
String s = "prova";
String s2 = "prova";
s
and s2
are literal strings which are pointing the same object in String Pool of JVM, so that the comparison returns true.
Source code literals are part of a constant pool, so if the same literal appears multiple times, it will be the same object at runtime.
The JVM may optimize the String usage so that there is only one instance of the "equal" String in memory. In this case also the == operator will return true. But don't count on it, though.
Ideally it should not happen ever. Because java specification guarantees this. So I think it may be the bug in JVM, you should report to the sun microsystems.
You must understand that "==" compares references and "equals" compares values. Both s
and s1
are pointing to the same string literal, so their references are the same.