switch
String day = "MONDAY"; switch (day) { case "MONDAY": System.out.println("星期一"); break; case "TUESDAY": System.out.println("星期二"); break; default: System.out.println("其他日子"); break; }
break
String day = "MONDAY"; String result = switch (day) { case "MONDAY" -> "星期一"; case "TUESDAY" -> "星期二"; default -> "其他日子"; };
String day = "MONDAY"; String result = switch (day) { case "MONDAY" -> { System.out.println("这是一周的开始"); yield "星期一"; } case "TUESDAY" -> { System.out.println("继续努力"); yield "星期二"; } default -> "其他日子"; };
Object obj = "Hello"; String result = switch (obj) { case Integer i -> "这是一个整数:" + i; case String s -> "这是一个字符串:" + s; case null -> "这是null值"; default -> "其他类型"; };
sealed interface Shape permits Rectangle, Circle {} record Rectangle(double length, double width) implements Shape {} record Circle(double radius) implements Shape {} String result = switch (shape) { case Rectangle(var length, var width) -> "矩形:长度 = " + length + ", 宽度 = " + width; case Circle(var radius) -> "圆形:半径 = " + radius; };