Java - Enum Constants Comparison

Introduction

You can compare two enum constants in three ways:

  • Using the compareTo() method of the Enum class
  • Using the equals() method of the Enum class
  • Using the == operator

compareTo() method

compareTo() method compares two enum constants of the same enum type.

It returns the difference in ordinal for the two enum constants.

If both enum constants are the same, it returns zero.

The following snippet of code will print -3 because the difference of the ordinals for LOW(ordinal=0) and URGENT(ordinal=3) is -3.

A negative value means the constant being compared occurs before the one being compared against.

Demo

enum Level {
  LOW, MEDIUM, HIGH, URGENT;/*w  ww  . ja  va2  s  .  c o m*/
}

public class Main {
  public static void main(String[] args) {
    Level s1 = Level.LOW;
    Level s2 = Level.URGENT;
    int diff = s1.compareTo(s2);
    System.out.println(diff);
  }
}

Result

equals()

equals() method compares two enum constants for equality.

An enum constant is equal only to itself.

If the two enum constants are from different enum types, the method returns false.

== operator

You can use the equality operator ( ==) to compare two enum constants for equality.

Both operands to the == operator must be of the same enum type. Otherwise, you get a compile-time error.

Quiz