Yes, Java has enums. They were introduced in Java 5 (2004) as a full language feature, not just a library or pattern. A Java enum is a special class type that defines a fixed set of named constants, and it is far more powerful than enums in older languages like C or C++ because each constant can carry its own data and behavior.
What an Enum Actually Is in Java
In Java, an enum is declared with the enum keyword. The simplest form looks like this:
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Behind the scenes, the compiler turns this into a final class that extends java.lang.Enum. Each constant (MONDAY, TUESDAY, etc.) is a public static final instance of that class. That means you cannot create new instances with new Day() — the enum constructor is private by default. This gives you type safety: a method that takes a Day parameter will only accept one of the seven defined values, never an arbitrary string or integer.
Why Enums Are More Than Named Constants
Unlike C-style enums that are just integers, Java enums are objects. You can add fields, constructors, and methods directly to an enum. For example, you can associate a description or a numeric code with each constant:
public enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6),
EARTH(5.976e+24, 6.37814e6);
private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double surfaceGravity() {
return 6.67300E-11 * mass / (radius * radius);
}
}
This example is from the official Oracle Java tutorial. Each enum constant is created once when the class loads, with the constructor arguments you provide in the declaration. You can then call Planet.EARTH.surfaceGravity() to get a real computed value. This is the key advantage over using a String or int constant: the data travels with the constant, and the compiler checks that you use a valid constant.
Built-In Methods Every Enum Has
Because every enum implicitly extends java.lang.Enum, it inherits several useful methods:
values()— returns an array of all constants in declaration order. ForDay, it returns{MONDAY, TUESDAY, ...}.valueOf(String name)— returns the constant with that exact name, throwingIllegalArgumentExceptionif no match exists.name()— returns the constant’s name as a string, exactly as declared.ordinal()— returns the zero-based position of the constant in the declaration. Use it sparingly; it changes if you reorder constants.compareTo(Enum other)— compares by ordinal.toString()— by default returns the same asname(), but you can override it for a friendlier display.
You can also iterate over an enum easily: for (Day d : Day.values()) { ... }. This is common for building dropdown lists or validating input.
Switch Statements and Enums Work Together
Enums are the only reference type that works directly in a switch statement (before Java 21, which added pattern matching for other types). The syntax is clean:
switch (day) {
case MONDAY:
System.out.println("Start of work week");
break;
case FRIDAY:
System.out.println("Almost weekend");
break;
default:
System.out.println("Midweek");
}
In modern Java (14+), you can use the arrow syntax with no break:
switch (day) {
case MONDAY, FRIDAY -> System.out.println("Work days");
case SATURDAY, SUNDAY -> System.out.println("Weekend");
default -> System.out.println("Midweek");
}
One common mistake is using Day.MONDAY inside a case label — you must use the unqualified MONDAY because the switch expression already knows the enum type.
Common Problems and How to Avoid Them
Three issues trip up beginners and even experienced developers:
- Using
ordinal()for persistence or logic. If you insert a new constant in the middle, all ordinals shift, silently breaking stored data or comparisons. Instead, store thename()string or an explicitidfield. - Assuming
valueOf()is case-insensitive. It is not.Day.valueOf("monday")throws an exception. If you need case-insensitive lookup, iteratevalues()and compare withequalsIgnoreCase(). - Adding too much logic inside the enum. Enums are classes, so it’s tempting to put business rules there. That’s fine for small, cohesive behavior (like
Planet.surfaceGravity()), but if the logic grows, extract it to a separate service class to keep the enum readable.
Another subtle issue: enums are singletons per classloader. If you serialize an enum and deserialize it in a different JVM, you get the same instance — this is guaranteed by the spec. But if you use multiple classloaders (common in application servers), you can end up with two different Day classes, and constants from one won’t equal constants from the other. This is rare but worth knowing if you work in enterprise environments.
Enums vs. Constants vs. Maps
When should you use an enum instead of a static final int or a Map? Here’s a practical guide:
- Use an enum when the set of values is fixed and known at compile time — days of the week, order statuses, HTTP methods, card suits. You get type safety and can attach behavior.
- Use
static finalconstants when the values are truly just numbers or strings with no associated behavior, and when you don’t need type safety. For example, a timeout value of 5000 milliseconds. - Use a
Mapwhen the set of values is dynamic, loaded from a database or config file, or when the mapping changes at runtime. An enum cannot be extended at runtime.
A common misconception is that enums are slower than int constants. In practice, the JVM optimizes enum comparisons and switch statements very well; the performance difference is negligible for almost all applications. The real cost is in memory — each enum constant is a full object, but with a handful of constants that’s irrelevant.
Enums in Modern Java: Records, Sealed Types, and More
Java has evolved, and enums have integrated with newer features. Since Java 16, you can combine an enum with a record for immutable data. For example:
public enum Operation {
PLUS("+"), MINUS("-"), TIMES("*");
private final String symbol;
Operation(String symbol) { this.symbol = symbol; }
public String symbol() { return symbol; }
}
Java 17 introduced sealed classes, and enums are implicitly sealed — you cannot extend them. This makes them a natural fit for exhaustive pattern matching. In Java 21, you can use a switch expression with an enum and the compiler will verify that you’ve handled all cases, eliminating the need for a default branch if you cover every constant.
Another useful pattern is the enum singleton. Because the JVM guarantees that an enum constant is instantiated only once, you can use a single-element enum as a thread-safe singleton:
public enum Singleton {
INSTANCE;
public void doSomething() { ... }
}
This is the recommended way to implement a singleton in Java, as it handles serialization and thread safety without extra code.
Frequently Asked Questions
Can I add methods to an enum?
Yes, you can add any number of methods, fields, and constructors. Each constant can even override a method individually by providing its own body in the declaration, though that’s rarely needed. The methods are just like regular class methods.
Can I compare enums with ==?
Yes, you can and should use == to compare enum constants. Because each constant is a single instance, reference equality (==) works and is faster than equals(). The equals() method also works but is redundant.
How do I convert a string to an enum?
Use Day.valueOf("MONDAY") for an exact match. If the string might be null or invalid, catch IllegalArgumentException or use a loop with equalsIgnoreCase() for case-insensitive matching. There is no built-in case-insensitive method.
Can I extend an enum?
No. Enums are final by default, and the language forbids extending them. If you need more values, you must modify the enum itself or use a different design like an interface with implementations.
Are enums thread-safe?
Yes, enum constants are created once during class initialization, which is thread-safe by the JVM’s class-loading mechanism. You don’t need to synchronize access to the constants themselves. However, if you add mutable fields to an enum, you must handle thread safety for those fields yourself.
What’s the difference between name() and toString()?
By default, they return the same string — the constant’s name. But name() is final and cannot be overridden, while toString() can be overridden to return a friendlier label, like “Monday” instead of “MONDAY”. Use name() for programmatic lookups and toString() for display.
Alternatives to Enums in Java
If enums don’t fit your situation, you have a few alternatives. A Map<String, SomeType> is the most flexible for dynamic sets. A Set of constants can enforce uniqueness but not type safety. For a fixed set of integer codes, you can use static final int constants, but you lose type safety and the ability to attach behavior. For a fixed set of string values with associated methods, a sealed interface with a fixed set of implementations (Java 17+) gives you similar compile-time exhaustiveness but allows more complex behavior than an enum. In practice, enums cover the vast majority of fixed-value scenarios, and the alternatives are only needed when the set must change at runtime or when you need multiple inheritance of behavior.
Related
- Google Spreadsheet Counter: How to Count Cells
- Split String in Power Automate: 3 Ways
- What Does String Do in Java? A Clear Guide
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Correlation Analysis in Excel: Methods and ExamplesTo run a correlation analysis in Excel, place two comparable numeric variables in separate columns and use =CORREL(A2:A6,B2:B6),…
- Flash Fill in Excel: Purpose, Examples, and LimitsFlash Fill in Excel recognizes a pattern in data you enter and fills the remaining cells to match…
- Multiple SUMIFS in Google Sheets: Criteria and ExamplesYes. In Google Sheets, use one SUMIFS for conditions that must all be true, and add separate SUMIFS…
- How to Close Excel Without Saving ChangesTo close Excel without keeping your latest edits in the desktop app, close the workbook or exit Excel,…
- How to Clean an Excel File to Reduce Its SizeTo reduce an Excel file’s size, save a copy, remove unnecessary data and formatting, compress pictures, and delete…
- Edit Conditional Formatting in Google SheetsTo edit conditional formatting in Google Sheets, select a cell covered by the rule, open Format > Conditional…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.