Loading
Imagine you are building a program where you need to represent days of the week.
You can write them as strings: "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday".
But what if someone types "Funday" by mistake?


This is where enum (enumeration) helps.

An enumeration is a special data type in Java that is used to define a fixed set of constants. It prevents invalid values and makes the code safe and easy to read.



What is Enumeration?

In Java, enumeration (enum) is a way to represent a group of predefined constant values. You can think of it as a list of fixed options, such as days of the week, directions, or colors. An enum variable can only take one value from this list.

Internally, Java treats an enum as a class, and each value inside it is an object of that class. But as a beginner, you can simply remember that enum is used to store constants



Declaring an Enum

In Java, an enum is created using the enum keyword.
When you declare an enum, you are basically creating a list of named constant values.

Syntax

enum EnumName {
    CONSTANT1, CONSTANT2, CONSTANT3
}

enum - keyword used to declare an enumeration.

EnumName - the name of the enum (it should start with a capital letter, just like class names).

Inside { } - you list all the constant values separated by commas.


Example

enum Color {
    RED, GREEN, BLUE
}

Here,

We created an enum called Color.

It has three constant values: RED, GREEN, and BLUE.

That means a variable of type Color can only hold one of these three values.



Why Do We Need Enum ?

Before enums were introduced in Java, programmers often used int or String constants to represent fixed values.
But there was a big problem, the program would also accept wrong or invalid values, and it would still run without showing any error.

Example: Problem Without Enum

public class Test {
    public static void main(String[ ] args) {
        String day = "Funday"; // Wrong value, but program accepts it
        System.out.println("Today is: " + day);
    }
}


Output

Today is: Funday

Here, "Funday" is not a valid day, but the program still accepts it.
That means if you use String, any value can be assigned, even if it is incorrect.


Enums solve this problem. In an enum, you can only store valid, predefined values.

Example: Solution With Enum

enum Day { MONDAY, TUESDAY, WEDNESDAY }

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


Output

Today is: MONDAY

Here, the variable today can only take values that are defined in the Day enum (MONDAY, TUESDAY, WEDNESDAY).
If you try to assign something like "Funday", the compiler will give an error immediately.



Advantage of Enum

  • Only allows valid values.
  • Works with switch-case.
  • Can have methods, variables, and constructors.
  • Improves readability and maintainability.
  • Best for situations with fixed number of options.



Enum Inside a Class

In Java, you can declare an enum inside a class.
This is useful when the enum is only related to that specific class and you don’t need to use it anywhere else.

Example

public class TestEnum {
    // Enum declared inside the class
    enum Color { RED, GREEN, BLUE }  

    public static void main(String[ ] args) {
        Color c = Color.RED;   // Access enum constant
        System.out.println("Selected color: " + c);
    }
}


Output

Selected color: RED

Here, the enum Color is part of the class TestEnum.



Enum Outside a Class

You can also declare an enum outside a class.
This makes the enum reusable across multiple classes in your project.

Example

// Enum declared outside the class
enum Color { RED, GREEN, BLUE }  

public class TestEnum {
    public static void main(String[ ] args) {
        Color c = Color.GREEN;  // Access enum constant
        System.out.println("Selected color: " + c);
    }
}

Output

Selected color: GREEN

Here, the enum Color is declared outside of any class.
That means it is independent and can be used by many different classes in the program.

Key Point

  • Inside Class - Enum is private to that class, used only within it.
  • Outside Class - Enum is independent and reusable in multiple classes.



Enum in Switch Statement

Enums can also be used in a switch-case statement.
This is very useful when you want to run different code for different enum values.
It works just like using integers or strings in a switch, but here you use enum constants.

Example

enum Day { MONDAY, FRIDAY, SUNDAY }  // enum declared outside class

public class SwitchExample {
    public static void main(String[ ] args) {
        Day today = Day.SUNDAY;   // assign enum value

        switch (today) {
            case MONDAY:
                System.out.println("Start of the week!");
                break;
            case FRIDAY:
                System.out.println("Almost weekend!");
                break;
            case SUNDAY:
                System.out.println("Relax, it's Sunday!");
                break;
        }
    }
}


Output

Relax, it's Sunday!

Explanation:

We created an enum Day with values MONDAY, FRIDAY, SUNDAY.

