How to compare enum members in Java

There are two ways for making comparison of enum members :

  • By using == operator
  • By using equals() method

The equals method uses the == operator internally to check if two enumerations are equal. This means you can compare Enums using the == and equals methods. But the question is, if we have two ways to compare two enum members, which one is better?

Both == operator and .equals() method are meant for comparison only. But there are few differences :

  • == operator never throws NullPointerException whereas .equals() method can throw NullPointerException.
  • == is responsible for type compatibility check at compile time whereas .equals() method will never worry about the types of both the arguments.

Lets have a look on the programs for better understanding:

 
// Java program to illustrate enum members comparison
class EnumDemo {
	public enum Day { MON,
					TUE,
					WED,
					THU,
					FRI,
					SAT,
					SUN }
	public static void main(String[] args)
	{
		Day d = null;

		// Comparing an enum member with null
		// using == operator
		System.out.println(d == Day.MON);

		// Comparing an enum member with null
		// using .equals() method
		System.out.println(d.equals(Day.MON));
	}
}

Output:

false
Exception in thread "main" java.lang.NullPointerException

Explanation: In the above program, we are comparing an enum member with a null. once we use == operator for comparison, then we aren't getting any Exception whereas once we use .equals() method then we are becoming NullPointerException.
Therefore we will conclude that once we use == operator for enum member comparison, then it doesn't throw any Exception but .equals() method throw an Exception.

Another Example:

// Java program to illustrate enum members comparison
class EnumDemo {
	public enum Day { MON,
					TUE,
					WED,
					THU,
					FRI,
					SAT,
					SUN }
	public enum Month { JAN,
						FEB,
						MAR,
						APR,
						MAY,
						JUN,
						JULY }
	public static void main(String[] args)
	{
		// Comparing two enum members which are from different enum type
		// using == operator
		System.out.println(Month.JAN == Day.MON);

		// Comparing two enum members which are from different enum type
		// using .equals() method
		System.out.println(Month.JAN.equals(Day.MON));
	}
}

Output:

error: incomparable types: Month and Day

Explanation: 

 

Submit Your Programming Assignment Details