0Pricing
Java Academy · Lesson

switch as an Expression

Return values from switch.

Statements vs Expressions

A statement performs an action. An expression produces a value. Modern Java lets switch be an expression, so you can assign its result directly to a variable.

Assigning a switch Result

When switch appears on the right side of =, each branch supplies the value. The arrow form returns the value after -> automatically.

public class Main {
    public static void main(String[] args) {
        int day = 6;
        String type = switch (day) {
            case 6, 7 -> "Weekend";
            default -> "Weekday";
        };
        System.out.println(type);
    }
}

All lessons in this course

  1. Arrow-Style switch
  2. switch as an Expression
  3. The yield Keyword
  4. Multi-Label Cases
← Back to Java Academy