Comparing enum members in Java
In Java, enum is a special Java type used to define collections of constants. More precisely, a Java enum type is a special kind of Java class. An enum can contain constants, methods etc. enum can be defined as a group of named constant.
There are two ways for making comparison of enum members :
- By using == operator
- By using equals() method
equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method. But the question is if we have two ways for comparing two members of enum, then 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:
false Exception in thread "main" java.lang.NullPointerException
Explanation: In the above program, we are comparing an enum member with a null. When we use == operator for comparison, then we are not getting any Exception whereas when we use .equals() method then we are getting NullPointerException.
Therefore we can conclude that when we use == operator for enum member comparison, then it does not throw any Exception but .equals() method throw an Exception.
error: incomparable types: Month and Day
Explanation:In the above program, we are comparing an enum member with an another enum member. When we use .equals() method for comparison then we are not getting any Compilation Failure(CF) whereas when we use == operator then we are getting Compilation Failure(CF) saying “incomparable types” . Therefore we can conclude that when we use == operator for enum member comparison then it performs type compatibility check at compile time whereas .equals() method will never worry about the types of both the arguments(it will just give “false” for incomparable types).
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.