In main, we set today = Day.SUNDAY.

The switch checks the value of today:

If it is MONDAY → it prints Start of the week!

If it is FRIDAY → it prints Almost weekend!

If it is SUNDAY → it prints Relax, it's Sunday!

Since today = SUNDAY, the output is → Relax, it's Sunday!



Enum with Variables, Methods, and Constructor

Many beginners think that enums are just simple constants, but actually, enums in Java are much more powerful.

An enum can also have:

  • Variables – to store additional information for each constant.
  • Constructor – to initialize the variable.
  • Methods – to get or use that variable.
This makes enums act like small classes where each constant can hold its own data.

Example: Planets with Distance from Sun

enum Planet {
    MERCURY(57.9), VENUS(108.2), EARTH(149.6);

    private double distanceFromSun; // variable to store distance

    // constructor to set the distance
    Planet(double distance) {
        this.distanceFromSun = distance;
    }

    // method to get the distance
    public double getDistance() {
        return distanceFromSun;
    }
}

public class EnumDemo {
    public static void main(String[] args) {
        // Loop through all enum values
        for (Planet p : Planet.values()) {
            System.out.println(p + " is " + p.getDistance() + " million km from the Sun.");
        }
    }
}


Output

MERCURY is 57.9 million km from the Sun.
VENUS is 108.2 million km from the Sun.
EARTH is 149.6 million km from the Sun.

Explanation:

Each planet (MERCURY, VENUS, EARTH) has its own distance value.

We declared a variable distanceFromSun inside the enum to store this information.

The constructor Planet(double distance) sets this value when the enum constant is created.

The method getDistance() returns the stored distance for that planet.

In main, we loop through all planets using Planet.values() and print their distances.



Predefined Methods in Enum

Java provides some built-in methods that make working with enums very easy. These methods help you get information about enum constants or find specific constants.

The most commonly used methods are:

  • values() - Returns an array of all constants in the enum.
  • ordinal() - Returns the position (index) of the constant, starting from 0.
  • valueOf("NAME") - Returns the enum constant that matches the given name exactly.

Example

enum Color { RED, GREEN, BLUE }

public class EnumMethods {
    public static void main(String[ ] args) {
        // Loop through all enum constants
        for (Color c : Color.values()) {
            System.out.println(c + " at index " + c.ordinal());
        }

        // Get a specific enum constant by name
        Color c1 = Color.valueOf("RED");
        System.out.println("Selected: " + c1);
    }
}


Output

RED at index 0
GREEN at index 1
BLUE at index 2
Selected: RED

Explanation:

Color.values() returns all enum constants as an array: [RED, GREEN, BLUE].

c.ordinal() gives the position of each constant:

  • RED - 0
  • GREEN - 1
  • BLUE - 2
Color.valueOf("RED") finds the enum constant with the exact name "RED" and returns it.



Real-Life Example: Order Status

Enums are not just for learning; they are very useful in real-world applications.

Imagine you are building an e-commerce application.
An order can have a few fixed statuses like:

  • PENDING - Order received but not processed
  • SHIPPED - Order has been sent
  • DELIVERED - Order has reached the customer
  • CANCELLED - Order was cancelled

Instead of using strings like "shipped" or "delivered" (where a typo can cause bugs), we can use an enum to represent these statuses.
This ensures that only valid values are used.

Example

enum OrderStatus { PENDING, SHIPPED, DELIVERED, CANCELLED }

public class OrderDemo {
    public static void main(String[ ] args) {
        OrderStatus status = OrderStatus.SHIPPED; // assign enum value

        // Check the status and perform action
        if (status == OrderStatus.SHIPPED) {
            System.out.println("Your order is on the way!");
        }
    }
}


Output

Your order is on the way!

Explanation:

We created an enum OrderStatus with four fixed constants.

The variable status is assigned the value OrderStatus.SHIPPED.

The if condition checks the current status using the enum.

Since status is SHIPPED, the program prints:
“Your order is on the way!”


Key Points

  • Enum introduced in Java 5.
  • Each constant is an object.
  • Can be inside or outside a class.


Two-Minute Drill

  • Enum = Special class for fixed constants
  • Declared with enum keyword
  • Can be used in switch-case
  • Has built-in methods like values(), ordinal().
  • Can hold extra info using variables, constructors and methods.