Learnitweb

Comparing enum members in Java

You can use both == and equals() method to compare Enum. They will give the same result because equals() method of Java.lang.Enum internally uses == to compare enum in Java. Since every Enum in Java extends java.lang.Enum and equals() method is declared final, there is no way to override equals method in user defined enum.

Java.lang.Enum implements Comparable interface and implements compareTo() method so you can also use compareTo() method.

public class EnumCompareExample {
	public enum Days {
		SUNDAY, MONDAY
	}

	public enum Months {
		JANUARY, FEBRUARY, MARCH
	}

	public static void main(String args[]) {
		Days sunday = Days.SUNDAY;
		Days monday = Days.MONDAY;
		Months jan = Months.JANUARY;

		if (sunday == sunday) {
			System.out.println("Sunday is equal to Sunday");
		}

		if (sunday != monday) {
			System.out.println("Sunday is not equal to monday");
		}

		if (sunday.equals(sunday)) {
			System.out.println("Sunday is equal to Sunday by equals method");
		}

		if (sunday.equals(jan)) {
			System.out.println("Sunday is not equal to Jan");
		}
	}
}

Output

Sunday is equal to Sunday
Sunday is not equal to monday
Sunday is equal to Sunday by equals method

Note

  • Using == for comparing Enum can prevent NullPointerException
    For example, following will result in NullPointerException.
Days sunday = null;
if(sunday.equals(jan)){
	System.out.println("Sunday is equal to Jan");
}
  • == provides type safety at compile time
    If you try to compare two enum which are of different type, == will give error at compile time itself.