Video in progress

Junior ☕ Core Java

What makes the switch expression in Java 14+ better than the old switch?

The new switch returns a value, is written with -> and needs no break, so "fall-through" bugs go away. If an enum or sealed type isn't fully covered, the compiler gives an error.

📖 Answer

The old one:

String label;
switch (status) {
    case NEW: label = "Yangi"; break;
    case PAID: label = "To'langan"; break;
    case SHIPPED: label = "Jo'natildi";   // break was forgotten: it falls into the next one
    default: label = "Noma'lum";
}

The new one:

String label = switch (status) {
    case NEW -> "Yangi";
    case PAID -> "To'langan";
    case SHIPPED, DELIVERED -> "Yo'lda yoki yetkazilgan";
    case CANCELLED -> {
        log.info("cancelled");
        yield "Bekor qilingan";   // returning a value from a block
    }
};

The result goes straight into the variable, and several values go on one line. The most useful part is something else: if a new value is added to the enum and there's no default, every switch expression gives a compile error, so no case gets forgotten.

That's why in a switch over an enum we often leave out default on purpose.