Java switch Expressions Explained: Syntax, Arrow Cases, yield & Examples

0

Traditional switch statements are useful for selecting one block of code from several choices. Modern Java also provides switch expressions, which make this decision-making syntax more concise and allow the result of the switch to be directly assigned to a variable or returned from a method.

Why Do We Need switch Expressions?

With a traditional switch statement, developers often need a variable outside the switch and then assign a value inside each case. This can create repetitive code.

int day = 2;
String dayName;

switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    default:
        dayName = "Invalid day";
}

A switch expression can make the same logic much cleaner because the switch itself can produce the value.

Basic Idea

String dayName = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    case 3 -> "Wednesday";
    default -> "Invalid day";
};

Here, the switch expression produces a String value. That value is directly assigned to dayName.

The key difference is simple: a traditional switch mainly controls execution, while a switch expression can produce a value.

What Is the Arrow Operator?

Modern switch expressions commonly use the -> arrow syntax.

int number = 2;

String result = switch (number) {
    case 1 -> "One";
    case 2 -> "Two";
    case 3 -> "Three";
    default -> "Other";
};

When number is 2, the matching case produces the value "Two".

Unlike the traditional colon-based syntax, an arrow case does not automatically continue into the following case. This makes the code easier to reason about.

switch Expression with yield

Sometimes a case needs multiple statements before producing a value. In that situation, Java provides the yield statement.

int marks = 85;

String result = switch (marks / 10) {
    case 10, 9 -> {
        System.out.println("Excellent performance");
        yield "A";
    }
    case 8 -> {
        yield "B";
    }
    case 7, 6 -> {
        yield "C";
    }
    default -> {
        yield "Needs improvement";
    }
};

The block form allows multiple statements inside a case. The yield statement provides the value that the switch expression produces.

Remember: Use yield when a block-form switch expression needs to produce a value after executing multiple statements.

Multiple Case Labels

Switch expressions can group multiple case labels when they should produce the same result.

int day = 6;

String type = switch (day) {
    case 1, 2, 3, 4, 5 -> "Weekday";
    case 6, 7 -> "Weekend";
    default -> "Invalid day";
};

Here, days 1 through 5 produce "Weekday", while days 6 and 7 produce "Weekend".

switch Expression with String

A switch expression can also work with String values.

String role = "admin";

String dashboard = switch (role) {
    case "admin" -> "Admin Dashboard";
    case "teacher" -> "Teacher Dashboard";
    case "student" -> "Student Dashboard";
    default -> "Unknown Role";
};

System.out.println(dashboard);

The switch expression evaluates the role and directly produces the corresponding dashboard name.

switch Statement vs switch Expression

Feature switch Statement switch Expression
Primary purpose Controls which code block executes. Selects and produces a value.
Common syntax case value: case value ->
break Commonly required with traditional cases. Not required with arrow cases.
Multiple statements Written directly inside the case. Can use a block with yield.
Value assignment Usually requires separate assignments. Can directly assign the switch result.

Example: Calculating a Discount

String customerType = "premium";

int discount = switch (customerType) {
    case "premium" -> 20;
    case "regular" -> 10;
    case "new" -> 5;
    default -> 0;
};

System.out.println("Discount: " + discount + "%");

The switch expression evaluates the customer type and directly produces the appropriate discount percentage. This is a good example of where the expression style makes the intent immediately visible.

Why switch Expressions Are Safer

Traditional switch statements can accidentally fall through when break is forgotten. Arrow-style switch expressions do not have this accidental fall-through behavior.

String result = switch (number) {
    case 1 -> "One";
    case 2 -> "Two";
    default -> "Other";
};

Each arrow case represents a separate result. After the selected case completes, the switch expression produces its value without continuing into the next case.

Common Beginner Mistakes

  • Confusing a switch statement with a switch expression.
  • Trying to use break as if it were required for arrow cases.
  • Forgetting that an expression must produce a value when it is assigned to a variable.
  • Forgetting yield inside a block-form switch expression that needs to return a value.
  • Not handling possible unmatched values when a default case is appropriate.

Best Practices

  • Use switch expressions when the purpose is to calculate or select a value.
  • Prefer arrow syntax when it makes the decision logic clearer.
  • Use yield when a case needs multiple statements before producing its result.
  • Group case labels when several values should produce the same result.
  • Keep each case short and focused on one logical outcome.

Interview Insight

A common interview question is: “What is the main difference between a switch statement and a switch expression?”

A switch statement is primarily used to control which block of code executes. A switch expression can evaluate the cases and produce a value that can be assigned, returned, or used as part of another expression.

Quick Revision

Concept Key Point
switch expression Produces a value based on matching cases.
Arrow syntax Uses -> and avoids traditional fall-through behavior.
yield Produces a value from a block-form switch expression.
Multiple labels Several case values can share one result.
default Handles values that do not match another case.

Switch expressions bring a cleaner and more expressive style to Java's decision-making capabilities. Instead of using a switch merely to control which statements execute, you can use it to directly produce a result. With decision-making covered, the next major part of Java control flow is repetition, beginning with the for loop.

Post a Comment

0Comments
Post a Comment (0)