Advanced Java · Lesson 90 of 150
Enum
An enum (short for enumeration) is a special Java type used to define a fixed set of named constant values, like the days of the week or the directions North, South, East, and West.
01What is an Enum?
An enum (short for enumeration) is a special Java type used to define a fixed set of named constant values, like the days of the week or the directions North, South, East, and West.
02Why is it used?
When a value should only ever be one of a small, known set of options, an enum prevents invalid values from being used by mistake, unlike a plain String or int, which could accidentally hold anything.
03Real-Life Example
Think of traffic light colours — only Red, Yellow, or Green are valid; there's no "Purple" traffic light. An enum locks a value down to only its officially defined options, just like a traffic light's fixed set of colours.
04Syntax
javaenum EnumName { VALUE1, VALUE2, VALUE3 }
05Example Program
javaenum Day { MONDAY, TUESDAY, WEDNESDAY } public class EnumDemo { public static void main(String[] args) { Day today = Day.TUESDAY; System.out.println("Today is: " + today); } }
Output:
Today is: TUESDAY06Key Points to Remember
- Enum values are constants and are conventionally written in uppercase.
- An
enumcan also have fields, constructors, and methods, making it more powerful than a plain list of names. - Using an
enuminstead of plain numbers or strings makes code safer and more readable.