Determine if Strings are equal

To determine if two 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 Strings, using the underlying Unicode representation, while == compares only the identity of the objects, using their address in memory (which is usually not desired).


* 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);

  private static final String BLAH = "blah";

  private static void testUsingEquals(String aString) {
    if (BLAH.equals(aString)) {
      log("Equals: YES, the user entered \"blah\".");
    else {
      log("Equals: NO, the user did not enter \"blah\".");

  private static void testUsingOperator(String aString) {
    if (aString == BLAH) {
      log("== operator: YES, the user entered \"blah\".");
    else {
      log("== operator: NO, the user did not enter \"blah\".");
  private static void log(String aMessage){

An example run of this class:

>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.

Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -