Learn Java · lesson 58 of 61 · about 8 minutes
enum
Name a fixed set of choices so the compiler can check you only use real ones.
What you'll learn
- Define an enum and use its values
- Switch on an enum
- Convert between enums and text with valueOf and name
Tonight's seats
The screens have three kinds of seat: standard, premium and recliner. The desk reads the seats booked tonight, one per line, like premium or Recliner, until done. A seat that doesn't exist gets No seat called sofa. Then the desk counts each kind, Seats booked: standard 1, premium 2, recliner 1, and says what the comfiest seat booked is like: Comfiest seat: a recliner, feet up!. If nobody booked anything, it's No seats booked. A word that can only be one of three things is just what an enum is for.
A type with a fixed set of values
Some values can only be one of a few choices: a traffic light is red, amber or green. Strings like "red" can be misspelt, and nothing stops "purple".
An enum lists every allowed value: enum Light { RED, AMBER, GREEN }. A Light variable can only ever hold one of those three, and a typo won't compile.
Switching on an enum
public class Main {
enum Light { RED, AMBER, GREEN }
static Light next(Light l) {
return switch (l) {
case RED -> Light.GREEN;
case GREEN -> Light.AMBER;
case AMBER -> Light.RED;
};
}
public static void main(String[] args) {
Light l = Light.RED;
for (int i = 0; i < 4; i++) {
System.out.print(l + " ");
l = next(l);
}
System.out.println();
}
}Output
RED GREEN AMBER REDUseful built-ins
Every enum gets some methods for free. Light.values() is an array of all the values, in order. l.ordinal() is its position, from 0. Light.valueOf("RED") turns text into the value, and l.name() turns it back into text.
values, ordinal and valueOf
public class Main {
enum Size { SMALL, MEDIUM, LARGE }
public static void main(String[] args) {
for (Size s : Size.values()) System.out.print(s.ordinal() + ":" + s + " ");
System.out.println();
Size chosen = Size.valueOf("LARGE");
System.out.println(chosen == Size.LARGE);
System.out.println(chosen.name().toLowerCase());
}
}Output
0:SMALL 1:MEDIUM 2:LARGE
true
largeFrom a typed word to a seat
SeatKind.valueOf(seatLine.trim().toUpperCase()) turns premium or Recliner into the value with that exact name, and throws an IllegalArgumentException for a word that isn't one, which the catch turns into No seat called sofa. The enum lists the seats from plainest to comfiest, so looping over SeatKind.values() counts them in that order, and the last kind with any bookings is the comfiest. The switch then has one case for each value, and the compiler checks that none is missing.
Tip
A switch expression on an enum that covers every value needs no default: the compiler checks you haven't forgotten one.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.