Beginner 5 min

Enums and fixed choices

An enum names the fixed choices that are valid for one value.

How it works

Represent the state with a name such as PAID; when you read a switch branch it is clear what that branch handles. To accept text from a file or form, explicitly map allowed labels to enum constants. This makes unknown values easier to report.

Walk through an example

An order might have NEW, PAID, or SENT states. An enum makes those choices explicit and a variable of its type can hold one of them.

What to watch for

Avoid storing business state as an enum’s numeric position in persistent data. Reordering constants can change that position.

Code example

public class Main {
    enum Status { NEW, PAID, SENT }
    public static void main(String[] args) {
        Status state = Status.PAID;
        System.out.println(state);
    }
}

Check your understanding

Can a caller assign the unrelated string shipped directly to an enum variable?

See the example and explanation
Worked example
Given Order states are NEW, PAID, and SENT.
Answer No.

The variable expects a declared enum value rather than an arbitrary string.

Open practice problem
Next lessonClasses and objects