Enums: Defining Fixed Sets of Constants
An Enum (short for "Enumeration") is a special "class" that represents a group of constants—unchangeable variables that don't change, like days of the week, colors, or game states.
Using Enums makes your code much more readable and prevents bugs caused by "magic strings" or random numbers.
1. Basic Syntax
You define an Enum using the enum keyword. By convention, enum constants are written in UPPERCASE.
enum Level {
LOW,
MEDIUM,
HIGH
}
2. Why Use Enums?
Instead of using a String where someone could make a typo (like "Loow" instead of "Low"), Enums force you to choose from a predefined list.
Level myVar = Level.MEDIUM;
// Enums work perfectly with Switch statements!
switch(myVar) {
case LOW:
System.out.println("Low Level");
break;
case MEDIUM:
System.out.println("Medium Level");
break;
case HIGH:
System.out.println("High Level");
break;
}
3. Enums are "Classes"
In Java, Enums are more powerful than in other languages. They can have fields, constructors, and methods.
enum Status {
START(1), RUNNING(2), STOPPED(0);
private final int code;
// Enum constructor (always private or package-private)
Status(int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
đź’» Full Practical Example: The Game State
Copy this into your project to see how to manage application flow cleanly:
enum GameState {
MENU, PLAYING, PAUSED, GAMEOVER
}
public class GameEngine {
private GameState currentState;
public GameEngine() {
this.currentState = GameState.MENU; // Initial state
}
public void setState(GameState newState) {
this.currentState = newState;
System.out.println("Game is now in " + currentState + " mode.");
}
public static void main(String[] args) {
GameEngine engine = new GameEngine();
engine.setState(GameState.PLAYING);
// Loop through all possible states
System.out.println("\nAll possible states:");
for (GameState s : GameState.values()) {
System.out.println("- " + s);
}
}
}
4. Built-in Methods
values(): Returns an array of all constants in the enum.ordinal(): Returns the position (index) of a constant (starting at 0).valueOf(String): Converts a string into the corresponding enum constant.
đź’ˇ Challenge: The Traffic Light
- Create an enum called
TrafficLightwithRED,YELLOW, andGREEN. - Give each constant a
durationfield (e.g., RED is 30, GREEN is 45). - Create a method inside the enum that returns the next light (e.g., if it's RED, return GREEN).
- In
main, print the duration of aYELLOWlight.