Java Enums
An enum (short for enumeration) is a special type that represents a fixed set of named constants. When a value can only ever be one of a small, known list, such as the days of the week or the states of an order, an enum makes your code clearer and safer than using plain strings or numbers.
Creating and using an enum
You declare an enum with the enum keyword followed by a list of constants, written in uppercase by convention. Each constant is a ready-made object of that enum type. Because the set is fixed, the compiler stops you from ever assigning a value outside the list.
A basic enum
enum Level {
LOW,
MEDIUM,
HIGH
}
public class Main {
public static void main(String[] args) {
Level current = Level.MEDIUM;
System.out.println(current); // MEDIUM
if (current == Level.MEDIUM) {
System.out.println("Halfway there");
}
}
}Enums in a switch
Enums pair naturally with switch statements. Because the compiler knows every possible constant, it can even warn you when you forget to handle one. Inside the switch you refer to constants by their name only, without the enum prefix.
Switching on an enum
enum Level {
LOW, MEDIUM, HIGH
}
public class Main {
public static void main(String[] args) {
Level level = Level.HIGH;
switch (level) {
case LOW:
System.out.println("Take it easy");
break;
case MEDIUM:
System.out.println("Steady pace");
break;
case HIGH:
System.out.println("Full speed");
break;
}
// Output: Full speed
}
}Looping over the values
Every enum automatically gets a values() method that returns an array of all its constants, and an ordinal() method that gives each constant's position starting from zero. These are handy for listing options or building menus.
Listing every constant
enum Level {
LOW, MEDIUM, HIGH
}
public class Main {
public static void main(String[] args) {
for (Level l : Level.values()) {
System.out.println(l + " is at position " + l.ordinal());
}
// LOW is at position 0
// MEDIUM is at position 1
// HIGH is at position 2
}
}Handy built-in enum methods
- Use an enum when the full set of valid values is known ahead of time and will rarely change.
- Enums are type safe, so an invalid value cannot slip in through a typo.
- They read better than magic numbers or loose strings scattered through your code.
- Enums can also hold fields, constructors, and methods for more advanced cases.
Exercise: Java Enums
What is a Java enum primarily used to represent?