Popular Searches
Popular Course Categories
Popular Courses

Creating Enumerations Using enum

Creating Enumerations Using enum

Wrapper Classes, Autoboxing, and Enumerations

Creating Enumerations Using enum in Java

Course: Core Java Training

Topic: Creating Enumerations Using enum

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to Enumerations in Java

An enumeration, commonly called an enum, is a special Java type used to represent a fixed set of predefined constants. It is useful when a variable should contain only one value from a known list of options.

For example, an application may need to represent the days of the week, months, order statuses, traffic-light colors, payment methods, or user roles. Instead of storing these values as arbitrary strings or numbers, Java allows developers to define an enum containing the permitted values.

Java introduced enum types in Java 5. An enum improves code readability, provides type safety, and helps prevent invalid values from being assigned accidentally.

Example of an Enumeration

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

In this example, Day is an enum type. It allows a variable of type Day to represent one of the seven declared constants.

2. Why Do We Use enum in Java?

Before enums were available, programmers often used strings or integer constants to represent a fixed set of choices. These approaches could allow unexpected values and make code harder to maintain.

Example Without enum

public class OrderExample {
    public static void main(String[] args) {
        String status = "SHIPPED";

        System.out.println("Order status: " + status);
    }
}

This approach works, but the variable could also contain an unintended value such as "SHIPED" or "UNKNOWN". The compiler does not know which strings are valid order statuses.

Example Using enum

enum OrderStatus {
    PENDING,
    PROCESSING,
    SHIPPED,
    DELIVERED,
    CANCELLED
}

public class EnumOrderExample {
    public static void main(String[] args) {
        OrderStatus status = OrderStatus.SHIPPED;

        System.out.println("Order status: " + status);
    }
}

Output:

Order status: SHIPPED

The compiler restricts assignments to constants declared in OrderStatus, making the code safer and easier to understand.

Main Advantages of enum

  • Provides a fixed set of named constants.
  • Improves type safety and reduces invalid assignments.
  • Makes programs more readable and maintainable.
  • Works with switch statements and expressions.
  • Supports fields, constructors, and methods.
  • Provides built-in methods for retrieving and comparing enum constants.

3. Syntax for Creating an enum

The enum keyword is used to declare an enumeration. Each constant is separated by a comma.

General Syntax

enum EnumName {
    CONSTANT_ONE,
    CONSTANT_TWO,
    CONSTANT_THREE
}

For example:

enum TrafficLight {
    RED,
    YELLOW,
    GREEN
}

Here, TrafficLight is the enum type, while RED, YELLOW, and GREEN are its constants.

Naming Conventions

  • Enum type names usually follow PascalCase, such as TrafficLight or PaymentMethod.
  • Enum constants conventionally use uppercase letters with underscores, such as IN_PROGRESS or CREDIT_CARD.
  • Choose meaningful names that clearly communicate what each constant represents.

4. Declaring and Using Enum Variables

After creating an enum, you can declare a variable using the enum type and assign one of its constants using the enum name followed by a dot.

Example

enum Season {
    SPRING,
    SUMMER,
    AUTUMN,
    WINTER
}

public class SeasonExample {
    public static void main(String[] args) {
        Season currentSeason = Season.SUMMER;

        System.out.println("Current season: " + currentSeason);
    }
}

Output:

Current season: SUMMER

Explanation:

  1. The Season enum declares four possible values.
  2. The variable currentSeason is declared with type Season.
  3. The value Season.SUMMER is assigned to the variable.
  4. Printing the variable displays the enum constant's name by default.

5. Creating an enum Inside a Java Class

An enum can be declared as a top-level type or nested inside another class. A nested enum is useful when its constants are closely related to the class that uses them.

Example

public class Employee {
    enum Department {
        HR,
        IT,
        FINANCE,
        MARKETING
    }

    public static void main(String[] args) {
        Department department = Department.IT;

        System.out.println("Department: " + department);
    }
}

Output:

Department: IT

In this example, Department is declared inside the Employee class. Since it is nested, it can be accessed from the enclosing class using its name. From another class, its accessibility depends on the access modifier and it can be referred to as Employee.Department when accessible.

6. Using enum with switch Statements

