Master Core Java Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

Module 9

Switch Expressions in Java

Learn modern switch expressions, arrow labels, yield, and pattern-oriented syntax.

🔀

1. What is a Switch Expression?

A traditional switch statement is mainly used to control program flow. A modern Java switch expression can also produce a value.

Switch expressions were introduced as a preview feature in Java 12 and became a standard language feature in Java 14.

Key idea: A switch expression evaluates to a value that can be assigned to a variable or returned from a method.

2. switch Statement

The older switch syntax commonly uses case, break, and mutable variables.

Java
int day = 2;
String name;

switch (day) {

    case 1:
        name = "Monday";
        break;

    case 2:
        name = "Tuesday";
        break;

    default:
        name = "Unknown";
}

3. Arrow Syntax

Modern switch expressions can use -> instead of the traditional colon syntax.

Arrow labels do not fall through to the next case.

Java
int day = 2;

switch (day) {

    case 1 -> System.out.println("Monday");
    case 2 -> System.out.println("Tuesday");
    case 3 -> System.out.println("Wednesday");
    default -> System.out.println("Other day");
}
Benefit: Arrow labels eliminate accidental fall-through between cases.

4. Switch Expression Returning a Value

A switch expression can directly return a value.

Java
int day = 2;

String dayName = switch (day) {

    case 1 -> "Monday";
    case 2 -> "Tuesday";
    case 3 -> "Wednesday";
    case 4 -> "Thursday";
    case 5 -> "Friday";
    case 6 -> "Saturday";
    case 7 -> "Sunday";

    default -> "Invalid day";
};

System.out.println(dayName);

5. Multiple Case Labels

Multiple constants can be handled by a single switch arm.

Java
int day = 6;

String type = switch (day) {

    case 1, 2, 3, 4, 5 -> "Weekday";

    case 6, 7 -> "Weekend";

    default -> "Invalid";
};

System.out.println(type);

6. Block Body

A switch arm can contain multiple statements by using braces.

Java
int number = 10;

String result = switch (number) {

    case 10 -> {
        System.out.println("Number is ten");
        yield "TEN";
    }

    default -> {
        System.out.println("Other number");
        yield "OTHER";
    }
};

System.out.println(result);

7. yield Keyword

The yield keyword is used to return a value from a block inside a switch expression.

Java
int score = 80;

String grade = switch (score / 10) {

    case 10, 9 -> "A";

    case 8 -> {
        System.out.println("Very good");
        yield "B";
    }

    case 7 -> "C";

    case 6 -> "D";

    default -> "F";
};

System.out.println(grade);
Remember: Use yield when the switch arm uses a block and needs to produce a value.

8. Exhaustiveness

A switch expression must be exhaustive. It must handle every possible input value.

For many types, a default case is used to cover remaining values.

Java
int value = 5;

String result = switch (value) {

    case 1 -> "One";
    case 2 -> "Two";

    default -> "Other";
};

9. Switch Expressions with Enum

Switch expressions work particularly well with enums.

Java
enum Level {
    LOW,
    MEDIUM,
    HIGH
}

Level level = Level.HIGH;

String message = switch (level) {

    case LOW -> "Low priority";

    case MEDIUM -> "Medium priority";

    case HIGH -> "High priority";
};

System.out.println(message);
Advantage: When all enum constants are covered, a separate default may not be necessary.

10. Switch Expressions with String

Strings can also be used with switch expressions.

Java
String language = "Java";

String category = switch (language) {

    case "Java" -> "Programming Language";

    case "SQL" -> "Database Language";

    case "HTML" -> "Markup Language";

    default -> "Unknown";
};

System.out.println(category);

11. Switch Expressions with Character

Java
char grade = 'A';

String result = switch (grade) {

    case 'A' -> "Excellent";

    case 'B' -> "Good";

    case 'C' -> "Average";

    default -> "Needs improvement";
};

System.out.println(result);

12. Switch Expression in a Method

A switch expression can be returned directly from a method.

