Comparing Constants Safely

When comparing two objects, the equals method is used to return true if they are identical. Typically, this leads to the following code :

if (name.equals("Jim")) {
}

The problem here is that whether intended or not, it is quite possible that the name value is null, in which case a null pointer exception would be thrown. A better practice is to execute the equals method of the string constant “Jim” instead :

if ("Jim".equals(name)) {
}

Since the constant is never null, a null exception will not be thrown, and if the other value is null, the equals comparison will fail.

If you are using Java 7 or above, the new Objects class has an equals static method to compare two objects while taking null values into account.

if (Objects.equals(name,"Jim")) {
}

Alternatively if you are using a java version prior to Java 7, but using the guava library you can use the Objects class which has a static equal() method that takes two objects and handles null cases for you. It should also be noted that there are probably a number of other implementations in various libraries (i.e. Apache Commons)

One thought on “Comparing Constants Safely

  1. Kieron Wilkinson

    Thanks for the Objects reference, I hadn’t seen that.

    I’ve always disliked the “backwards” equality comparison. It just doesn’t seem as readable to me.

    But actually, we’ve been pretty successful if getting rid of use of nulls from many of our main codebases, to an extent that doing the more natural equality comparison is preferable exactly because it will produce an NPE. It means it’s a bug, and it will fail fast, rather than hiding the problem.

    This is of course much more difficult in a legacy codebase. We’ve found the use of IntelliJ’s Nullable/NotNull annotations invaluable there.