Loading lessons...
Java Enums
Java Enums
An enum is a special class that represents a fixed group of constants, like days of the week or colors.
Declaring an enum
Use the enum keyword and list the constants in uppercase:
enum Level {
LOW,
MEDIUM,
HIGH
}
Using an enum in a switch
Level myVar = Level.MEDIUM;
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;
}
Loop through an enum
for (Level myVar : Level.values()) {
System.out.println(myVar);
}
The values() method returns an array of all enum constants.
Why use enums
- Group related constants together.
- Prevent invalid values, since only the listed constants are allowed.
- Improve readability compared to magic numbers.
Enum vs class
An enum is like a class, but its constants are fixed. You cannot create new values beyond the ones declared.
TL;DR
- Enums hold a fixed set of constants.
- Constants are written in uppercase.
- Use in switch statements and loops.