You can compare two enum constants in three ways:
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.
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); } }
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.
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.