Enums for Fixed Set of Constants in Java


Enums define a fixed set of constants. They are more powerful than simple constants and provide type-safe checking.

Source Code

enum Direction {
    NORTH, SOUTH, EAST, WEST
}

public class TestEnum {
    Direction dir = Direction.NORTH;

    void showDirection() {
        switch (dir) {
            case NORTH:
                System.out.println("Going North");
                break;
            // handle other directions
        }
    }
}

Use enums to represent a group of named constants for better type safety and clarity in your code.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments