Java
Constants with enum
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.
Exercise 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.
Show example solution
enum Direction { NORTH, SOUTH, EAST, WEST }
public class Main {
public static void main(String[] args) {
Direction d = Direction.EAST;
System.out.println(d);
}
}
Test yourself
-
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
Show answer
It provides type safety — Enum provides type safety; wrong types cause compile errors.
-
Complete the enum definition
enum Direction {
NORTH, SOUTH, EAST, ____
}
Show answer
enum Direction {
NORTH, SOUTH, EAST, WEST
}
-
Match the enum parts
- enum
- Keyword
- Direction
- Enum name
- NORTH
- Constant
- Direction.NORTH
- Access
Next lesson: Interface constants