Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Comparing Constants Safely

DZone's Guide to

Comparing Constants Safely

· Java Zone
Free Resource

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

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)

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

Topics:

Published at DZone with permission of Andy Gibson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}