Comparing enums in Java is straightforward because every enum type implicitly extends java.lang.Enum, which provides built-in methods for equality and ordering. This guide covers the three main ways to compare enums: using ==, using equals(), and using compareTo(). You’ll also learn when each is appropriate, how to handle nulls, and how to avoid common pitfalls.
What You’ll Need
- A Java development environment (JDK 8 or later is fine; examples work on any modern version).
- Basic familiarity with defining and using enums in Java.
Step-by-Step
-
Define an enum for testing. For example:
public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } -
Compare with the
==operator. This is the most common and recommended way to check if two enum variables refer to the same constant. Because enums are singletons (each constant is a single instance),==works reliably and is null-safe when you check for null first.Day today = Day.MONDAY; Day other = Day.MONDAY; if (today == other) { System.out.println("Same day"); } -
Use
equals()for comparison. Theequals()method is inherited fromEnumand behaves exactly like==(it checks reference equality). It’s safe to use, but many developers prefer==because it’s more concise and avoids a method call.if (today.equals(other)) { System.out.println("Same day"); }Note:
equals()will throw aNullPointerExceptionif you call it on a null reference. Always check for null first if the variable might be null. -
Compare enum constants with
compareTo(). Enums implementComparableviaEnum, so you can compare them by their ordinal (declaration order). This returns a negative integer, zero, or a positive integer.Day first = Day.MONDAY; Day second = Day.WEDNESDAY; int result = first.compareTo(second); // result is negative because MONDAY comes before WEDNESDAY -
Use
ordinal()for explicit index comparison. If you need the numeric position of an enum constant, callordinal()(0-based). Comparing ordinals is equivalent to comparing withcompareTo().int index = Day.FRIDAY.ordinal(); // returns 4 -
Handle nulls safely. When comparing variables that could be null, use
Objects.equals()(Java 7+) or check for null explicitly.Day a = null; Day b = Day.MONDAY; if (Objects.equals(a, b)) { // false, no exception } -
Compare enums with different types. You cannot directly compare enums of different types with
==orequals()because they are different classes. The compiler will reject==between incompatible types. If you need to compare by name, usename()ortoString().enum Color { RED, GREEN } enum Size { SMALL, LARGE } // Color.RED == Size.SMALL // compile error -
Use
switchstatements for cleaner comparisons. Java allows switching on enums, which internally usesordinal()and is efficient.switch (today) { case MONDAY: System.out.println("Start of week"); break; case FRIDAY: System.out.println("TGIF"); break; default: System.out.println("Other day"); }
Common Mistakes
- Using
equals()on a null reference – This throwsNullPointerException. Always check for null or useObjects.equals(). - Assuming
compareTo()compares by name – It compares by ordinal (declaration order), not alphabetically. If you need alphabetical order, comparename()strings. - Comparing enums of different types – Attempting
==between different enum types causes a compile error. Evenequals()will return false because the classes differ. - Overriding
equals()orhashCode()in an enum – You cannot override these methods in an enum; the compiler forbids it. If you try, you’ll get a compile error. Use fields and methods instead. - Using
toString()for comparison when you meanname()–toString()can be overridden to return a custom label, whilename()always returns the constant name. Comparing withtoString()may give unexpected results if overridden.
Tips
- Prefer
==overequals()for enums – It’s faster and avoids a method call, and it’s safe because each constant is a singleton. - Use
compareTo()when you need to sort or find min/max – For example,Collections.min(list)works on enums because they areComparable. - If you need a custom ordering, add a field to the enum and compare that field manually, or implement a
Comparator. - In switch statements, use the enum constant name without the enum type prefix (e.g.,
case MONDAY:, notcase Day.MONDAY:). - When storing enums in collections,
HashSetandHashMapwork correctly becausehashCode()is also final and consistent withequals().
Troubleshooting
- Compile error: “incompatible types” when using
==– You’re comparing enums of different types. Usename().equals()or a common interface if needed. - NullPointerException when calling
equals()– The receiver is null. Check for null before calling, or useObjects.equals(a, b). - Your enum comparison returns unexpected order – Remember
compareTo()uses declaration order. If you need a different order, add anintfield and compare that. - Switch statement doesn’t compile – Ensure you’re using the enum type in the switch expression and case labels are unqualified constant names. Also, the enum must be in scope.
- You accidentally overrode
toString()and now comparisons fail – If you compare usingtoString(), it might return a custom string. Usename()instead for the constant’s identifier.
Frequently Asked Questions
- Is it safe to use
==to compare enums? Yes, because each enum constant is a singleton instance. The JVM guarantees only one instance per constant, so==is equivalent toequals()and is the recommended approach. - Can I override
equals()in an enum? No, the compiler prevents overridingequals()andhashCode()in enums. This is intentional to maintain the singleton guarantee. - What’s the difference between
name()andtoString()?name()returns the exact identifier used in the declaration (e.g., “MONDAY”).toString()by default returns the same, but you can override it to return a friendlier label. For comparisons, usename()to avoid surprises. - How do I compare enums alphabetically? Use
a.name().compareTo(b.name())or create aComparatorthat usesname(). - Can I compare an enum to a String? Not directly. You can compare the enum’s
name()ortoString()to a String using.equals(), but the types are different. - Does
compareTo()throw an exception if the enum is null? Yes, callingcompareTo()on a null reference will throwNullPointerException. Always check for null before calling.
Related
- All Mac Shortcuts: The Complete List
- Battery Life Calculations: How to Estimate Runtime
- Dictionary Add or Update in C#: Best Way
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Cell Service in Clementi: What to CheckIf you mean a mobile-phone repair or service business called Excel Cell Service, I can’t reliably confirm that…
- Excel vs CSV: Key Differences and When to Use EachExcel is spreadsheet software and a workbook format; CSV is a plain-text format for rows and columns. Choose…
- Upper Excel Shortcut: How to Capitalize TextExcel has no built-in keyboard shortcut that turns the selected cell’s text into uppercase. With the text maria…
- Track Changes in Word for the Web: A Step-by-Step GuideTo track edits in Word for the web, open the document, select Review > Track Changes, and choose…
- How to Add Consecutive Page Numbers in Microsoft WordTo add consecutive page numbers in Word, choose Insert > Page Number, select where the numbers should appear,…
- Daily Cash Flow Report Template in Excel: Setup and UseA daily cash flow report template in Excel lists each day’s opening cash, money received, money paid, net…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.