Skip to main content
  1. blog/

Enum equality in Java

·2 mins

Note

This article was written over 5 years ago. Some information may be outdated or irrelevant.

Overview #

The enum type was introduced in Java 5 and is useful when we have a field that’s only allowed to have a small set of possible values.

Enums make our code more readable, allow compile-time checking, and prevent errors due to illegal values.

Here are some concepts that are good enum candidates:

  • Account status: ENABLED, DISABLED
  • T-Shirt size: SMALL, MEDIUM, LARGE
  • Seat class: ECONOMY, PREMIUM_ECONOMY, BUSINESS

In this article, I’ll cover how to check enum equality in Java.

Note that Java enum values cannot contain spaces. The convention is to use all uppercase and use underscores to separate words.


Using equals() method #

Consider this example using equals():

1
2
3
4
5
6
Customer customer = new Customer();
customer.setStatus(null);

if (customer.getStatus().equals(Status.ENABLED)) { 
  // do something 
}

Line 4 will throw a NullPointerException because we attempted to call the equals() method on a null reference.

We can make this null-safe by switching the order of the comparison on line 4:

1
2
3
4
5
6
Customer customer = new Customer();
customer.setStatus(null);

if (Status.ENABLED.equals(customer.getStatus())) { 
  // do something 
}

Line 4 now evaluates to false.


Using == operator #

Unlike String equality comparisons, we can use the == operator and it is also null-safe.

1
2
3
4
5
6
Customer customer = new Customer();
customer.setStatus(null);

if (customer.getStatus() == Status.ENABLED) { 
  // do something 
}

Line 4 evaluates to false.