An enum in Java is a special data type that defines a fixed set of named constants, such as days of the week or compass directions. It provides a type-safe way to represent a group of predefined values, making code more readable and less error-prone than using plain integers or strings.
What Is an Enum and Why Use It?
Before enums were introduced in Java 5, developers often used int constants or String constants to represent fixed sets of values. For example:
public static final int MONDAY = 1;
public static final int TUESDAY = 2;
This approach had problems: you could accidentally pass 3 or "monday" to a method expecting a day, and there was no compile-time checking. Enums solve this by creating a distinct type. Here is a simple enum declaration:
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Now a method can accept a Day parameter, and the compiler will reject any value that is not one of the seven constants. This catches bugs early and makes the code self-documenting.
Enum Syntax and Basic Usage
An enum is declared with the enum keyword, followed by the name and a list of constants separated by commas. The constants are implicitly public static final fields of the enum type. You can use them like this:
Day today = Day.MONDAY;
if (today == Day.MONDAY) {
System.out.println("Start of the week");
}
Enums can also be used in switch statements, which is a common and clean pattern:
switch (day) {
case MONDAY:
System.out.println("Work day");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekend");
break;
default:
System.out.println("Midweek");
}
Note that in a switch, you refer to the constants without the enum name (just MONDAY, not Day.MONDAY).
Enums with Fields, Constructors, and Methods
Enums can be much more than simple lists. You can add fields, constructors, and methods to each constant. For example, consider a planet enum with mass and radius:
public enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6),
EARTH(5.976e+24, 6.378e6);
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 getMass() { return mass; }
public double getRadius() { return radius; }
}
Each constant is created with its own values when the enum is loaded. You can also override methods in individual constants, which is useful for behavior that differs per value. For instance:
public enum Operation {
PLUS { double apply(double x, double y) { return x + y; } },
MINUS { double apply(double x, double y) { return x - y; } };
abstract double apply(double x, double y);
}
This pattern is called constant-specific method implementation. It allows each enum constant to define its own behavior.
Built-in Methods: values(), valueOf(), and ordinal()
Every enum in Java automatically inherits from java.lang.Enum, which provides several useful methods:
values()– returns an array of all constants in the order they are declared.valueOf(String name)– returns the enum constant with the exact name, throwingIllegalArgumentExceptionif not found.ordinal()– returns the zero-based position of the constant in the declaration.name()– returns the constant’s name as a string.
Example:
Day[] days = Day.values();
for (Day d : days) {
System.out.println(d + " at index " + d.ordinal());
}
Day monday = Day.valueOf("MONDAY");
Note that ordinal() is tied to the declaration order; if you reorder constants, the ordinal values change. Avoid relying on it for persistence or logic that needs stability.
EnumSet and EnumMap: Specialized Collections
Java provides two specialized collection classes for enums: EnumSet and EnumMap. EnumSet is a high-performance Set implementation that uses a bit vector, making it very fast and memory-efficient. It is ideal for representing subsets of an enum:
EnumSet<Day> weekend = EnumSet.of(Day.SATURDAY, Day.SUNDAY);
if (weekend.contains(today)) {
System.out.println("It's the weekend!");
}
EnumMap is a Map implementation optimized for enum keys. It is implemented as an array internally, so lookups are fast and the iteration order matches the enum’s declaration order:
EnumMap<Day, String> schedule = new EnumMap<>(Day.class);
schedule.put(Day.MONDAY, "Gym");
schedule.put(Day.FRIDAY, "Movie night");
Both classes are part of the Java Collections Framework and are generally preferred over HashMap or HashSet when working with enums because of their performance and type safety.
Common Pitfalls and Best Practices
Enums are straightforward, but there are a few mistakes to avoid:
- Comparing with
==vsequals(): Since enum constants are singletons, you can safely use==for comparison. It is both faster and null-safe. Usingequals()also works but is unnecessary. - Using
ordinal()for logic: As mentioned, ordinals change if you reorder constants. Instead, store an explicit field if you need a stable identifier. - Not handling
valueOf()exceptions:valueOf()throwsIllegalArgumentExceptionfor invalid names. Use a try-catch or a lookup map if you need to parse user input. - Overcomplicating with too many fields: While enums can hold data, if you find yourself adding many fields and methods, consider whether a regular class with instances would be more appropriate.
- Forgetting that enums are classes: You cannot extend an enum, and an enum cannot extend another class (because it already extends
Enum). But it can implement interfaces.
One common misconception is that enums are only for simple lists. In reality, they are full-featured classes that can encapsulate behavior and data, making them powerful tools for domain modeling.
Enums vs. Alternatives: When to Use What
Enums are not always the right choice. Here is a quick comparison with alternatives:
- Enums vs. int constants: Enums are type-safe, readable, and can carry behavior. Use enums unless you are working with legacy code or a very simple set that is unlikely to change.
- Enums vs. String constants: Strings are not type-safe and can be misspelled. Enums are preferred for fixed sets.
- Enums vs. a class with static final instances: This is similar, but enums provide built-in features like
values(),valueOf(), and switch support. Use enums for a fixed set of constants. - Enums vs. collections: If the set of values is dynamic (e.g., loaded from a database), use a
SetorListinstead of an enum.
In practice, enums are the go-to solution for any fixed set of related constants, such as status codes, directions, or configuration keys.
Frequently Asked Questions
Can an enum have a constructor?
Yes, an enum can have a constructor, but it cannot be called directly. The constructor is invoked implicitly when each constant is created. For example, Planet.EARTH calls the constructor with the specified mass and radius. The constructor must be private or package-private; it cannot be public or protected.
Can I use an enum in a switch statement?
Yes, enums work perfectly in switch statements. You use the constant names without the enum type prefix. The switch will compile to a lookup table, making it efficient. This is one of the most common uses of enums.
How do I convert a String to an enum?
Use the static valueOf(String) method: Day d = Day.valueOf("MONDAY");. It is case-sensitive and throws IllegalArgumentException if the string does not match any constant. If you need case-insensitive parsing, iterate over values() and compare with equalsIgnoreCase().
Can an enum implement an interface?
Yes, an enum can implement one or more interfaces. This is useful when you want different constants to provide different implementations of the interface methods. For example, you could have an Operation enum that implements a BinaryOperator interface.
What is the difference between name() and toString()?
By default, name() and toString() return the same string: the constant’s name. However, toString() can be overridden to return a more user-friendly representation, while name() is final and always returns the exact identifier. For example, you might override toString() to return “Monday” instead of “MONDAY”.
Are enums thread-safe?
Yes, enum constants are created once when the enum class is loaded, and they are effectively immutable. The JVM guarantees that each constant is a singleton, so there is no need for synchronization when accessing them. This makes enums a good choice for implementing singletons.
Related
- Cell Counting and Viability: Methods Explained
- Split String SQL Server: Best Methods
- Google Sheets Split Cell Into Two: 3 Easy Ways
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Replace Shortcut: Use Ctrl+H and Find & ReplaceIn Excel for Microsoft 365 on Windows, press Ctrl+H to open Find and Replace on the Replace tab.…
- What Column Number Is JJ in Excel?Column JJ is column number 270 in Excel. The quickest way to verify it in a worksheet is…
- Can You Insert a Page Break in Excel? Yes, Here’s HowYes. In Excel for Microsoft 365 on Windows, select the row below or the column to the right…
- Number Rows in Excel When FilteredTo number only the rows currently visible after filtering, put a SUBTOTAL formula in your numbering column and…
- How to Insert a Page Break in Word for Windows and MacTo start a new page in Word, place the cursor where the next page should begin and press…
- Count DISTINCT in T-SQL: Syntax and ExamplesThe COUNT(DISTINCT column_name) expression in T-SQL returns the number of unique, non-NULL values in a column or expression.…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.