Declaring enums
- Java course
- Beginner
- Lesson 100/116
- 4 min
Learn constant sets with enum.
Enum: a named set of constants
An enum represents a fixed set of values. It is used for limited options like days of the week, seasons or directions. Each constant is written in uppercase.
enum Day {
MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY, SUNDAY
}An enum is really a special kind of class; its constants are automatically public static final. To assign a constant to a variable you write Day d = Day.MONDAY;. This way typos are caught at compile time, which is safer than using strings.
ordinal and name
Every enum constant has an ordinal number (ordinal()) and a name (name()). The ordinal starts at zero and increases in declaration order.
Day d = Day.WEDNESDAY;
System.out.println(d.ordinal()); // 2
System.out.println(d.name()); // WEDNESDAYordinal() is rarely needed; relying on the number is riskier than using the constant itself. name() returns the string form of the constant, which is useful for logging.
Practice Define a color enum and print it
Define a Color enum with constants RED, GREEN, BLUE. Assign the RED constant to a variable and print it.
Starter code
public class Main {
public static void main(String[] args) {
// Define the Color enum, assign RED, print it
}
}
// Define the Color enum hereSample solution
enum Color { RED, GREEN, BLUE }
// inside main:
Color c = Color.RED;
System.out.println(c);Expected output
RED
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each enum constant to its description
| Term | Meaning |
|---|---|
MONDAY |
First day of week |
SUNDAY |
Last day of week |
WEDNESDAY |
Middle day |
FRIDAY |
Friday |
2 Assign an enum constant
Day d = Day.____;
Day d = Day.MONDAY;
Explanation: enum constants are written in uppercase.
3 Which of the following is a valid enum declaration?
- enum Color = RED, GREEN, BLUE; Correct answer
- enum Color { RED, GREEN, BLUE }
- enum Color { red, green, blue }
- Color enum { RED, GREEN, BLUE }
Explanation: enum constants are uppercase and separated by commas inside braces.