Basic Enum Declaration Syntax
What you'll learn: How to declare your first enum using the enum keyword to define a fixed set of constant values.
The Core Idea
An enum (short for enumeration) is a special Java type that represents a fixed set of related constants. Instead of using integers or strings to represent days of the week, directions, or states, you create an enum that explicitly lists all possible values. The syntax is straightforward: use the enum keyword followed by the enum name, then list the constant values separated by commas.
Declaration Syntax
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
This declares an enum named Day with seven constant values. Each value (like MONDAY) is an instance of the Day type.
Key Components
- The
enumkeyword – Similar to how you useclassorinterface, but specifically for enumerations - Enum name – Follows standard naming conventions (capitalize first letter)
- Constant values – Listed in uppercase by convention, separated by commas
- Semicolon – Optional if you only have constants (required if you add methods or constructors later)
Simple Examples
enum TrafficLight {
RED, YELLOW, GREEN
}
enum CardSuit {
HEARTS, DIAMONDS, CLUBS, SPADES
}
Using Enum Constants
Once declared, you access enum constants using dot notation:
Day today = Day.MONDAY;
TrafficLight signal = TrafficLight.RED;
Each constant is a unique instance of its enum type, and the compiler ensures you can only use the values you've defined—no invalid values possible!
Key Takeaway: Use the enum keyword followed by a list of comma-separated constant names to declare a fixed set of related values that are type-safe and compiler-checked.