It s because of a memory optimization performed by the compiler... namely, String
constants (ie - String
s made by the same String
literal) use the same String
object since Strings
are immutable. The ==
operator just checks that two objects are the same actual object.
If you can grab a hold of the book Java Puzzlers by Joshua Bloch and Neal Gafter, and look at puzzle 13, "Animal Farm"... he has great advice on this issue. I am going to copy some relevant text:
"You may be aware that compile-time constants of type String
are interned [JLS 15.28]. In other words any two constant expressions of type String
that designate the same character sequence are represented by identical object references... Your code should rarely, if ever, depend on the interning of string constants. Interning was designed solely to reduce the memory footprint of the virtual machine, not as a tool for programmers... When comparing object references, you should use the equals
method in preference to the ==
operator unless you need to compare object identity rather than value."
That s from the above reference I mentioned... pages 30 - 31 in my book.