Enums
An enum is a class with a fixed set of instances. The instances are written as constants, the compiler makes them final and gives the class a private constructor, and no other object of that type can exist. It replaces a group of static final int constants with a type the compiler checks.
An enum
enum Size { SMALL, MEDIUM, LARGE } declares a type with exactly three values. A variable of the type is one of them or null, and the compiler refuses Size.XL because no such constant exists. The constants are written in capitals by convention, and each one is a public static final field of the enum class.
The enum below gives each constant a price through a constructor:
public class SizeDemo {
enum Size {
SMALL(5), MEDIUM(8), LARGE(12);
private final int price;
Size(int price) {
this.price = price;
}
int price() {
return price;
}
}
public static void main(String[] args) {
for (Size size : Size.values()) {
System.out.println(size + ": " + size.price());
}
Size medium = Size.valueOf("MEDIUM");
System.out.println("valueOf: " + medium);
int price = switch (medium) {
case SMALL -> 5;
case MEDIUM -> 8;
case LARGE -> 12;
};
System.out.println("switch: " + price);
System.out.println("ordinal: " + Size.LARGE.ordinal());
}
}
javac -Xlint:all SizeDemo.java
java SizeDemo
SMALL: 5
MEDIUM: 8
LARGE: 12
valueOf: MEDIUM
switch: 8
ordinal: 2
The class is declared inside SizeDemo because only one class per file may be public; an enum used by several classes gets its own file, and then the declaration is public enum Size.
Fields and a constructor
Each constant passes its arguments to the constructor in parentheses after its name, and the constructor stores them in the fields of that constant. The constants are created once, when the enum class is initialised, so the fields are effectively final even without the keyword.
The constructor is implicitly private: an enum cannot be instantiated from outside, and a call such as new Size(3) is a compile error. That is the guarantee the type gives: the set of values is the set written in the source.
A method per constant
A method on the enum reads the fields of the constant it is called on, as size.price() does. An enum can also declare an abstract method and give every constant its own body; lesson 057 builds that form, where each constant answers differently instead of reading a different field.
values and valueOf
values() returns a new array of the constants in declaration order, which is what a loop over an enum uses. valueOf(String) returns the constant with that name and throws IllegalArgumentException for a name that does not exist. ordinal() is the position in the declaration, starting at 0; it is for the implementation of the enum, not for a program, because adding a constant in the middle changes every later ordinal.
An enum in a switch
A switch on an enum uses the constant names without the type, and an arrow switch that names every constant needs no default, as lesson 014 showed. The compiler then checks the switch against the enum: add a constant and every switch that forgot it is reported, at the switch rather than in a test.
Exercises
- Add a TINY(2) constant to the enum and fix every switch the compiler reports.
- Add a label() method that returns the constant name in lower case.
-
Try Size.MEDIUM.ordinal() and
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
How many instances does an enum type have?
Answer
Exactly the constants written in the source
An enum cannot be instantiated from outside, so its set of values is fixed by the declaration.
-
What does
values()return?Answer
An array of the constants in declaration order
values() builds a new array of all constants each time it is called.
-
What does
ordinal()give?Answer
The position of the constant in the declaration, from 0
ordinal is the index in the declaration, which shifts when a constant is inserted before it.
-
What does this program print?
public class Q1 { enum Color { RED, GREEN, BLUE } public static void main(String[] args) { System.out.println(Color.valueOf("GREEN")); } }Answer
GREEN
valueOf returns the constant whose name is GREEN, and println prints its name.
-
What does this program print?
public class Q2 { enum Color { RED, GREEN } public static void main(String[] args) { for (Color color : Color.values()) { System.out.print(color.ordinal()); } System.out.println(); } }Answer
01
The two constants are at positions 0 and 1.
-
What does this program print?
public class Q3 { enum Size { SMALL(1), LARGE(2); final int code; Size(int code) { this.code = code; } } public static void main(String[] args) { System.out.println(Size.LARGE.code); } }Answer
2
The constant passes 2 to the constructor, which stores it in code.
-
What does this program print?
public class Q4 { enum Size { SMALL, LARGE } public static void main(String[] args) { Size size = Size.SMALL; int price = switch (size) { case SMALL -> 5; case LARGE -> 10; }; System.out.println(price); } }Answer
5
Both constants have a label, so the switch is exhaustive and SMALL gives 5.
-
What is the first line of the compiler output for this program?
public class Q5 { enum Size { SMALL } public static void main(String[] args) { Size size = new Size(); } }Answer
error: enum classes may not be instantiated
An enum constructor is private, and the compiler refuses new on the enum type.
-
What does this program print?
public class Q6 { enum Size { SMALL, LARGE } public static void main(String[] args) { try { System.out.println(Size.valueOf("HUGE")); } catch (IllegalArgumentException error) { System.out.println("caught"); } } }Answer
caught
valueOf has no constant for the name, throws, and the catch prints its line.
-
Why is an enum better than a group of static final ints?
Answer
The compiler checks the type and the set of values
A variable of the enum type cannot hold a number that is not a constant, and every switch is checked.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev
-