Summary - Enum
- Java course
- Beginner
- Lesson 105/116
- 5 min
Combine values, methods and switch to write a seasons app.
Summary - Enum
In this group you learned to declare enums, work with values and valueOf, add fields and methods, and branch with switch. Enums are a safe and readable way to handle fixed sets of constants.
Now you will combine everything to write a small seasons app: define a Season enum and produce a label and a message for each constant. This summary lesson has 5 steps and includes one code task.
Practice Seasons app
Define a Season enum with SPRING and SUMMER constants. Each constant takes a String label (SPRING gets ilkbahar, SUMMER gets yaz). Start with Season s = Season.SPRING;, use switch to print ilkbahar in the SPRING branch.
Starter code
public class Main {
public static void main(String[] args) {
// Define the Season enum, assign SPRING, print the label with switch
}
}
// Define the Season enum hereSample solution
enum Season {
SPRING("ilkbahar"), SUMMER("yaz");
String label;
Season(String label) { this.label = label; }
}
// inside main:
Season s = Season.SPRING;
switch (s) {
case SPRING: System.out.println(s.label); break;
}Expected output
ilkbahar
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each concept to its purpose
| Term | Meaning |
|---|---|
values() |
All constants |
valueOf() |
Constant from name |
switch |
Branching |
ordinal() |
Order number |
2 Find a constant with valueOf
Season s = Season.____("SUMMER");
Season s = Season.valueOf("SUMMER");
Explanation: valueOf produces a constant from a name.
3 What is the advantage of using an enum over using strings?
- Typos are caught at compile time Correct answer
- Less code is written
- It runs faster
- It uses less memory
Explanation: enum constants are checked at compile time; a wrong name is a compile error.