Enums
An Enum (short for Enumeration) is a special Java type used to define collections of constants.
Defining an Enum
enum Level {
LOW,
MEDIUM,
HIGH
}
Level myVar = Level.MEDIUM;
Enums in Switch Statements
Enums are often used in switch statements to check for corresponding values.
switch(myVar) {
case LOW:
// ...
break;
}
Enums are Classes
In Java, enums are real classes. They can have attributes and methods!
enum Level {
LOW(1), MEDIUM(5), HIGH(10); // Constructor calls
private final int value; // Field
Level(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
Full Example
Output
Click Run to execute your code
Summary
- Enums represent a fixed set of constants.
- They are type-safe and more readable than integer constants.
- They can have constructors, fields, and methods.
Enjoying these tutorials?