Java
public static String getDayType(int day) {

    return switch (day) {

        case 1, 2, 3, 4, 5 -> "Weekday";

        case 6, 7 -> "Weekend";

        default -> "Invalid";
    };
}

13. Avoid Complex Nested Switches

Although switch expressions are concise, deeply nested switches can still make code difficult to understand.

Java
String result = switch (type) {

    case "A" -> {
        yield switch (status) {
            case "ACTIVE" -> "Running";
            default -> "Stopped";
        };
    }

    default -> "Unknown";
};

For complex business logic, consider extracting logic into separate methods.

14. Switch and Pattern Matching

Modern Java also supports pattern matching with switch. This makes it possible to select behavior based on the type and characteristics of an object.

Java
static String describe(Object value) {

    return switch (value) {

        case String text ->
            "String: " + text;

        case Integer number ->
            "Integer: " + number;

        case null ->
            "null";

        default ->
            "Other type";
    };
}
Modern Java: Pattern matching for switch became a standard feature in Java 21.

15. Pattern Matching with when

In modern Java, additional conditions can be expressed using a when guard in pattern matching.

Java
static String classify(Object value) {

    return switch (value) {

        case Integer number when number > 0 ->
            "Positive integer";

        case Integer number ->
            "Zero or negative integer";

        case String text ->
            "Text";

        default ->
            "Other";
    };
}
Version note: The guarded when syntax is part of the modern pattern-matching switch language evolution and requires an appropriate recent Java version.

16. Handling null

Modern pattern matching switch can explicitly handle null.

Java
static String check(Object value) {

    return switch (value) {

        case null -> "Value is null";

        case String text ->
            "Text value";

        default ->
            "Other value";
    };
}

17. Advantages of Switch Expressions

  • Can directly return a value.
  • Reduces boilerplate code.
  • Arrow syntax prevents accidental fall-through.
  • Supports multiple labels.
  • Works well with enums and strings.
  • Supports block expressions using yield.
  • Works with modern pattern matching.
  • Improves readability for many branching operations.

18. Traditional switch vs Switch Expression

Traditional switch Modern switch expression
Usually statement-oriented Can produce a value
Often requires break Arrow labels avoid fall-through
More verbose More concise
Uses case with colon frequently Can use arrow syntax
No yield concept Uses yield inside block arms

19. Example 😁🫥

Java
public class Main {

    public static String getCategory(String language) {

        return switch (language) {

            case "Java" ->
                "Object-Oriented Programming";

            case "SQL" ->
                "Database";

            case "HTML", "CSS" ->
                "Web";

            default ->
                "Other";
        };
    }

    public static void main(String[] args) {

        String language = "Java";

        String category =
            getCategory(language);

        System.out.println(
            "Language: " + language
        );

        System.out.println(
            "Category: " + category
        );
    }
}

20. Best Practices

  • Use switch expressions when a branch naturally produces a value.
  • Prefer arrow syntax for modern code.
  • Keep each switch arm simple.
  • Use exhaustive handling where practical.
  • Use yield only when a block needs to produce a value.
  • Use pattern matching when type-based branching improves clarity.
  • Avoid deeply nested switch expressions.
  • Use an appropriate Java version for the language features being used.

21. Interview Questions

A switch expression is a modern Java switch construct that evaluates to a value.

Switch expressions became a standard Java language feature in Java 14 after being introduced through preview releases.

yield returns a value from a block inside a switch expression.

Arrow syntax prevents the traditional fall-through behavior and makes switch branches more concise.

Exhaustive means that every possible input value is handled, either through explicit cases or a default branch.

Pattern matching allows a switch to match values based on their types and additional conditions.

Summary

In this lesson, you learned:

  • Traditional switch statements
  • Modern switch expressions
  • Arrow syntax
  • Multiple case labels
  • Switch expressions returning values
  • The yield keyword
  • Exhaustive switch expressions
  • Switch expressions with enums and strings
  • Pattern matching with switch
  • Modern null handling
  • Best practices for switch expressions