Command Palette

Search for a command to run...

Back to the lesson: Topic 4.10 — Enums
Core Java · Example 1 of 3 Java 14+

Enum basics: values, ordinal, valueOf, switch

The message uses the canonical name, Main.Size, because Size is nested in Main.

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?

Enum basics: values, ordinal, valueOf, switch Java 14+
Sign in to run this example in your browser.

Expected output

0 SMALL
1 MEDIUM
2 LARGE
picked LARGE, == LARGE? true
SMALL before LARGE? true
LARGE is 400 ml
No enum constant Main.Size.HUGE