Enum in Java

In Java, an enum (short for enumeration) is a special data type that enables a variable to be a set of predefined constants. It’s used when you want to represent a fixed set of related constants in a type-safe way.


✅ Why Use enum in Java?

  • Groups constants into a single type
  • Type-safe (no invalid values allowed)
  • Can include fields, constructors, and methods
  • Great for switch statements and control logic

🔧 Basic Syntax

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

Usage:

Day today = Day.FRIDAY;

if (today == Day.FRIDAY) {
    System.out.println("Weekend is near!");
}


🚀 Enums in switch

switch (today) {
    case MONDAY:
        System.out.println("Back to work!");
        break;
    case FRIDAY:
        System.out.println("Party time!");
        break;
    default:
        System.out.println("Regular day.");
}

🛠️ Enum with Fields and Methods


public enum Status {
    NEW(0), IN_PROGRESS(1), COMPLETED(2);

    private int code;

    Status(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }
}

Usage:

Status s = Status.IN_PROGRESS;
System.out.println(s.getCode()); // Output: 1

📋 Enum Features Summary

Feature Supported in Java Enum
Type-safe constants ✅ Yes
Switch-case usage ✅ Yes
Fields and methods ✅ Yes
Constructors ✅ Yes (private only)
Extending a class ❌ No (enums extend java.lang.Enum)
Implementing interface ✅ Yes


📚 Real-World Use Cases

  • Order status (NEW, SHIPPED, DELIVERED)
  • User roles (ADMIN, USER, GUEST)
  • Days, months, categories
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.