AI Hints
Home›Java Tutorial›Switch Expressions, Nested Decisions, Practice: Grade Checker
Java · Lesson 34 of 120

Switch Expressions

Modern, safer switch.

⏱ 2 min read▶ Video at 43:43🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Modern Java has a better switch. It uses arrows, it never falls through, and it can give back a value.

  • Arrows, not colons
  • No fall-through
  • Gives back a value

Arrow switch

This switch gives back a value, which we store in name. Each case uses an arrow, and the value after it. Several values can share one case, separated by commas. No break is needed, because arrows never fall through. And notice the semicolon after the closing brace. Run it. Day six is the weekend.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int day = 6;
        String name = switch (day) {
            case 1 -> "Monday";
            case 2 -> "Tuesday";
            case 3 -> "Wednesday";
            case 4 -> "Thursday";
            case 5 -> "Friday";
            case 6, 7 -> "Weekend";
            default -> "Not a day";
        };
        System.out.println("Day " + day + " is " + name);
    }
}
Output
Day 6 is Weekend

Strings and blocks

Switch works with strings too. When a case needs several lines, use curly braces. Yield gives back the value from that block. Size is M. Run it. M costs three pounds.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String size = "M";
        double price = switch (size) {
            case "S" -> 2.50;
            case "M" -> 3.00;
            case "L" -> {
                System.out.println("Large chosen");
                yield 3.50;
            }
            default -> 0;
        };
        System.out.println(size + " costs " + price);
    }
}
Output
M costs 3.0

Old or new

The old switch uses colons, and needs break. The new switch uses arrows, can't fall through, and can give back a value. In new code, prefer the arrow form.

Old switch

  • case 1:Needs breakStatements only

Switch expression

  • case 1 ->No fall-throughGives a value

Summary

Switch expressions use arrows, never fall through, and give back a value. Prefer them in new code. Next, decisions inside decisions.

Key takeaways
  • case x -> value
  • case a, b ->
  • yield in blocks
Next up: Nested Decisions — if inside if