Command Palette

Search for a command to run...

Back to the lesson: Topic 4.10 — Enums
Core Java · Example 2 of 3

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.

01

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.

02

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.

03

Count the votes {"TEA", "COFFEE", "TEA", "JUICE", "TEA", "COFFEE"} into an EnumMap<Drink, Integer> and print it.

Explain it without notes

01

Why are enums better than int or String constants?

02

What does the compiler generate for enum Size { SMALL, MEDIUM, LARGE }?

03

Why is == the right way to compare enum values?

04

What's the danger of ordinal() and how should you persist enums?

05

How do constant-specific method bodies work, and when would you use them?

Fields, a constructor and a lookup by code
Sign in to run this example in your browser.

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