How to compare enums in Java

September 6, 2016


The best way to compare enums in Java is == operator, like in an example below:

Comparison of == and equals methods

There are two ways to compare enums in java: == operator and equals() method.

First of all, I would like to show you an implementation of method equals() of java.lang.Enum:

As you can see, the equals() method of java.lang.Enum uses the == operator. This means you can use both to compare Enums. So, when we run the code below:

The result is:

But due to == being an operator and equals() being method, there are subtle differences.

Using equals() can cause NullPointerException

Let’s declare two variables of type Color:

and compare them using == operator:

Everything is alright because if we compare any Enum with null like this, it will print false.

But if we try to compare those variables using equals() method:

we will get NullPointerException.

== operator provides compile-time checking

Compile time safety is another advantage of using == operator. This operator checks if both objects are the same enum type at compile time. Equals() method does not do that because of contract (Object.equals(Object)), so we can expect a RuntimeException.

We should use an == operator, since detecting errors at compile time is always better.

Click here to add a comment

Leave a comment: