×

java · level 2 · unit 4 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An lists every choice a value can take.

A coffee comes small, medium or large. Store the size as text and someone will type "meduim". An enum fixes the choices: enum Size { SMALL, MEDIUM, LARGE }. Now a Size box can only hold one of those three.

Write a choice with the enum's name and a dot: Size.LARGE. A typo like Size.LRAGE is caught before anything runs. Compare choices with ==, which is safe here because each choice exists only once.

gives every choice in order, ready for a for-each loop, and .name() gives a choice's name as text.

public class Main {
    enum Size { SMALL, MEDIUM, LARGE }
    public static void main(String[] args) {
        Size order = Size.MEDIUM;
        if (order == Size.LARGE) {
            System.out.println("That is a big one!");
        } else {
            System.out.println("You chose " + order);
        }
        for (Size size : Size.values()) {
            System.out.println(size.name().toLowerCase());
        }
    }
}

Enum choices are written in capitals, like constants, because they never change.