Behavior of String literals is confusing
Solution 1:
Every compile-time constant expression that is of type String
will be put into the String pool.
Essentially that means: if the compiler can (easily) "calculate" the value of the String
without running the program, then it will be put into the pool (the rules are slightly more complicated than that and have a few corner cases, see the link above for all the details).
That's true for all the Strings in lines 1-3.
"Hel"+lo
is not a compile-time constant expression, because lo
is a non-constant variable.
The hash codes are the same, because the hashCode of a String depends only on its content. That's required by the contract of equals()
and hashCode()
.
Solution 2:
Strings computed by concatenation at runtime are newly created and therefore distinct
here is a link to read: http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.5