Fields, a constructor and a lookup by code
The static map is filled in a static block, which runs after all constants exist.
An enum is a class with a fixed, named set of instances, such as SMALL, MEDIUM, LARGE. Enums replace error-prone int and String constants with a real type the compiler checks, and they can carry fields, constructors and behaviour.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write enum Planet with MERCURY, EARTH, JUPITER and a field surfaceGravity (3.7, 9.8, 24.8). Print what a 50 kg mass weighs (mass times gravity, rounded to one decimal) on each planet.
Write enum TrafficLight { RED, GREEN, YELLOW } with a method next() implemented with a switch expression (RED -> GREEN -> YELLOW -> RED). Starting from RED, print five transitions.
Count the votes {"TEA", "COFFEE", "TEA", "JUICE", "TEA", "COFFEE"} into an EnumMap<Drink, Integer> and print it.
Explain it without notes
Why are enums better than int or String constants?
What does the compiler generate for enum Size { SMALL, MEDIUM, LARGE }?
Why is == the right way to compare enum values?
What's the danger of ordinal() and how should you persist enums?
How do constant-specific method bodies work, and when would you use them?
Expected output
SMALL 200 ml Rs 120 (0.60 per ml)
MEDIUM 300 ml Rs 150 (0.50 per ml)
LARGE 400 ml Rs 180 (0.45 per ml)
code ' m ' -> MEDIUM