switch 声明:
与if/else if/else 语句不同,switch 语句可以有多个可能的执行路径。 switch 适用于原始类型 byte、short、char 和 int,它们各自的包装类型(Byte、Short、Character 和 Integer),枚举类型和String 类型1。 if-else 语句用于测试基于值范围或条件的表达式,而switch 语句用于测试仅基于单个值的表达式。
演示
enum PaymentStatus {
UNPAID, PARTPAID, PAID, DISPUTED, UNKNOWN;
}
public class Main {
public static void main(String[] args) {
String message = "";
PaymentStatus paymentStatus = PaymentStatus.PARTPAID;
switch (paymentStatus) {
case UNPAID:
message = "The order has not been paid yet. Please make the minimum/full amount to procced.";
break;
case PARTPAID:
message = "The order is partially paid. Some features will not be available. Please check the brochure for details.";
break;
case PAID:
message = "The order is fully paid. Please choose the desired items from the menu.";
break;
default:
throw new IllegalStateException("Invalid payment status: " + paymentStatus);
}
System.out.println(message);
}
}
输出:
The order is partially paid. Some features will not be available. Please check the brochure for details.
switch 表达式:
switch 表达式是在 Java SE 12 中引入的。但是,它仍然作为 Java SE 12 和 13 中的预览功能,最终在 Java SE 14 中实现了标准化。Like any expression,@ 987654341@ 表达式计算为单个值,并且可以在语句中使用。它还引入了“箭头case”标签,无需break 语句来防止失败。从 Java SE 15 开始,支持的数据类型没有变化(在上面的 switch 语句部分中提到)。
演示
enum PaymentStatus {
UNPAID, PARTPAID, PAID, DISPUTED, UNKNOWN;
}
public class Main {
public static void main(String[] args) {
PaymentStatus paymentStatus = PaymentStatus.PARTPAID;
String message = switch (paymentStatus) {
case UNPAID -> "The order has not been paid yet. Please make the minimum/full amount to procced.";
case PARTPAID -> "The order is partially paid. Some features will not be available. Please check the brochure for details.";
case PAID -> "The order is fully paid. Please choose the desired items from the menu.";
default -> throw new IllegalStateException("Invalid payment status: " + paymentStatus);
};
System.out.println(message);
}
}
输出:
The order is partially paid. Some features will not be available. Please check the brochure for details.
switch 表达式与yield:
从 Java SE 13 开始,您可以使用 yield 语句而不是箭头运算符 (->) 从 switch 表达式返回值。
演示
enum PaymentStatus {
UNPAID, PARTPAID, PAID, DISPUTED, UNKNOWN;
}
public class Main {
public static void main(String[] args) {
PaymentStatus paymentStatus = PaymentStatus.PARTPAID;
String message = switch (paymentStatus) {
case UNPAID:
yield "The order has not been paid yet. Please make the minimum/full amount to procced.";
case PARTPAID:
yield "The order is partially paid. Some features will not be available. Please check the brochure for details.";
case PAID:
yield "The order is fully paid. Please choose the desired items from the menu.";
default:
throw new IllegalStateException("Invalid payment status: " + paymentStatus);
};
System.out.println(message);
}
}
输出:
The order is partially paid. Some features will not be available. Please check the brochure for details.
1 JDK 7 添加了对String 的支持