Enum equality in Java
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()
:
|
|
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:
|
|
Line 4 now evaluates to false
.
Using == operator #
Unlike String equality comparisons, we can use the ==
operator and it is also null-safe.
|
|
Line 4 evaluates to false
.