0Pricing
Java Academy · Lesson

Switch Expressions with Enums

Use modern switch expressions with enums for clean, exhaustive branching.

Switch Expressions with Enums is a free Java Academy lesson on CoddyKit — lesson 3 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.

Switch Expressions with Enums

Switch expressions (Java 14+) with enums provide exhaustive, concise type-based routing. When all enum constants are covered, no default is needed.

Traditional Switch Statement

The classic switch statement works with enums but requires break to prevent fall-through.

enum Severity { LOW, MEDIUM, HIGH, CRITICAL }

Severity s = Severity.HIGH;
String action;
switch (s) {
    case LOW:
        action = "Log and monitor";
        break;
    case MEDIUM:
        action = "Notify on-call team";
        break;
    case HIGH:
        action = "Page engineer immediately";
        break;
    case CRITICAL:
        action = "Activate incident response";
        break;
    default:
        action = "Unknown";
}
System.out.println(action); // Page engineer immediately

Switch Expression with Arrow Labels

Arrow-label switch expressions eliminate fall-through and break. They evaluate to a value and require exhaustiveness.

enum Severity { LOW, MEDIUM, HIGH, CRITICAL }

Severity s = Severity.HIGH;
String action = switch (s) {
    case LOW      -> "Log and monitor";
    case MEDIUM   -> "Notify on-call team";
    case HIGH     -> "Page engineer immediately";
    case CRITICAL -> "Activate incident response";
    // no default needed — all cases covered
};
System.out.println(action); // Page engineer immediately

Switch Expression with Blocks

When the case logic requires multiple statements, use a block with yield to produce the result value.

enum DayOfWeek { MON, TUE, WED, THU, FRI, SAT, SUN }

DayOfWeek day = DayOfWeek.FRI;
int hoursOpen = switch (day) {
    case MON, TUE, WED, THU -> 8;
    case FRI -> {
        System.out.println("Half day on Friday!");
        yield 4;  // yield returns value from block
    }
    case SAT, SUN -> 0;
};
System.out.println("Hours open: " + hoursOpen); // Hours open: 4

Grouping Multiple Cases

Multiple enum constants can share the same case using comma separation.

enum Season { SPRING, SUMMER, FALL, WINTER }

Season season = Season.SUMMER;
String activity = switch (season) {
    case SPRING, FALL -> "Hike in the mountains";
    case SUMMER       -> "Beach vacation";
    case WINTER       -> "Ski at the resort";
};
System.out.println(activity); // Beach vacation

Returning from Methods with Switch

Switch expressions work great as return statements in methods, making the intent clear.

enum Priority { LOW, NORMAL, HIGH, URGENT }

static int getSlaHours(Priority p) {
    return switch (p) {
        case LOW    -> 72;
        case NORMAL -> 24;
        case HIGH   -> 4;
        case URGENT -> 1;
    };
}

System.out.println(getSlaHours(Priority.URGENT)); // 1
System.out.println(getSlaHours(Priority.LOW));    // 72

Switch Expression in Stream

Switch expressions can be used inside stream operations for clean per-element transformations.

import java.util.*;
import java.util.stream.*;

enum Status { PENDING, ACTIVE, CLOSED }

record Account(String id, Status status) {}

List<Account> accounts = List.of(
    new Account("A1", Status.ACTIVE),
    new Account("A2", Status.PENDING),
    new Account("A3", Status.CLOSED)
);

accounts.stream()
    .map(a -> a.id() + ": " + switch (a.status()) {
        case ACTIVE  -> "\u2705 Live";
        case PENDING -> "\u23f3 Awaiting activation";
        case CLOSED  -> "\u274c Deactivated";
    })
    .forEach(System.out::println);

Compile-Time Exhaustiveness

The compiler enforces that all enum constants are covered. Adding a new constant to an enum causes compile errors in all switch expressions that don't handle it.

enum Color { RED, GREEN, BLUE }  // add YELLOW here → compile error below

Color c = Color.GREEN;
// This switch is exhaustive for RED, GREEN, BLUE
// If you add YELLOW to the enum without adding a case here,
// the compiler will report an error.
String hex = switch (c) {
    case RED   -> "#FF0000";
    case GREEN -> "#00FF00";
    case BLUE  -> "#0000FF";
};
System.out.println(hex); // #00FF00

Switch with default for Safety

When using a switch statement (not expression) or when the switch covers only some cases intentionally, add a default case.

enum Feature { DARK_MODE, PUSH_NOTIFICATIONS, ANALYTICS, BETA_FEATURE }

static boolean isEnabled(Feature feature) {
    return switch (feature) {
        case DARK_MODE, PUSH_NOTIFICATIONS -> true;
        case ANALYTICS                     -> false;
        default -> {
            System.out.println("Unknown feature: " + feature);
            yield false;
        }
    };
}
System.out.println(isEnabled(Feature.DARK_MODE));     // true
System.out.println(isEnabled(Feature.BETA_FEATURE));  // false

Practical: Order Lifecycle

A complete order lifecycle state machine using switch expression to determine allowed transitions.

enum OrderState { CART, PENDING, CONFIRMED, SHIPPED, DELIVERED, CANCELLED }

static Set<OrderState> allowedTransitions(OrderState from) {
    return switch (from) {
        case CART      -> Set.of(OrderState.PENDING, OrderState.CANCELLED);
        case PENDING   -> Set.of(OrderState.CONFIRMED, OrderState.CANCELLED);
        case CONFIRMED -> Set.of(OrderState.SHIPPED);
        case SHIPPED   -> Set.of(OrderState.DELIVERED);
        case DELIVERED, CANCELLED -> Set.of(); // terminal states
    };
}
System.out.println(allowedTransitions(OrderState.PENDING));
// [CONFIRMED, CANCELLED]

Switch on String vs Enum

Switching on a String requires a null check and is case-sensitive. Switching on an enum is null-safe (NPE if null) and type-safe — prefer enums when the set of values is known.

// String switch — fragile
String role = "admin";
String label = switch (role.toLowerCase()) {
    case "admin" -> "Administrator";
    case "guest" -> "Guest User";
    default      -> "Unknown";
};

// Enum switch — type-safe
enum Role { ADMIN, GUEST }
Role r = Role.ADMIN;
String label2 = switch (r) {
    case ADMIN -> "Administrator";
    case GUEST -> "Guest User";
};
System.out.println(label2); // Administrator

Quick Check

You have an enum with 4 constants and write a switch expression covering all 4. What happens if you add a 5th constant to the enum?

Recap: Switch Expressions with Enums

Key takeaways:

  • Arrow-label switch expressions eliminate break and fall-through
  • Use yield to return a value from a block case
  • Group multiple constants with commas: case A, B ->
  • Exhaustive switch expressions require no default when all constants are covered
  • Adding a new enum constant causes compile errors in exhaustive switch expressions
  • Switch expressions are great in stream map() operations

Frequently asked questions

Is the “Switch Expressions with Enums” lesson free?

Yes — the full text of “Switch Expressions with 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 “Switch Expressions with Enums”?

Use modern switch expressions with enums for clean, exhaustive branching. 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 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Switch Expressions with 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