An enum can be used with a switch statement to perform different actions depending on the selected constant. This is a common technique for implementing menus, status handling, and business rules.

Example

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

public class DaySwitchExample {
    public static void main(String[] args) {
        Day day = Day.SATURDAY;

        switch (day) {
            case MONDAY:
            case TUESDAY:
            case WEDNESDAY:
            case THURSDAY:
            case FRIDAY:
                System.out.println("It is a working day.");
                break;
            case SATURDAY:
            case SUNDAY:
                System.out.println("It is the weekend.");
                break;
        }
    }
}

Output:

It is the weekend.

Each case names an enum constant without repeating the enum type. This makes the selection logic concise and readable.

7. Important Built-in Methods of enum

Java provides useful methods for working with enum values. Enum types also receive a generated values() method and a generated valueOf(String) method.

Method Description Example
values() Returns an array containing all enum constants in declaration order. Day.values()
valueOf(String) Returns the constant whose declared name exactly matches the supplied string. Day.valueOf("MONDAY")
name() Returns the exact declared name of the constant. day.name()
ordinal() Returns the zero-based position of the constant in its declaration. day.ordinal()
toString() Returns a string representation of the constant; it can be overridden. day.toString()
compareTo() Compares constants of the same enum type by their declaration order. day1.compareTo(day2)

8. Using values() to Retrieve All Constants

The values() method returns an array of all constants defined in an enum. It is commonly used with an enhanced for loop to display or process every available option.

Example

enum Browser {
    CHROME,
    FIREFOX,
    EDGE,
    SAFARI
}

public class EnumValuesExample {
    public static void main(String[] args) {
        for (Browser browser : Browser.values()) {
            System.out.println(browser);
        }
    }
}

Output:

CHROME
FIREFOX
EDGE
SAFARI

The values are returned in the same order in which they are declared in the enum.

9. Using valueOf() to Convert a String into an enum

The generated valueOf(String) method converts a string into the matching enum constant. The supplied string must match the constant's declared name exactly, including capitalization and without extra spaces.

Example

enum PaymentMethod {
    CASH,
    CREDIT_CARD,
    UPI,
    NET_BANKING
}

public class EnumValueOfExample {
    public static void main(String[] args) {
        String paymentText = "UPI";

        PaymentMethod method = PaymentMethod.valueOf(paymentText);

        System.out.println("Selected payment: " + method);
    }
}

Output:

Selected payment: UPI

If the supplied name does not match any constant, valueOf() throws IllegalArgumentException. If the supplied reference is null, it throws NullPointerException.

Handling Invalid Enum Input

enum UserRole {
    ADMIN,
    MANAGER,
    CUSTOMER
}

public class SafeEnumConversion {
    public static void main(String[] args) {
        String roleText = "admin";

        try {
            UserRole role = UserRole.valueOf(roleText.toUpperCase());
            System.out.println("Role: " + role);
        } catch (IllegalArgumentException e) {
            System.out.println("Invalid user role.");
        }
    }
}

Output:

Role: ADMIN

Converting the input to uppercase allows this example to accept lowercase text. For external input, you may also need to trim whitespace and validate the accepted format.

10. Creating an enum with Fields and Constructors

Java enums can contain fields, constructors, and methods, so they can represent more than a simple list of names. Each constant can be initialized with associated data.

An enum constructor must be private or package-private; it cannot be public or protected. Enum constants are created by Java, so developers cannot call the constructor directly with new.

Example: Days with Working Hours

enum WorkDay {
    MONDAY(8),
    TUESDAY(8),
    WEDNESDAY(8),
    THURSDAY(8),
    FRIDAY(6);

    private final int workingHours;

    WorkDay(int workingHours) {
        this.workingHours = workingHours;
    }

    public int getWorkingHours() {
        return workingHours;
    }
}

public class WorkDayExample {
    public static void main(String[] args) {
        WorkDay day = WorkDay.FRIDAY;

        System.out.println("Day: " + day);
        System.out.println("Working hours: " + day.getWorkingHours());
    }
}

Output:

Day: FRIDAY
Working hours: 6

