In Java, an enum is a special data type used to define a fixed set of constants. It is a special kind of Java class that can contain constants, methods and variables, where each enum constant represents a single, unique instance
- Enum constants can be compared using the == operator or the equals() method.
- The equals() method internally uses ==.
- The == operator is preferred because it provides compile-time type safety and avoids NullPointerException.
Key Differences
1. Null Safety
- == never throws NullPointerException
- equals() throws NullPointerException if called on a null reference
2. Type Safety
- == performs compile-time type checking
- equals() does not check type compatibility at compile time
Example 1: Comparing Enum Constants Using == and equals()
This example shows how enum constants are compared using the == operator and the equals() method in different scenarios.
enum Status {
ACTIVE,
INACTIVE
}
public class GFG {
public static void main(String[] args) {
Status s1 = Status.ACTIVE;
Status s2 = Status.ACTIVE;
Status s3 = null;
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s1.equals(s2)); // true
// This will throw NullPointerException
System.out.println(s3.equals(s1));
}
}
Output:
true
false
true
Exception in thread "main" java.lang.NullPointerException
Explanation:
- s1 == s2: true because both refer to the same enum constant.
- s1 == s3: false; the == operator safely handles null.
- s1.equals(s2): true because both constants are equal.
- s3.equals(s1) : throws NullPointerException because equals() is called on a null reference.
Example 2: Type Safety in Enum Comparison
This example shows that == enforces compile-time type safety for enums, while equals() allows comparison and returns false for different enum types.
enum Month {
JAN, FEB
}
enum Day {
MON, TUE
}
public class EnumTypeSafety {
public static void main(String[] args) {
Month m = Month.JAN;
Day d = Day.MON;
System.out.println(m.equals(d)); // false
System.out.println(m == d); // Compilation error: incomparable types
}
}
Output:
false
Compilation error: incomparable types: Month and Day
Explanation:
- m.equals(d) compiles and prints false because the enum types are different.
- m == d causes a compile-time error because == enforces strict type safety and does not allow comparison between different enum types.