That's because they are "string literals" -- means "compile time constants". they are treated as constants during the compile time itself. To be clear, those string literals are loaded when the class is loaded -- much before the runtime.
Whereas even though you have the String reference variables 'hel' and 'lo' contain the equivalent string as their content, they are the values of a variable, which is
not a constant.
So the output is false in your case.
Taken from Strings section of JLS, second edition:
# Literal strings within the same class (�8) in the same package (�7) represent references to the same String object (�4.3.1).
# Literal strings within different classes in the same package represent references to the same String object.
# Literal strings within different classes in different packages likewise represent references to the same String object.
# Strings computed by constant expressions (�15.28) are computed at compile time and then treated as if they were literals.
# Strings computed at run time are newly created and therefore distinct.
# The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.
Hope this helps! :cheers:
For example, try chaging the variables 'hel' and 'lo' as final variables
[ April 08, 2008: Message edited by: Raghavan Muthu ]