Skip to main content

Command Palette

Search for a command to run...

Enums in Java: From Basics to Advanced Concepts πŸš€

Updated
β€’4 min read

Java offers many features that help developers write safe, readable, and maintainable code. Enum (Enumeration) is one such powerful feature. Although enums look simple, they are much more capable than just holding constants.

This article explains Enums in Java from beginner to advanced level, with clear examples and real-world relevance.


1. What is an Enum in Java? (Basic Level)

An enum is a special data type used to define a fixed set of constants.

Simple Definition:

An enum represents a group of predefined values that do not change.

Examples:

  • Days of the week

  • Directions (NORTH, SOUTH, EAST, WEST)

  • Order status (PLACED, SHIPPED, DELIVERED)


2. Why Enums Were Introduced?

Before Java 5, constants were defined using:

public static final int MONDAY = 1;
public static final int TUESDAY = 2;

Problems:

❌ Not type-safe

❌ Invalid values allowed

❌ Hard to maintain

Enums solve these problems by providing type safety and clarity.


3. Basic Enum Example

enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

Using the enum:

public class TestEnum {
    public static void main(String[] args) {
        Day today = Day.MONDAY;
        System.out.println(today);
    }
}

Output

MONDAY

4. Enum vs Normal Constants

Using Constants ❌

int day = 10; // Invalid but allowed

Using Enum βœ…

Day day = Day.MONDAY; // Only valid values allowed

Benefits of Enum:

βœ” Compile-time checking

βœ” Cleaner code

βœ” Easy to understand

βœ” No invalid values


5. Using Enum with Switch Statement

Enums work seamlessly with switch.

Day day = Day.FRIDAY;

switch (day) {
    case MONDAY:
        System.out.println("Week starts");
        break;
    case FRIDAY:
        System.out.println("Weekend is near");
        break;
    default:
        System.out.println("Midweek");
}

6. Important Internal Concept of Enum πŸ”₯

Behind the scenes:

  • Every enum extends java.lang.Enum

  • Enums are special classes

  • Enum constants are objects

Key Restrictions:

❌ Enum cannot extend another class

βœ” Enum can have variables, methods, and constructors


7. Enum with Fields and Constructor (Intermediate Level)

Enums can store data just like classes.

enum Level {
    LOW(1),
    MEDIUM(2),
    HIGH(3);

    private int value;

    Level(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

Usage:

public class Test {
    public static void main(String[] args) {
        Level level = Level.HIGH;
        System.out.println(level.getValue());
    }
}

Output

3

πŸ”‘ Note:

Enum constructors are private by default and cannot be called directly.


8. Built-in Enum Methods (Very Important ⭐)

Java provides useful methods automatically:

Day d = Day.MONDAY;

d.name();        // MONDAY
d.ordinal();     // 0
Day.valueOf("MONDAY");
Day.values();

Looping through enum values:

for (Day day : Day.values()) {
    System.out.println(day);
}

⚠ Avoid using ordinal() for business logic.


9. Enum with Methods (Advanced Level)

Enums can have methods and logic.

enum Operation {
    ADD,
    SUB;

    public int apply(int a, int b) {
        switch (this) {
            case ADD:
                return a + b;
            case SUB:
                return a - b;
            default:
                return 0;
        }
    }
}

Usage:

public class Calculator {
    public static void main(String[] args) {
        System.out.println(Operation.ADD.apply(10, 5));
    }
}

10. Enum with Constant-Specific Behavior (Deep Concept πŸ’‘)

Each enum constant can behave differently.

enum TrafficLight {
    RED {
        public String action() {
            return "Stop";
        }
    },
    GREEN {
        public String action() {
            return "Go";
        }
    },
    YELLOW {
        public String action() {
            return "Ready";
        }
    };

    public abstract String action();
}

Usage:

public class Test {
    public static void main(String[] args) {
        System.out.println(TrafficLight.RED.action());
    }
}

11. Real-World Use Cases of Enum

Enums are widely used in real applications:

βœ” Order Status (PLACED, SHIPPED, DELIVERED)

βœ” User Access Levels

βœ” Payment Status

βœ” Application Modes

βœ” Machine Learning labels

Example:

enum OrderStatus {
    PLACED, SHIPPED, DELIVERED, CANCELLED
}

12. Common Mistakes with Enums ❌

❌ Using ordinal() in database logic

❌ Comparing enum values with strings

❌ Using enum when values are dynamic


13. Best Practices for Enums βœ…

βœ” Use enums only for fixed values

βœ” Add fields instead of relying on position

βœ” Keep enum names meaningful

βœ” Prefer enum over constant integers