Enum

Thinking

When you need to define a fixed set of constants in your program—like days of the week, directions, or status codes—`enum` becomes your best tool. Unlike traditional constants, Java enums are more powerful, type-safe, and flexible.

They improve readability and maintainability, while also allowing you to associate additional behavior with each constant, making your code more expressive and error-free.

Description

An enum (short for "enumeration") in Java is a special data type that enables a variable to be a set of predefined constants.

Java enums are more than simple collections of constants—they are full-fledged classes with methods, constructors, and variables.

  • Defined using the enum keyword.
  • Can have fields, constructors, and methods.
  • Can be used in switch statements.
Type Safety:

Enums provide compile-time checking so that values outside the defined set are not allowed.

Video Resources

Examples (code)

Basic Enum Example


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

public class EnumTest {
    public static void main(String[] args) {
        Day today = Day.FRIDAY;
        System.out.println("Today is: " + today);
    }
}
  

Enum with Constructor and Method


enum Status {
    SUCCESS(200), NOT_FOUND(404), SERVER_ERROR(500);

    private int code;

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

    public int getCode() {
        return code;
    }
}

public class EnumWithMethod {
    public static void main(String[] args) {
        System.out.println("Code for SUCCESS: " + Status.SUCCESS.getCode());
    }
}
  

Real-World Applications

Scheduling Systems

Use enums to represent days of the week or time blocks in calendar applications.

HTTP Response Handling

Define HTTP status codes using enums to manage responses cleanly and consistently.

Game Development

Use enums to represent game states like START, PAUSE, RUNNING, and GAME_OVER.

Interview Questions

Q1: What is an enum in Java?

Show Answer

An enum is a special data type that enables for a variable to be a set of predefined constants. It provides type safety and clarity in the code.

Q2: Can enums have methods and constructors in Java?

Show Answer

Yes, enums in Java can have fields, constructors, and methods like a normal class. However, the constructors must be private or package-private.

Q3: What happens if you use enums in a switch statement?

Show Answer

Switch statements with enums improve readability and ensure that only valid enum constants are used in control flow.