Explanation:

  • Each enum constant passes a value to the constructor.
  • The constructor stores the value in the workingHours field.
  • The getter method returns the number of working hours for the selected day.
  • The field is private final, so it cannot be reassigned after initialization.

When an enum declares fields or methods after its constants, the constants must be followed by a semicolon.

11. Creating an enum with Custom Methods

An enum can define methods that provide behavior related to its constants. This can keep logic associated with the values instead of scattering it throughout the application.

Example: Traffic Light Actions

enum TrafficSignal {
    RED,
    YELLOW,
    GREEN;

    public String getAction() {
        switch (this) {
            case RED:
                return "Stop";
            case YELLOW:
                return "Get ready";
            case GREEN:
                return "Go";
            default:
                return "Unknown";
        }
    }
}

public class TrafficSignalExample {
    public static void main(String[] args) {
        TrafficSignal signal = TrafficSignal.GREEN;

        System.out.println(signal.getAction());
    }
}

Output:

Go

The this keyword refers to the current enum constant. Calling getAction() returns a message based on that constant.

12. Comparing Enum Constants

Enum constants are unique instances of their enum type. You can safely use == to compare whether two enum references represent the same constant. The equals() method also compares enum identity.

Example

enum Status {
    ACTIVE,
    INACTIVE
}

public class EnumComparisonExample {
    public static void main(String[] args) {
        Status first = Status.ACTIVE;
        Status second = Status.ACTIVE;
        Status third = Status.INACTIVE;

        System.out.println(first == second);
        System.out.println(first == third);
    }
}

Output:

true
false

Because first and second refer to the same enum constant, the first comparison returns true. The second comparison returns false because the constants are different.

13. Understanding ordinal()

The ordinal() method returns the zero-based position of an enum constant in the declaration. The first constant has ordinal zero, the second has ordinal one, and so on.

Example

enum Priority {
    LOW,
    MEDIUM,
    HIGH
}

public class EnumOrdinalExample {
    public static void main(String[] args) {
        System.out.println(Priority.LOW.ordinal());
        System.out.println(Priority.MEDIUM.ordinal());
        System.out.println(Priority.HIGH.ordinal());
    }
}

Output:

0
1
2

Best practice: Do not use ordinal() as a permanent business identifier or store it as a stable database value. Reordering enum constants changes their ordinal positions. Use an explicit field when a stable code or identifier is needed.

14. Enum vs Constants

Enums are often safer and more expressive than declaring unrelated string or integer constants.

Feature Traditional Constants enum
Declaration Often uses static final fields. Uses the enum keyword.
Type safety Can allow unrelated or invalid values. Restricts values to declared constants.
Readability Depends on the naming and use of constants. Clearly defines a named set of options.
Built-in iteration Usually requires manually maintained collections. Provides values().
Additional behavior Usually requires a separate class or utility. Can contain fields, constructors, and methods.
Typical use Independent constant values. A fixed set of related choices.

15. Practical Example: Order Management System

In an order management system, an order may have a limited set of valid statuses. Using an enum helps the program handle those states consistently.

enum OrderStatus {
    PLACED,
    CONFIRMED,
    PACKED,
    SHIPPED,
    DELIVERED,
    CANCELLED
}

public class OrderManagement {
    public static void main(String[] args) {
        OrderStatus status = OrderStatus.SHIPPED;

        System.out.println("Current status: " + status);

        switch (status) {
            case PLACED:
                System.out.println("Order received.");
                break;
            case CONFIRMED:
                System.out.println("Order confirmed.");
                break;
            case PACKED:
                System.out.println("Order packed.");
                break;
            case SHIPPED:
                System.out.println("Order is on its way.");
                break;
            case DELIVERED:
                System.out.println("Order delivered successfully.");
                break;
            case CANCELLED:
                System.out.println("Order was cancelled.");
                break;
        }
    }
}

Output:

Current status: SHIPPED
Order is on its way.

This example keeps the order status within a known set of choices and makes the program's decision logic easy to read.

16. Common Mistakes When Using enum

