public static void main(String[] args) {
String a = new String("abc");
String b = new String("abc");
System.out.println(a.equals(b));
System.out.println(a == b);
}
Prints true
, then false
. So two strings with the same sequence of characters do have to equal
each other, but can either ==
each other or not.
Obviously, a == a
under all circumstances, and a
is a String
containing the same sequence of characters as a
.
But in the example above, we're creating two different instances, which just happen to contain the same sequence of characters. Hence a != b
.
So what's happening in your example? String interning.
Any string literals are allocated in a special pool by the compiler, and any duplicate literals share the same reference. So even though the literal is defined twice, as far as the compiler's concerned, they're the same instance.