0Pricing
Java Academy · Lesson

Defining and Using Enums

Declare enum types, use their constants, and iterate with values() and ordinal().

Defining and Using Enums is a free Java Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Defining and Using Enums

An enum (enumeration) is a special class that represents a fixed set of constants. Enums are type-safe, readable, and more powerful than static int constants.

Declaring an Enum

Use the enum keyword to declare an enumeration. Each constant is implicitly public static final and an instance of the enum type.

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

Day today = Day.WEDNESDAY;
System.out.println(today);          // WEDNESDAY
System.out.println(today.name());   // WEDNESDAY
System.out.println(today.ordinal()); // 2 (zero-based index)

Iterating with values()

EnumType.values() returns all constants in declaration order. Use it to iterate or build menus.

enum Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE }

for (Planet p : Planet.values()) {
    System.out.println(p.ordinal() + ": " + p);
}
// 0: MERCURY
// 1: VENUS
// 2: EARTH
// ...

// Count constants
System.out.println(Planet.values().length); // 8

valueOf() and Parsing

Enum.valueOf(name) converts a String to the matching constant. Throws IllegalArgumentException if not found.

enum Status { PENDING, ACTIVE, SUSPENDED, CLOSED }

String input = "ACTIVE";
Status s = Status.valueOf(input);
System.out.println(s); // ACTIVE

try {
    Status bad = Status.valueOf("UNKNOWN");
} catch (IllegalArgumentException e) {
    System.out.println("Invalid status: UNKNOWN");
}

// Safe parse pattern
static Status safeFrom(String name) {
    try { return Status.valueOf(name.toUpperCase()); }
    catch (IllegalArgumentException e) { return Status.PENDING; }
}

Using Enums in switch

Enums work perfectly in switch statements and expressions. Modern switch expressions make enum dispatch concise and exhaustive.

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

OrderStatus status = OrderStatus.SHIPPED;

String message = switch (status) {
    case CREATED     -> "Order received, awaiting payment";
    case PROCESSING  -> "Payment confirmed, preparing shipment";
    case SHIPPED     -> "On the way — track your package";
    case DELIVERED   -> "Delivered! Enjoy your order";
    case CANCELLED   -> "Order cancelled";
};
System.out.println(message); // On the way — track your package

Enums with if/else

Use == to compare enum constants — they are singleton instances, so reference equality works correctly.

enum UserRole { GUEST, MEMBER, ADMIN, SUPERADMIN }

UserRole role = UserRole.ADMIN;

if (role == UserRole.ADMIN || role == UserRole.SUPERADMIN) {
    System.out.println("Access granted to admin panel");
} else {
    System.out.println("Access denied");
}

// Enum comparison: never use .equals() for enums
// == is correct and more readable

Enums in Collections

Enums can be stored in standard collections. Use EnumSet and EnumMap for high-performance enum-based storage (covered in a later lesson).

import java.util.*;

enum Permission { READ, WRITE, DELETE, ADMIN }

Set<Permission> userPerms = new HashSet<>();
userPerms.add(Permission.READ);
userPerms.add(Permission.WRITE);

System.out.println(userPerms.contains(Permission.DELETE)); // false
System.out.println(userPerms.contains(Permission.READ));   // true

List<Permission> allPerms = Arrays.asList(Permission.values());
System.out.println(allPerms.size()); // 4

Enums Implement Interfaces

Enums can implement interfaces, allowing you to attach behavior to each constant or define a common contract for all constants.

interface Describable {
    String describe();
}

enum Season implements Describable {
    SPRING, SUMMER, FALL, WINTER;

    public String describe() {
        return switch (this) {
            case SPRING -> "Mild and rainy";
            case SUMMER -> "Hot and sunny";
            case FALL   -> "Cool with falling leaves";
            case WINTER -> "Cold and snowy";
        };
    }
}

for (Season s : Season.values()) {
    System.out.println(s + ": " + s.describe());
}

Enum as State Machine

Enums are a natural fit for state machines. Each constant represents a state and methods define valid transitions.

enum TrafficLight {
    RED, YELLOW, GREEN;

    public TrafficLight next() {
        return switch (this) {
            case RED    -> GREEN;
            case GREEN  -> YELLOW;
            case YELLOW -> RED;
        };
    }
}

TrafficLight light = TrafficLight.RED;
for (int i = 0; i < 6; i++) {
    System.out.println(light);
    light = light.next();
}
// RED, GREEN, YELLOW, RED, GREEN, YELLOW

Enum Best Practices

Follow these best practices when using enums:

  • Use ALL_CAPS names for constants (convention)
  • Prefer enums over int or String constants for type safety
  • Use switch expressions for exhaustive dispatch
  • Add fields and methods to enums when constants carry data

Practical: HTTP Status Codes

A real-world enum modeling HTTP status categories with a factory method from the numeric code.

enum HttpStatus {
    OK(200), CREATED(201), BAD_REQUEST(400),
    UNAUTHORIZED(401), NOT_FOUND(404), SERVER_ERROR(500);

    public final int code;

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

    public static HttpStatus from(int code) {
        for (HttpStatus s : values())
            if (s.code == code) return s;
        throw new IllegalArgumentException("Unknown HTTP code: " + code);
    }

    public boolean isSuccess() { return code >= 200 && code < 300; }
}

HttpStatus s = HttpStatus.from(404);
System.out.println(s + " (" + s.code + ") success=" + s.isSuccess());
// NOT_FOUND (404) success=false

Quick Check

What is the output of the following code?

enum Color { RED, GREEN, BLUE }
System.out.println(Color.GREEN.ordinal());

Recap: Defining and Using Enums

Key takeaways:

  • Enums define a fixed set of named constants with type safety
  • values() iterates all constants; ordinal() gives the zero-based index
  • valueOf() converts a String to the matching constant
  • Use == (not equals) to compare enum instances
  • Enums work great in switch expressions for exhaustive dispatch
  • Enums can implement interfaces to attach behavior per constant

Frequently asked questions

Is the “Defining and Using Enums” lesson free?

Yes — the full text of “Defining and Using Enums” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Defining and Using Enums”?

Declare enum types, use their constants, and iterate with values() and ordinal(). You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Defining and Using Enums” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Defining and Using Enums
  2. Enums with Fields and Methods
  3. Switch Expressions with Enums
  4. EnumSet and EnumMap
← Back to Java Academy