The following statement appears in Section 3.10.5. String Literals of the Java Language Specification:
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.
I am using Java JDK 7 and Eclipse indigo.
and my test program is as follows:
public class Main {
public static void main(String[] args) {
String s1 = "string";
String s2 = "string";
System.out.print(s1 == s2); // true
System.out.print(" , " + "string" == "string"); // false
}
}
This is an operator precedence issue. The
==operator has a lower precedence than the+operator.What you are actually testing is whether
(" , " + "string")is equal to"string". It isn’t.If you mean that to compare
"string"and"string"you should write:The standard advice of not using
==to test strings applies too … but that’s not what is giving you the confusing output.