In case anyone else has a similar problem, this is what went wrong:
The == operator tests
reference equality, while the equals() method usually tests
object equality. Two objects may to all intents and purposes be the same, but if they are actually different objects, then the references will not be the same, so the == test will return false.
However, if you perform the obvious test to confirm this, you'll get a different result!
1 2 3 4 5
| public static void main(String[] args){ String s1 = "Hello"; String s2 = "Hello"; System.out.println(s1 == s2); } |
This will actually output "true".
There are two things that lead to this non-obvious result:
- Strings are immutable
As there is no difference between the two "Hello" objects, the compiler is allowed to create a single instance and point both references at it.
- String.intern()
The String class maintains a pool of String objects, and all String literals are placed into it. Even if the compiler didn't share the instances, both references will be pointing at the same object anyway.
In summary, use equals() when you want to check whether two objects represent the same information; use == when you want to check whether two references are pointing at the same object.