Java Enum
In this page:
What is an Enum?
An enum defines a fixed, named set of constant values, like DAY or SUIT, giving you compile-time safety that a variable can only ever hold one of those specific values. Because the compiler restricts a variable of this enum type to only its declared constants, invalid values become impossible rather than just discouraged.
Example: What is an Enum?
enum Day { MONDAY, TUESDAY, WEDNESDAY }
public class Main {
public static void main(String[] args) {
Day today = Day.MONDAY;
System.out.println(today);
}
}
Login to try C/C++/Java/PHP code in the editor
Enum with Fields and Methods
Enum constants can carry their own fields and methods, letting each constant hold associated data (like a planet's mass) and expose behavior specific to that constant. This turns an enum into more than just a labeled constant, effectively giving each value its own mini-object with real behavior.
Example: Enum with Fields and Methods
enum Planet {
EARTH(5.97), MARS(0.64);
final double massInYottagrams;
Planet(double mass) { this.massInYottagrams = mass; }
}
public class Main {
public static void main(String[] args) {
System.out.println(Planet.EARTH.massInYottagrams);
}
}
Login to try C/C++/Java/PHP code in the editor
Iterating over Enums
You can iterate every constant in an enum with EnumType.values(), which returns them as an array in the order they were declared. This is especially useful when you need to populate a dropdown, generate a report, or loop through every possible state a variable could hold.
Example: Iterating over Enums
enum Day { MONDAY, TUESDAY, WEDNESDAY }
public class Main {
public static void main(String[] args) {
for (Day d : Day.values()) {
System.out.println(d);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Enum valueOf and ordinal
valueOf(String) converts a matching string back into its enum constant, throwing IllegalArgumentException if there's no match; ordinal() returns each constant's zero-based declaration position.
Example: Enum valueOf and ordinal
enum Day { MONDAY, TUESDAY, WEDNESDAY }
public class Main {
public static void main(String[] args) {
Day d = Day.valueOf("TUESDAY");
System.out.println(d.ordinal()); // 1: zero-based position
}
}
Login to try C/C++/Java/PHP code in the editor
EnumSet and EnumMap
EnumSet and EnumMap are highly optimized collection implementations built specifically for enum keys, offering better performance than a generic HashSet/HashMap would for the same data.
Example: EnumSet and EnumMap
import java.util.EnumSet;
enum Day { MONDAY, TUESDAY, WEDNESDAY }
public class Main {
public static void main(String[] args) {
EnumSet<Day> weekStart = EnumSet.of(Day.MONDAY, Day.TUESDAY);
System.out.println(weekStart);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: