String
objects match exactly, you should almost always use the
equals
method, and not the ==
operator.
The equals
method compares the actual content of the String
s, using the underlying Unicode representation,
while ==
compares only the identity of the objects, using their address in memory (which is usually not desired).
Example
import java.util.Objects; /** * Illustrates the incorrectness of using == for typical * String comparisons. */ public final class EqualStrings { /** * Pass in the String "blah" on the command line in * order to exercise the code. */ public static void main(String... arguments) { String text = (arguments.length == 1 ? arguments[0] : null); testUsingEquals(text); testUsingOperator(text); } // PRIVATE private static final String BLAH = "blah"; private static void testUsingEquals(String string) { if (BLAH.equals(string)) { log("Equals: YES, the user entered \"blah\"."); } else { log("Equals: NO, the user did not enter \"blah\"."); } } private static void testUsingOperator(String string) { if (string == BLAH) { log("== operator: YES, the user entered \"blah\"."); } else { log("== operator: NO, the user did not enter \"blah\"."); } } private static void log(String message){ System.out.println(Objects.toString(message)); } }
>java -cp . EqualStrings blah
Equals: YES, the user entered "blah".
== operator: NO, the user did not enter "blah".
Note that x.equals(y)
will generate a NullPointerException
if x
is null
, but will not generate such an exception
if only y
is null
. In the above example, for instance,
BLAH.equals(aString)
is used instead of aString.equals(BLAH)
,
since aString
may be null
.
It's true that the intern
method may be used to allow meaningful comparisons using ==
.
(See The Java Programming Language by Arnold, Gosling, and Holmes for further information.)
The intern
technique is meant as a performance optimization, and should usually be avoided
since it's more complex.