Constant-specific behaviour and EnumMap
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
7 + 3 = 10
7 - 3 = 4
7 * 3 = 21
uses: {PLUS=9, TIMES=4}
weekdays: [MON, TUE, WED, THU, FRI]
range: [TUE, WED, THU]