There are two ways for making comparison of enum members :
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 :
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:
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.