Skip to content
C

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.


1. What 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.

2. Why 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.

3. Real-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.

4. Syntax

java
enum EnumName { VALUE1, VALUE2, VALUE3 }

5. Example Program

java
enum 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: TUESDAY

6. Key Points to Remember

  • Enum values are constants and are conventionally written in uppercase.
  • An enum can also have fields, constructors, and methods, making it more powerful than a plain list of names.
  • Using an enum instead of plain numbers or strings makes code safer and more readable.