Mistake Why It Is a Problem Correct Approach
Assigning a string directly to an enum variable A string and an enum are different types. Use a declared constant or convert the string with valueOf().
Using an invalid enum constant The compiler rejects constants that do not exist in the enum. Use one of the declared constants.
Passing incorrectly formatted text to valueOf() The method throws IllegalArgumentException if no exact name matches. Normalize and validate external input.
Using ordinal() as a permanent ID Changing declaration order changes ordinal values. Define an explicit identifier field.
Attempting to instantiate an enum with new Enum instances are created by Java from declared constants. Reference constants such as Status.ACTIVE.
Declaring a public enum constructor Enum constructors cannot be public or protected. Use a private or package-private constructor.

17. Best Practices for Using Enumerations

  • Use enums when a variable should represent one value from a known, finite set.
  • Use meaningful enum type and constant names.
  • Follow the uppercase naming convention for constants.
  • Use enum types instead of arbitrary strings for internal application states when practical.
  • Use values() to iterate over all declared constants.
  • Validate external text before converting it with valueOf().
  • Use fields to associate stable identifiers or descriptive values with constants.
  • Avoid relying on ordinal() for database identifiers or long-term data storage.
  • Keep enum-specific behavior inside the enum when that makes the design clearer.

18. Practice Exercises

Complete the following exercises to strengthen your understanding of Java enumerations.

  1. Create an enum named Month containing all twelve months and print each month using values().
  2. Create a UserRole enum with ADMIN, EDITOR, and VIEWER. Use a switch statement to display the permissions for each role.
  3. Create an enum named PaymentMethod with CASH, CARD, and UPI. Convert a string into a payment method and handle invalid input.
  4. Create a Priority enum with LOW, MEDIUM, and HIGH. Print the ordinal value of each constant.
  5. Create a ProductType enum with a field that stores a display label for each product type.
  6. Create a TrafficSignal enum with a method that returns the action associated with each signal.

19. Interview Questions and Answers

Q1. What is an enum in Java?

An enum is a special type that represents a fixed set of named constants.

Q2. Which keyword is used to declare an enumeration?

The enum keyword is used to define an enumeration in Java.

Q3. What are common use cases for enums?

Enums are useful for days, months, order statuses, user roles, payment methods, directions, and other fixed sets of related choices.

Q4. Can an enum contain methods and fields?

Yes. An enum can contain fields, constructors, and methods in addition to its constants.

Q5. What does values() do?

The generated values() method returns an array containing all enum constants in declaration order.

Q6. What does valueOf() do?

The generated valueOf(String) method returns the enum constant whose declared name exactly matches the supplied string.

Q7. Can an enum constructor be public?

No. Enum constructors cannot be declared public or protected. They are private or package-private.

Q8. Can we create an enum object using new?

No. Enum instances are created by Java from the constants declared in the enum definition.

Q9. What is the purpose of ordinal()?

The ordinal() method returns a constant's zero-based position in the enum declaration. It should not be used as a stable business identifier.

Q10. Can enum be used with switch?

Yes. Enum values can be used in switch statements and switch expressions to select behavior based on a constant.

Q11. Can an enum extend another class?

No. Every enum implicitly extends java.lang.Enum, so it cannot extend another class. It can implement interfaces.

Q12. How do you compare two enum constants?

You can use == to check whether two references identify the same enum constant. Enum constants are unique instances of their enum type.

20. Quick Revision Checklist

  • Understand the purpose of enumerations.
  • Know how to declare an enum using the enum keyword.
  • Learn how to declare variables and access enum constants.
  • Practice using enums with switch statements.
  • Understand values(), valueOf(), name(), and ordinal().
  • Know how to add fields, constructors, and methods to an enum.
  • Handle invalid string input when converting text into enum constants.
  • Prefer enums over arbitrary strings when a fixed set of values is required.
  • Avoid using ordinal positions as permanent identifiers.

21. Conclusion

Enumerations are an important feature of Core Java for representing a fixed set of related constants. By using the enum keyword, developers can create readable, type-safe code for values such as days, statuses, roles, and payment methods. Java enums also support switch statements, built-in methods, fields, constructors, and custom behavior, making them more powerful than simple constant declarations.

Continue learning Java fundamentals through the JustAcademy Core Java Training Course. You can also register for a course demo or visit the JustAcademy official website.

Previous Next
whatsapp