Comparing strings in Java for equality

By Steve Claridge on 2015-12-01.

Java doesn't allow you to check if two strings are equal in the completely obvious and intuitive way. It is the classic beginner's mistake to do this:

  
  if ( "hello" == "world" ) 
  {
  }

Everyone has done it (and probably more than once) because it is the obvious thing to do and it is the way most other languages compare strings. It just makes sense to use == but in Java == checks that the two string instances are the same, which means that if ( "hello" == "hello" ) can potentially return false.

A Java String is an instance of the String class, so writing String s = "bah" creates a instance of String in the same way that Animal lion = new Animal() creates an instance of the Animal class. The reason you don't have to write String s = new String( "bah" ) is because strings are handled differently from other objects - because strings are so often used in everyday code the Java language designers built in some shortcuts (not having to write new String()) and improved their performance behind the scenes.

Which makes me wonder why they didn't go a bit further and make equality checking on strings a special case too? Possibly they felt it was too confusing to use == for one class but none of the others.

The usual way

So the typical way to check if two strings are equal is to

  
  if ( "hello".equals( "world" ) ) 
  {
  }

Which is fine but if you are comparing to variables rather than constants you have to also make sure the instance you are calling equals() on is not null:

  
  String a = null;
  String b = "w00t";
  if ( a != null && a.equals( b ) ) 
  {
  }

Which is too much code to be writing all the time and clutters up the codebase.

Alternatives

Obvious thing to do is create your own equals method that does the null check, calls equals() and returns a boolean. But since Java 1.7 the Objects class has some useful utility methods to take away the pain:

  
  String a = null;
  String b = "w00t";
  if ( Objects.equals( a, b ) ) 
  {
  }