Java ยท Chapter 30 of 42
Java Enums
An enum is a special type representing a fixed set of constants, such as days of the week or directions. Enums improve type safety compared to using plain integers or strings for fixed categories.
Java enums are actually full classes โ they can have fields, constructors, and methods, not just a list of names.
Syntax
enum Level {
LOW, MEDIUM, HIGH
}Declaring and using enums
An enum is declared with the `enum` keyword and a list of constant names. You typically use it in a switch statement or comparison.
Enums with fields and methods
Enums can have constructors and fields to attach extra data to each constant, making them more powerful than simple constant lists.
Example 1 (java)
enum Level { LOW, MEDIUM, HIGH }
public class Main {
public static void main(String[] args) {
Level myLevel = Level.MEDIUM;
System.out.println(myLevel);
switch (myLevel) {
case LOW -> System.out.println("Low level");
case MEDIUM -> System.out.println("Medium level");
case HIGH -> System.out.println("High level");
}
}
}Output
MEDIUM
Medium levelmyLevel holds one of the enum's fixed constants and is matched in a switch.
Key points
- enum defines a fixed set of named constants.
- Enums are type-safe alternatives to plain constants.
- Enums can have fields, constructors and methods.
- Enums work well with switch statements.
๐ก Note: Enums improve compile-time safety, since only valid values can be assigned.
