To elaborate on deadpools answer what is most likely happening in the background is code optimisation.
Java will evaluate String s1 == String s2
to true only if it is the same object.
because y
is declared final
the compiler can replace all instances of y
with the value
it is given
so
final int y = 10;
System.out.println("Y="+y=="Y="+y);
becomes
System.out.println("Y="+10=="Y="+10);
which becomes
String tmp = "Y="+10;
System.out.println(tmp==tmp);
which becomes
System.out.println(true);
However if you do not declare the variable as final then the compiler cannot do this trick as it cannot predict what will happen to y between "Y="+y
and "Y="+y
.
also doing something like
final int y = x;
System.out.println("Y="+y=="Y="+y);
will cause the(my) compiler to skip this optimisation and then it evaluates to false.
TL;DR
It evaluates to true
iff it is the same object, under certain conditions the compiler will optimise the comparison away by doing a pre-calculation.