A common mistake by new Java programers is using
== for comparing
Strings. Often the results are correct when using the
== comparison with
== works for comparing
ints. Not only does it work, but it is the correct way to do primitive comparisons.
Strings in Java with
== is bad, because you are comparing
String references and not
String value equality. The reason this ever works is that equal
String constants (meaning
Strings that are defined with quotes) are stored internally at the same memory address.
Strings defined in any other way are stored at unique memory addresses. That means
Strings defined only using quotes are always equal when compared with
==, but not equal with
Strings defined in any other way.
Even when you start out with two
Strings defined using quotes, any manipulation of them places their values at a new memory locations. Here again,
== becomes worthless for comparing the
The moral of this story is that you should almost always use the
equals() method for comparing
Strings in Java. Yes, I said almost always.
== is faster than using the
equals() method. When optimizing code in enterprise systems, a few milliseconds saved using a
equals() may be worth the hassle (and danger) of working with
== for comparisons.
In the rare situations where you need to use
== for improving performance, you can use the
intern() method to make
Strings with otherwise unequal memory locations, equal. After you have manipulated or created a
String, just call
intern() on the
String, and now it gains the memory location of every other equal
String that has been created with quotes, or had
intern() used on it.
Sometimes you need to compare
Strings, but ignore their case. Java has a method for that! Use the
equalsIgnoreCase() method to compare two
Strings for equality without using the capitalization in the comparison.
Finally, when comparing a dynamically created
String to a
String literal, always use the string literal to call the equals method. Doing so prevents
NullPointerExceptions when the dynamically set
String happens to be