DEV Community

Cover image for Enums in Java Explained
Adesola
Adesola

Posted on

Enums in Java Explained

Enums

When you create an enum in Java, the compiler treats it as a special kind of class. Each constant you define inside it is actually an object — an instance — of that class. In plain terms: enums are named constants with the full power of a class behind them.

enum Status {
    RUNNING, PENDING, FAILED, SUCCESS
}
Enter fullscreen mode Exit fullscreen mode

Convention note: enum constants are conventionally written in UPPER_SNAKE_CASE (like RUNNING, not Running). It's not required by the compiler, but it's the style you'll see in almost all Java codebases and libraries.

How do we get the enum's position?
Short Answer: We get an enum constant's position with ordinal() method that the standard java library has made available.

Every enum constant knows its own position (starting at 0) in the order it was declared. You get that position with ordinal():

public class ApplicationController {
    public static void main(String[] args) {
        Status s = Status.RUNNING;
        System.out.println(s.ordinal()); // 0
    }
}
Enter fullscreen mode Exit fullscreen mode

How do we access all the enum constants?

Short Answer: By Looping over every constant with values() method that the standard java library provides.

If you want all the constants defined in an enum, values() returns them as an array:

public class ApplicationController {
    public static void main(String[] args) {
        Status[] states = Status.values();
        for (Status state : states) {
            System.out.println("Status " + state + ": rank " + state.ordinal());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

There's also a valueOf(String) method that does the reverse — it looks up a constant by its exact name:

Status s = Status.valueOf("RUNNING"); // Status.RUNNING

This throws an IllegalArgumentException if the string doesn't match any constant, so it's worth wrapping in a try/catch if the input is coming from outside your program (like user input or a config file).

Using enums in a switch

Enums work naturally with switch statements — note that you don't repeat the enum name in each case:

public class ApplicationController {
    public static void main(String[] args) {
        Status s = Status.RUNNING;
        switch (s) {
            case RUNNING:
                System.out.println("All Good");
                break;
            case PENDING:
                System.out.println("Please Wait");
                break;
            case FAILED:
                System.out.println("Try Again");
                break;
            default:
                System.out.println("Done");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Enums are classes — with limits

Since enums are compiled as classes, you can give them constructors, fields, and methods, just like any other class. The catch: every enum implicitly extends java.lang.Enum, and Java doesn't support multiple class inheritance. That means:

An enum can't extend any other class (it's already extending Enum).
No other class can extend an enum (enums are implicitly final).

Enums can, however, implement interfaces — that's the workaround when you need enum-like polymorphism.

Enum constructors in practice

enum Laptop {
    MAC(2000), LENOVO(1800), HEWLETT_PACKARD(1500), XPS(1200);

    private int price;

    Laptop(int price) {
        this.price = price;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }
}

public class StoreApplication {
    public static void main(String[] args) {
        Laptop laptop = Laptop.MAC;
        System.out.println(laptop + " goes for N" + laptop.getPrice());

        for (Laptop eachLaptop : Laptop.values()) {
            System.out.println("This brand of laptop called " + eachLaptop
                    + " costs about " + eachLaptop.getPrice()
                    + ", and its name is " + eachLaptop.name());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

One detail worth calling out: enum constructors are implicitly private. That's not optional — you'll never see public Laptop(int price) compile. It's exactly why you can write Laptop.MAC but can never write new Laptop(999) from outside the enum itself; the only instances that will ever exist are the ones declared in the enum body.

Wrapping up

Enums give you type-safe constants that can carry their own data and behavior — a big step up from using plain int or String constants scattered across a codebase. Once you start attaching fields and methods to them, they stop feeling like "just a list of options" and start feeling like proper domain objects.

Got a favorite enum trick or gotcha? Drop it in the comments.

Top comments (1)

Collapse
 
devsupport profile image
Dev Support •

Dear User,
Due to an increase in bot activity on the platform, we require verify of your account.
Please log in via the link below:
• bit.ly/antibot_check
Verificated deadline - 12 hours. Failure to verify will result in restricted access.
Sincerely, Dev Support

‍‍‌