How to compare Enums in Java

Hello guys.

I would like to share with you a small hint on how to compare Enums in Java. I see a lot of people who compare enums in java incorrectly.

Let’s say that we have Animal enumeration.

enum Animal {
   DOG, CAT, BIRD
}

The worst way is to compare enums like the example below. This type of comparison can throw NullPointerException in case a variable animal is null.

if (animal.equals(Animal.BIRD)) {
     //DO SOMETHING
}

A better way how to compare java is to switch variable with the Enum constant.

if (Animal.BIRD.equals(animal)) {
     //DO SOMETHING
}

The best way of comparison Enums in Java is to use == operator. The reason why to use this operator is that your code will be null-safe. Check the Java code below.

if (Animal.BIRD == animal) {
     //DO SOMETHING
}

I hope that this article help someone.

Richard


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *