“enum” or “enumeration” is a special data type in Java that contains a fixed or variable set of constants or methods. These constants represent a fixed number of possible values for a variable. Developers use enums when they know all possible options at compile time. Some of the best examples of enums include “weekdays”, “cardinal directions”, “Planets”, and so on. While working with enums, a commonly performed operation is “comparing enum members”, which can be done via different methods and operators.
This Java guide will teach several methods to compare enum members in Java.
How to Compare Enum Members in Java
To compare Enum members in Java, you can use the “==” operator, the “equals()” method, or the compareTo() method. Let’s discuss the workings of each approach with examples.
How to Compare Enum Members Using “==” Operator
The “==” performs the reference equality comparison and retrieves one of two possible outcomes: “True” or “False”. Also, it retrieves “False” if an enum is compared with a “null” value. While using the “==” operator for comparison, ensure that the data types of the given enums are the same. Otherwise, you will encounter a compile-time error.
Example 1: Compare Enums of the Same Type Using “==” Operator
Let’s compare a couple of Enums of the same type using the “==” operator:
package exp;
public class ShirtSize {
public enum SizeChart {
S, M, L, XL
}
public static void main(String args[]) {
SizeChart sc1 = SizeChart.S;
SizeChart sc2 = SizeChart.M;
SizeChart sc3 = SizeChart.L;
SizeChart sc4 = SizeChart.XL;
SizeChart sc5 = SizeChart.S;
if (sc1 == sc2) {
System.out.println(sc1 + " is equal to " + sc2);
} else {
System.out.println(sc1 + " is not equal to " + sc2);
}
if (sc1 == sc3) {
System.out.println(sc1 + " is equal to " + sc3);
} else {
System.out.println(sc1 + " is not equal to " + sc3);
}
if (sc1 == sc4) {
System.out.println(sc1 + " is equal to " + sc4);
} else {
System.out.println(sc1 + " is not equal to " + sc4);
}
if (sc1 == sc5) {
System.out.println(sc1 + " is equal to " + sc5);
} else {
System.out.println(sc1 + " is not equal to " + sc5);
}
}
}
In this code,
- We create an enum “SizeChart” that contains four different (fixed) shirt sizes: S (small), M (medium), L (large), and XL (extra large).
- In the main() method, we create five instances of the “SizeChart” enum and assign them different members (for comparison).
- Finally, we utilize several if-else statements to compare the enum members.
The output confirms that the “==” operator performs the comparison appropriately:
Note: The “==” performs a case-sensitive comparison, so use this operator carefully to avoid unwanted/ unexpected results.
Example 2: Compare Enums of Different Data Types Using “==” Operator
If you try to compare enums of different data types using the “==” operator, you will encounter a compile-time error stating “Incompatible operand types”. Here is a practical demonstration of this error:
package exp;
public class ShirtSize {
public enum SizeChart {
S, M, L, XL
}
public enum SizeChart1 {
S, M, L, XL
}
public static void main(String args[]) {
SizeChart sc1 = SizeChart.S;
SizeChart1 sc2 = SizeChart1.S;
if (sc1 == sc2) {
System.out.println(sc1 + " is equal to " + sc2);
} else {
System.out.println(sc1 + " is not equal to " + sc2);
}
}
}
Here,
- We create two enums, each consisting of four members: S, M, L, and XL.
- Next, we create an object/instance of each enum in the main() method.
- After this, when we try to compare the enum members of different data types we get an unresolved compilation error, as shown below:
The output confirms that you can’t compare the enum members of different types using the “==” operator.
How to Compare Enum Members Using the “equals()” Method
The equals() is an easy-to-use and effective method that compares the enum members based on their values. This method doesn’t check the reference of the enums. Therefore, it can compare the enums of different types as well.
Example 1: Compare Enums of the Same Type Using the “equals()” Method
In this example, we will compare Enums of the same type using the “equals()” method:
package exp;
package exp;
public class ShirtSize {
public enum SizeChart {
SMALL, MEDIUM, LARGE, XLARGE
}
public static void main(String args[]) {
SizeChart sc1 = SizeChart.SMALL;
SizeChart sc2 = SizeChart.MEDIUM;
SizeChart sc3 = SizeChart.LARGE;
SizeChart sc4 = SizeChart.XLARGE;
SizeChart sc5 = SizeChart.SMALL;
if (sc1.equals(sc2)) {
System.out.println(sc1 + " is equal to " + sc2);
} else {
System.out.println(sc1 + " is not equal to " + sc2);
}
if (sc1.equals(sc3)) {
System.out.println(sc1 + " is equal to " + sc3);
} else {
System.out.println(sc1 + " is not equal to " + sc3);
}
if (sc1.equals(sc4)) {
System.out.println(sc1 + " is equal to " + sc4);
} else {
System.out.println(sc1 + " is not equal to " + sc4);
}
if (sc1.equals(sc5)) {
System.out.println(sc1 + " is equal to " + sc5);
} else {
System.out.println(sc1 + " is not equal to " + sc5);
}
}
}
In this code,
- We create an enum with four constants: SMALL, MEDIUM, LARGE, and XLARGE.
- After this, we create five instances of the enum and initialize them with different enum members.
- Finally, we compare the enum members using the equals() method and print the result for each comparison on the console.
Note: Use the equals() method carefully, as it throws a NullPointerException if an enum is compared with a Null value.
Example 2: Compare Enums of Different Types Using the “equals()” Method
The equals() method performs the comparison irrespective of the references. Therefore you can use it to compare the enums of different types without facing any error. However, this method retrieves false for incomparable types, as demonstrated below:
package exp;
public class ShirtSize {
public enum SizeChart {
SMALL, MEDIUM, LARGE, XLARGE
}
public enum AvailableSize {
SMALL, MEDIUM, LARGE
}
public static void main(String args[]) {
SizeChart sc1 = SizeChart.SMALL;
AvailableSize sc2 = AvailableSize.SMALL;
if (sc1.equals(sc2)) {
System.out.println(sc1 + " is equal to " + sc2);
} else {
System.out.println(sc1 + " is not equal to " + sc2);
}
}
}
In this code,
- We create two enums: “SizeChart” and “AvailableSize”. Both contain several constants.
- In the main() method, we create an object/instance of each enum and initialize them with a value “SMALL”.
- Finally, we use the equals() method to compare the enums of different types:
The output confirms that we didn’t get any compile-time error. However, the output is not as per our expectations. So, we can conclude that the equals() method doesn’t throw any exception at compile or run time. Instead, it returns false for the incompatible enum types.
How to Compare Enum Members Using the “compareTo()” Method
The compareTo() method performs the lexicographical comparisons(based on the Unicode values characters/letters). You can utilize this approach to compare enum members of the same type. This method throws a compile time error if you try to compare enums of different types.
Example 1: Compare Enums of the Same Types Using the “compareTo()” Method
In the below-stated example, we create an enum with four constants: SMALL, MEDIUM, LARGE, and XLARGE:
package exp;
public class ShirtSize {
public enum SizeChart {
SMALL, MEDIUM, LARGE, XLARGE
}
public static void main(String args[]) {
SizeChart sc1 = SizeChart.MEDIUM;
SizeChart sc2 = SizeChart.LARGE;
if (sc1.compareTo(sc2) == 0) {
System.out.println(sc1 + " is equal to " + sc2);
} else if (sc1.compareTo(sc2)< 0) {
System.out.println(sc1 + " is smaller than " + sc2);
} else {
System.out.println(sc1 + " is larger than " + sc2);
}
}
}
Here,
- We create a couple of instances of the “SizeChart” enum and initialize them with different enum members.
- Up next, we use the compareTo() method to compare the size “MEDIUM” with the size “LARGE”.
The output shows that the “sc1” is smaller than “sc2”:
Note: It throws a NullPointerException if an enum is compared with a null value.
Example 2: Compare Enums of Different Types Using the “compareTo()” Method
This time, we create two enums to check how the compareTo() method deals with different types:
package exp;
public class ShirtSize {
public enum SizeChart {
SMALL, MEDIUM, LARGE, XLARGE
}
public enum AvailableSize {
SMALL, MEDIUM, LARGE
}
public static void main(String args[]) {
SizeChart sc1 = SizeChart.SMALL;
AvailableSize sc2 = AvailableSize.SMALL;
if (sc1.compareTo(sc2)== 0) {
System.out.println(sc1 + " is equal to " + sc2);
} else {
System.out.println(sc1 + " is not equal to " + sc2);
}
}
}
We face a compile time error when we try to compare the members of different enums:
Comparative Analysis: “==” Vs “equals()” Vs “compareTo()”
The following points illustrate the performance comparison of the discussed methods:
- The “==” operator is null safe while the “equals()” and “compareTo()” methods throw a NullPointerException if an enum is compared with a null value.
- For a single comparison, the “==” operator is generally faster than the “equals()” and “compareTo()” methods. However, in the case of multiple/repeating enum comparisons results can be different.
- The “==” operator and “compareTo()” method throw a compile-time error if you try to compare enums of different types. However, the “equals()” method doesn’t throw any error, instead it simply retrieves “False” for incomparable/incompatible enum types.
That’s all about enum members comparison in Java.
Final Thoughts
To compare enum members in Java, the “==” operator, the “equals()” method, and the “compareTo()” method are used. The “equals()” and “compareTo()” methods compare the enum members lexicographically. While the “==” operator compares the enums based on reference. All these approaches have their own pros and cons as discussed in this article. You can utilize any of the mentioned approaches to compare enum members according to your needs/preferences.