Java Represent a Fixed Set of Choices
An enum models a finite named set of values. It can carry data and behaviour, which is often clearer than scattering string comparisons or unrelated integer codes.
Understand the idea
Enum constants are instances of the enum type. A constructor can associate a value with each constant, and methods can expose the intended meaning. Enum constructors are not public creation points for callers. Use name or an explicit external code deliberately when storing values outside the program; ordinal depends on declaration order and can change when the enum is reorganised.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
public class Main {
enum SessionLength {
SHORT(45), EXTENDED(90);
private final int minutes;
SessionLength(int minutes) { this.minutes = minutes; }
int minutes() { return minutes; }
}
public static void main(String[] args) {
for (SessionLength length : SessionLength.values()) {
System.out.println(length.name() + ":" + length.minutes());
}
}
}
Expected output
SHORT:45
EXTENDED:90Each constant is created with its own duration. values returns the declared constants in order, and the loop accesses the stored minutes through a method. The choice remains type-safe: a caller cannot pass an arbitrary string wherever a SessionLength is required without a deliberate conversion step.
Check the official Java documentation for detailed contracts and supported options.