Switch的新特性,早在JDK 12就以预览功能被引入了,最终在JDK 14成为了正式版本的功能:JEP 361: Switch Expressions (Standard)。其实Switch新增的特性有两个,一个就是允许每个case包含多个常量,一个就是switch-case块可以有返回值。本文主要介绍Java(JDK) 14中, Switch表达式使用方法,以及相关示例代码。

1、case包含多个常量

单个的写法:

public void daysOfMonth(int month) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.println("this month has 31 days");
break;
case 4:
case 6:
case 9:
System.out.println("this month has 30 days");
break;
case 2:
System.out.println("February can have 28 or 29 days");
break;
default:
System.out.println("invalid month");
}
}

多个常量的写法:

switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> System.out.println("this month has 31 days");
case 4, 6, 9 -> System.out.println("this month has 30 days");
case 2 -> System.out.println("February can have 28 or 29 days");
default -> System.out.println("invalid month");
}

新语法“ case L->”,开关块代码看起来更加清晰,简洁和可读。可以使用多个常量来减少代码,并且不必显式使用break语句来跳出,从而减少了容易出错的代码(没有失败,也没有中断)。

switch新语法中,箭头标签后面的代码可以是表达式,块或throw语句。例如:

switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> System.out.println("this month has 31 days");
case 4, 6, 9 -> System.out.println("this month has 30 days");
case 2 -> {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter year: ");
int year = scanner.nextInt();
if (year % 4 == 0)
System.out.println("This february has 29 days");
else
System.out.println("This February has 28 days");
}
default -> throw new IllegalArgumentException("Invalid month");
}

注意:新语法的switch表达式,由于代码不会进入下一种情况,因此我们不必每种情况使用break中断。

2、switch-case中返回值

从Java 14开始,可以在表达式中使用switch case块,也就是switch块可以返回一个值。对于传统的switch语句,我们必须使用临时变量,如以下代码示例所示:

int days = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
days = 30;
break;
case 2:
days = 28;
break;
default:
throw new IllegalArgumentException("Invalid month");
}

在switch-case中返回值:

int days = switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9 -> 30;
case 2 -> 28;
default -> 0;
};

System.out.println(
switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9 -> 30;
case 2 -> 28;
default -> 0;
}
);

int days = switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9 -> 30;
case 2 -> {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter year: ");
int year = scanner.nextInt();
if (year % 4 == 0)
yield 29;
else
yield 28;
}
default -> 0;
};

int days = switch (month) {
case 1, 3, 5, 7, 8, 10, 12:
yield 31;
case 4, 6, 9:
yield 30;
case 2: {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter year: ");
int year = scanner.nextInt();
if (year % 4 == 0)
yield 29;
else
yield 28;
}
default: yield 0;
};

注意:不能在Switch代码块中同时使用“case L:”“case L->”

相关文档:

Java JDK13(Java 13) switch新特性语法使用及示例代码

Java中switch用法示例

推荐文档