Java Enums
A Java enum is a special type used to define a fixed set of named constants. Use an enum when a variable should only hold one value from a known list, such as days, sizes, states, or roles.
Enums make code clearer than using plain strings or numbers because the compiler can check that only valid values are used.
Basic Enum Syntax
Create an enum with the enum keyword, followed by a list of constants. By convention, enum constants are written in uppercase.
enum Level {
LOW,
MEDIUM,
HIGH
}
public class Main {
public static void main(String[] args) {
Level currentLevel = Level.MEDIUM;
System.out.println("Current level: " + currentLevel);
switch (currentLevel) {
case LOW:
System.out.println("Low priority");
break;
case MEDIUM:
System.out.println("Normal priority");
break;
case HIGH:
System.out.println("High priority");
break;
}
System.out.println("All levels:");
for (Level level : Level.values()) {
System.out.println(level);
}
}
}
Output:
Current level: MEDIUM
Normal priority
All levels:
LOW
MEDIUM
HIGH
The variable currentLevel can only hold one of the constants declared in Level. This prevents mistakes such as assigning "Medium", "MED", or another spelling that the program does not understand.
Using Enums With Switch
Enums work well with switch because there is a small, known set of possible values. Inside the switch, write the enum constant names without the enum type prefix. For example, use case HIGH:, not case Level.HIGH:.
The method values() returns all constants from the enum in the order they were declared. This is useful when you need to print choices, validate menu options, or loop through all possible states.
Enums Can Have Fields And Methods
An enum can store extra information for each constant. To do this, put values in parentheses after each constant, add fields, and define an enum constructor. Enum constructors are used internally when Java creates the enum constants.
enum Planet {
MERCURY("Mercury", 3.7),
EARTH("Earth", 9.8),
JUPITER("Jupiter", 24.8);
private final String displayName;
private final double gravity;
Planet(String displayName, double gravity) {
this.displayName = displayName;
this.gravity = gravity;
}
public String getDisplayName() {
return displayName;
}
public double getGravity() {
return gravity;
}
}
public class Main {
public static void main(String[] args) {
for (Planet planet : Planet.values()) {
System.out.println(planet.getDisplayName() + ": " + planet.getGravity() + " m/s^2");
}
Planet home = Planet.EARTH;
System.out.println("Home planet is " + home.getDisplayName());
}
}
Output:
Mercury: 3.7 m/s^2
Earth: 9.8 m/s^2
Jupiter: 24.8 m/s^2
Home planet is Earth
Each Planet constant has its own displayName and gravity. The fields are marked final because enum constants normally represent stable values that should not change while the program runs.
Useful Enum Methods
| Method | Meaning |
|---|---|
values() |
Returns an array of all enum constants. |
name() |
Returns the exact constant name, such as HIGH. |
ordinal() |
Returns the zero-based position of the constant. |
valueOf("HIGH") |
Returns the enum constant with that exact name. |
Use ordinal() carefully. It depends on declaration order, so changing the enum order can change the numbers. For most programs, a named field is clearer and safer than relying on the ordinal value.
When To Use Enums
- Use an enum for a fixed set of choices, such as
SMALL,MEDIUM, andLARGE. - Use an enum instead of unrelated string constants when invalid spelling would cause bugs.
- Use fields and methods when each constant needs extra data or behavior.
- Do not use an enum when values must be created freely by the user at runtime.
Common Mistakes
- Forgetting the semicolon after the constant list when the enum also has fields, constructors, or methods.
- Trying to create enum objects with
new. Enum constants are created by Java. - Using
valueOf()with the wrong case.valueOf("high")does not matchHIGH. - Storing user-facing text only in the constant name instead of using a separate field like
displayName.
Takeaway: enums give names, type safety, and optional data to a fixed set of choices in your Java programs.
