Tsallaka zuwa abun ciki
Justice Tech School

Switch Expressions and Pattern Matching

Modern switch uses arrows, returns a value and needs no break. Patterns match types, and yield returns from a block. Enhanced for and labelled breaks complete the flow tools.

Example
int day = 3;
String name = switch (day) { case 1, 7 -> "Weekend"; case 2, 3, 4, 5, 6 -> "Weekday"; default -> "Invalid"; };
System.out.println(name);
Object o = 42;
String d = switch (o) { case Integer i when i > 40 -> "big int"; case Integer i -> "int"; case String s -> "text"; default -> "other"; };
System.out.println(d);

Result

Weekday
big int

Exercise

Arrow in a switch case.

case 1  "a";

Quiz Test

Does an arrow case need break?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.