Constants with enum
- Java course
- Intermediate
- Lesson 38/116
- 5 min
Learn to define constant sets with enum.
Constants with enum
An enum is used to define a fixed set of constants. It is ideal when values are limited in number, like days of a week, directions or states. It is defined with the enum keyword.
Example: enum Direction { NORTH, SOUTH, EAST, WEST }. This definition represents four constant directions. It is assigned to a variable with Direction d = Direction.NORTH;. The value of d can only be one of these four constants; no other value can be assigned. Enums are safer than static final constants; because they provide type safety. If a method expects Direction, you cannot pass a String or int; you get a compile error.
Using enums
An enum constant is accessed as EnumName.CONSTANT. Enum variables can only take the defined constants. You can branch on enum values with switch; this is useful in state management.
Example: Direction d = Direction.EAST; switch (d) { case NORTH: ...; case EAST: ...; }. Here the variable d holds EAST. switch determines which direction to go. When using switch with an enum, some compilers warn if case is not written for all constants. This helps catch missing cases. Enums can return all constants as an array with the values() method.
Practice Define and use the Direction enum
Define an enum named Direction with NORTH, SOUTH, EAST, WEST constants. In a main method write Direction d = Direction.EAST; and print d with println.
Starter code
// Define the Direction enum
// Add four constants
// Instantiate and print in mainSample solution
enum Direction { NORTH, SOUTH, EAST, WEST }
public class Main {
public static void main(String[] args) {
Direction d = Direction.EAST;
System.out.println(d);
}
}Expected output
EAST
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the advantage of enum over static final constants?
- It runs faster
- It is shorter to write
- It uses less memory
- It provides type safety Correct answer
Explanation: Enum provides type safety; wrong types cause compile errors.
2 Complete the enum definition
enum Direction {
NORTH, SOUTH, EAST, ____
}
enum Direction {
NORTH, SOUTH, EAST, WEST
}
Explanation: Enum constants are uppercase.
3 Match the enum parts
| Term | Meaning |
|---|---|
enum |
Keyword |
Direction |
Enum name |
NORTH |
Constant |
Direction.NORTH |
Access |