In Java, for non-primitive types, the ==
operator compares references, not values.
If you create a bunch of equivalent String literals, like:
String sLit1 = "test";
String sLit2 = "test";
(sLit1 == sLit2)
will be true
, since Java doesn't allocate new memory for each new String literal, it just points them all to the same location in memory. However, when you create a String object:
String sObj = new String("test")
Java always creates a new object, which occupies a new location in memory. So sLit1 == sObj
will always be false
.
Which means that ==
yields true
if and only if the two arguments refer to the same object. To compare strings, use equals
method, as in (sObj.equals(sLit1))
.