Accessing Enum Constants
What you'll learn: How to reference enum values in your code and compare them correctly.
Referencing Enum Values
Now that you know enums are public, static, and final constants, you need to know how to actually use them in code. You access enum constants using the same syntax as any static field: ClassName.VALUE.
enum Day {
MONDAY, TUESDAY, WEDNESDAY
}
// Accessing enum constants
Day today = Day.MONDAY;
Day tomorrow = Day.TUESDAY;
The syntax is exactly like accessing a static constant from a class—because that's essentially what enum values are under the hood.
Comparing Enums: Use ==
Since each enum constant is a unique, final object that exists exactly once in memory, you can (and should) use == to compare enums:
Day day1 = Day.MONDAY;
Day day2 = Day.MONDAY;
if (day1 == day2) { // Recommended: fast reference comparison
System.out.println("Same day!");
}
You can also use .equals(), but it's unnecessary. The == operator works perfectly because Java guarantees only one instance of each enum constant exists:
if (day1.equals(day2)) { // Works, but == is preferred
System.out.println("Same day!");
}
Think of it this way: Enum constants are like unique name tags. There's only one "MONDAY" tag in existence, so you can simply check if two variables point to the same tag using ==.
Why == Is Better for Enums
Using == is faster (no method call), null-safe (won't throw NullPointerException if one variable is null), and more idiomatic for enum comparisons.
Key Takeaway: Access enum constants with ClassName.VALUE syntax and compare them using == for the most efficient, readable code.