I have a simple application with a main method that compares two literal strings:
public class App {
public static void main (String[] args) {
String first = "a";
String second = "a";
System.out.println(first == second);
}
}
When I run this program in Eclipse, I get false
as result. But when I compile and run this program by the command line, I get true
.
The result should be true
for both. Why does Eclipse return false
?
I have tested it using JDK 7 and 8.
Note that I am aware that comparison with ==
compares for identity.
The JLS requires "a"
to come out of the internal String cache, for both variables.
String first = "a"; // Creates instance, stores in cache and returns
String second = "a"; // Should return instance from cache
However, if I run this from Eclipse I get false
for the comparison, so both instances seem to be different although the JLS requires them to be the same.
Therefore, see JLS§3.10.5 String Literals:
Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method
String.intern
.