← Back to Chapters

Enum in Java

? Enum in Java

? Quick Overview

An enum in Java is a special data type used to define a fixed set of constant values. It improves code readability, safety, and prevents invalid values.

? Key Concepts

  • Enums represent a group of predefined constants
  • They are type-safe (no invalid values allowed)
  • Enums can have fields, methods, and constructors
  • They internally extend java.lang.Enum

? Syntax & Theory

Enums are declared using the enum keyword. Each constant is separated by a comma and written in uppercase by convention.

? View Code Example
// Basic enum declaration representing days of the week
enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}

? Code Example

? View Code Example
// Using enum in a Java program
enum Status {
SUCCESS,
FAILURE,
PENDING
}

public class Main {
public static void main(String[] args) {
Status currentStatus = Status.SUCCESS;
System.out.println(currentStatus);
}
}

?️ Output

The program prints the enum constant: SUCCESS

? Interactive Enum Demo

See how an enum TrafficLight works in real-time. Click the button to change states!

 
 
 
Current Java Enum Value: TrafficLight.RED

Action Description: STOP! Do not proceed.

✅ Tips & Best Practices

  • Use enums instead of constants (public static final)
  • Keep enum names singular and constants uppercase
  • Add methods to enums for better behavior modeling
  • Use enums in switch statements for clean logic

? Try It Yourself

  • Create an enum for traffic light colors
  • Add a method inside enum to describe each value
  • Use the enum in a switch-case statement
  • Print all enum values using values()