Java Tutorial 0/145 lessons ~6 min read Lesson 30

    Java Enums

    java enums enumeration EnumSet EnumMap valueOf ordinal switch type-safe constants OrderStatus

    Course progress0%
    Focus
    31 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Learning Objectives

    After completing this lesson, you will be able to:

    • Understand what Enums are
    • Create Enum constants
    • Use Enums in switch statements
    • Add fields and methods to Enums
    • Create Enum constructors
    • Override methods in Enums
    • Iterate over Enum values
    • Use EnumSet
    • Use EnumMap
    • Compare Enums
    • Understand Enum internals
    • Learn best practices
    • Prepare for Java interview questions

    Introduction

    In many applications, certain values are fixed and should never change.

    Examples:

    • Days of the week
    • Months
    • Order Status
    • Payment Status
    • User Roles
    • HTTP Methods
    • Directions
    • Database Types

    Instead of using Strings:

    code
    String status = "ACTIVE";

    Someone might accidentally write:

    code
    status = "Actve";

    This typo compiles successfully but causes runtime bugs.

    Enums solve this problem.

    What is an Enum?

    An Enum (Enumeration) is a special Java type used to define a fixed set of constants.

    Example:

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

    Each value is an object of the Day enum.

    Why Use Enums?

    Without Enum

    code
    String role = "ADMIN";

    Problems

    • Typing mistakes
    • Invalid values
    • Difficult validation
    • Less readable

    With Enum

    code
    Role role = Role.ADMIN;

    Benefits

    • Type Safe
    • Compile-time checking
    • Better readability
    • Cleaner code
    • Easier maintenance

    Enum Syntax

    code
    public enum Status {
    NEW,
    PROCESSING,
    COMPLETED,
    FAILED
    }

    Usage

    code
    Status status = Status.NEW;
    System.out.println(status);

    Output

    code
    NEW

    Enum Constants

    Each constant is actually a singleton object.

    code
    Status.NEW
    Status.COMPLETED

    Internally

    code
    Status
    NEW
    PROCESSING
    FAILED

    Only one object exists for each constant.

    Using Enums

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

    Output

    code
    COMPLETED

    Enum in Switch Statement

    code
    Status status = Status.PROCESSING;
    switch(status){
    case NEW ->
    System.out.println("New Order");
    case PROCESSING ->
    System.out.println("Processing");
    case COMPLETED ->
    System.out.println("Completed");
    case FAILED ->
    System.out.println("Failed");
    }

    Output

    code
    Processing

    Enums work naturally with switch expressions.

    Enum Methods

    Every Enum automatically inherits methods from java.lang.Enum.

    Common methods

    code
    values()
    valueOf()
    name()
    ordinal()
    compareTo()

    values()

    Returns all constants.

    code
    for(Status status : Status.values()){
    System.out.println(status);
    }

    Output

    code
    NEW
    PROCESSING
    COMPLETED
    FAILED

    valueOf()

    Converts String into Enum.

    code
    Status status =
    Status.valueOf("NEW");
    System.out.println(status);

    Output

    code
    NEW

    Throws IllegalArgumentException if the string does not exactly match an enum constant.

    name()

    Returns Enum name.

    code
    System.out.println(Status.NEW.name());

    Output

    code
    NEW

    ordinal()

    Returns index position.

    code
    System.out.println(Status.COMPLETED.ordinal());

    Output

    code
    2

    Avoid using ordinal() for business logic because changing the declaration order changes the value.

    Enum Comparison

    Enums should be compared using ==.

    code
    if(status == Status.NEW){
    System.out.println("New Order");
    }

    Since Enum constants are singleton instances, == is safe and recommended.

    Enum Constructors

    Enums can have constructors.

    code
    public enum Status{
    NEW("Order Created"),
    COMPLETED("Order Delivered");
    private final String message;
    Status(String message){
    this.message = message;
    }
    public String getMessage(){
    return message;
    }
    }

    Usage

    code
    System.out.println(
    Status.NEW.getMessage()
    );

    Output

    code
    Order Created

    Enum constructors are implicitly private.

    Enum Fields

    Enums can store data.

    code
    public enum Planet{
    EARTH(9.8),
    MOON(1.62);
    private final double gravity;
    Planet(double gravity){
    this.gravity = gravity;
    }
    public double getGravity(){
    return gravity;
    }
    }

    Enum Methods

    Enums can contain methods.

    code
    public enum Direction{
    NORTH,
    SOUTH;
    public void move(){
    System.out.println(
    "Moving");
    }
    }

    Usage

    code
    Direction.NORTH.move();

    Abstract Methods in Enums

    Each constant can provide its own implementation.

    code
    public enum Operation{
    ADD{
    @Override
    public int apply(int a,int b){
    return a+b;
    }
    },
    SUBTRACT{
    @Override
    public int apply(int a,int b){
    return a-b;
    }
    };
    public abstract int apply(int a,int b);
    }

    Usage

    code
    System.out.println(
    Operation.ADD.apply(10,20)
    );

    Output

    code
    30

    EnumSet

    EnumSet is a specialized high-performance Set implementation for Enum types.

    code
    EnumSet<Day> weekends =
    EnumSet.of(
    Day.SATURDAY,
    Day.SUNDAY
    );
    System.out.println(weekends);

    Output

    code
    [SATURDAY, SUNDAY]

    Benefits

    • Faster than HashSet
    • Memory efficient
    • Type safe

    EnumMap

    EnumMap is a specialized Map implementation for Enum keys.

    code
    EnumMap<Day,String> schedule =
    new EnumMap<>(Day.class);
    schedule.put(
    Day.MONDAY,
    "Office"
    );
    schedule.put(
    Day.SUNDAY,
    "Holiday"
    );
    System.out.println(schedule);

    Enum Internals

    The compiler transforms an enum into a final class that extends java.lang.Enum.

    Conceptually:

    code
    public final class Status
    extends Enum<Status>

    Each constant becomes a static final instance.

    code
    Status.NEW
    static final object

    This is why Enum objects are immutable and singleton.

    Enum Memory Diagram

    code
    JVM Heap
    ┌──────────┼──────────┐
    │ │ │
    NEW PROCESSING COMPLETED
    │ │ │
    Singleton Singleton Singleton

    Real-World Example: Order Status

    code
    public enum OrderStatus{
    PLACED,
    CONFIRMED,
    SHIPPED,
    DELIVERED,
    CANCELLED
    }

    Spring Boot applications frequently use enums for entity fields.

    Real-World Example: User Roles

    code
    public enum Role{
    ADMIN,
    MANAGER,
    USER,
    GUEST
    }

    Real-World Example: Payment Status

    code
    public enum PaymentStatus{
    PENDING,
    SUCCESS,
    FAILED,
    REFUNDED
    }

    Best Practices

    Use Enums Instead of String Constants

    Prefer

    code
    Role.ADMIN

    Instead of

    code
    "ADMIN"

    Keep Enums Immutable

    Declare fields as private final.

    Avoid Using ordinal()

    Use explicit fields if persistence or business logic requires stable numeric values.

    Use EnumSet

    Prefer EnumSet over HashSet for enum collections.

    Use EnumMap

    Prefer EnumMap over HashMap when keys are enums.

    Common Mistakes

    Comparing with equals()

    Prefer

    code
    status == Status.NEW

    Using ordinal() in Database

    Changing enum order changes ordinal values.

    Instead

    code
    NEW(1),
    PROCESSING(2)

    Store explicit codes if needed.

    Using Strings Instead of Enums

    Enums provide compile-time safety.

    Creating Mutable Fields

    Enum fields should generally be immutable.

    Using valueOf() Without Validation

    Invalid input throws IllegalArgumentException.

    Handle user input safely before converting.

    Hands-on Exercise

    Create a Java program that:

    1. Creates a Day enum.
    2. Uses switch with enums.
    3. Adds fields and constructors to an enum.
    4. Creates methods inside an enum.
    5. Implements abstract methods for enum constants.
    6. Uses values().
    7. Uses valueOf().
    8. Uses EnumSet.
    9. Uses EnumMap.
    10. Builds a simple Order Management System using enums.

    Summary

    Enums provide a type-safe way to represent fixed sets of constants. Unlike string literals, enums prevent invalid values at compile time, improve readability, and integrate seamlessly with switch statements, collections, and enterprise frameworks. Java enums are full-fledged classes that can contain fields, constructors, methods, and even abstract methods. Specialized collections such as EnumSet and EnumMap make enum-based programming both efficient and expressive.

    Key Takeaways

    • Enums represent a fixed set of constants.
    • Enum constants are singleton objects.
    • Enums are type-safe.
    • Enums can contain fields, constructors, and methods.
    • Enum constructors are implicitly private.
    • Use == to compare enum constants.
    • EnumSet is optimized for enum collections.
    • EnumMap is optimized for enum keys.
    • Avoid using ordinal() for business logic.
    • Enums are heavily used in Spring Boot, JPA, and enterprise applications.

    Professional Interview Questions

    1What is an Enum in Java?

    Professional Answer

    An enum is a special Java type used to define a fixed set of constants. Each enum constant is a singleton object, providing type safety, readability, and compile-time validation. Enums can also contain fields, constructors, methods, and implement interfaces, making them much more powerful than simple constants.

    Follow-up Questions

    • Can enums have constructors?
    • Can enums implement interfaces?
    • Can enums extend another class?

    Interview Tip: Remember: Enum = Type-Safe Singleton Constants.

    2Why should Enums be preferred over String constants?

    Professional Answer

    Enums prevent invalid values at compile time, eliminate typographical errors, improve readability, and simplify maintenance. Unlike string constants, enum values are validated by the compiler and integrate naturally with switch statements, collections, and frameworks.

    Follow-up Questions

    • What problems occur when using Strings?
    • How does the compiler validate enum values?

    Interview Tip: Strings → Error-Prone, Enums → Compile-Time Safe.

    3What is the difference between EnumSet and EnumMap?

    Professional Answer

    EnumSet is a highly optimized implementation of the Set interface designed specifically for enum values. It provides excellent performance and memory efficiency. EnumMap is a specialized implementation of the Map interface where enum constants are used as keys. Both are faster and more efficient than HashSet and HashMap when working with enums.

    Follow-up Questions

    • Why is EnumSet faster than HashSet?
    • Can EnumMap use non-enum keys?

    Interview Tip: EnumSet → Enum Collection, EnumMap → Enum Keys, Both are optimized for performance.

    Ready to mark this lesson complete?Track your journey across the entire course.