什么是switch表达式,它们与switch语句有何不同? [英] What are switch expressions and how are they different from switch statements?

查看:64
本文介绍了什么是switch表达式,它们与switch语句有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为Java SE 12的一部分, 引入了switch 表达式,自Java SE 14开始,它们已经标准化.它们与 switch 语句有何不同?

解决方案

switch 语句:

if/else if/else 语句不同, switch 语句可以具有许多可能的执行路径.一个 switch 可以使用以下原始类型: byte short char int ,它们各自的包装器类型( Byte Short Character Integer ),枚举类型和 String 类型为 1 .虽然 if-else 语句用于根据值或条件的范围来测试表达式,但是 switch 语句用于仅基于单个值来测试表达式.

演示

 枚举PaymentStatus {UNPAID,PARAPAID,PAID,已争议,未知;}公共班级主要{公共静态void main(String [] args){字符串消息=";PaymentStatus paymentStatus = PaymentStatus.PARTPAID;切换(paymentStatus){案件UNPAID:message =订单尚未支付.请输入要处理的最低/全部金额.休息;案例PARTPAID:message =订单已部分支付.某些功能将不可用.请查看手册以获取详细信息.休息;付费案例:message =订单已全额支付.请从菜单中选择所需的项目.休息;默认:抛出新的IllegalStateException(无效的付款状态:" + paymentStatus);}System.out.println(message);}} 

输出:

 订单已部分支付.某些功能将不可用.请查看手册以获取详细信息. 

switch 表达式:

switch 表达式是Java SE 12引入的.但是,它仍然是Java SE 12和13中的 Preview 功能,并最终通过Java SE 14进行了标准化.像任何表达式一样 switch 表达式计算为单个值,并且可以在语句中使用.它还引入了箭头 case "标签消除了 break 语句以防止失败的需要.从Java SE 15开始,支持的数据类型没有变化(在上面的 switch 语句部分中提到).

演示

 枚举PaymentStatus {UNPAID,PARAPAID,PAID,已争议,未知;}公共班级主要{公共静态void main(String [] args){PaymentStatus paymentStatus = PaymentStatus.PARTPAID;字串讯息=切换(paymentStatus){案例UNPAID->"订单尚未支付.请输入要处理的最低/全部金额.案例PARTPAID->订单已部分支付.某些功能将不可用.请查看手册以获取详细信息.案例付款->"订单已全额支付.请从菜单中选择所需的项目.默认->抛出新的IllegalStateException(无效的付款状态:" + PaymentStatus);};System.out.println(message);}} 

输出:

 订单已部分支付.某些功能将不可用.请查看手册以获取详细信息. 

带有 yield switch 表达式:

从Java SE 13开始,您可以使用 yield 语句而不是箭头运算符(->)从 switch 表达式返回值.

演示

 枚举PaymentStatus {UNPAID,PARAPAID,PAID,已争议,未知;}公共班级主要{公共静态void main(String [] args){PaymentStatus paymentStatus = PaymentStatus.PARTPAID;字串讯息=切换(paymentStatus){案件UNPAID:yield"该订单尚未付款.请输入要处理的最低/全部金额.案例PARTPAID:产生订单已部分支付.某些功能将不可用.请查看手册以获取详细信息.付费案例:产生订单已全额支付.请从菜单中选择所需的项目.默认:抛出新的IllegalStateException(无效的付款状态:" + PaymentStatus);};System.out.println(message);}} 

输出:

 订单已部分支付.某些功能将不可用.请查看手册以获取详细信息. 


1 JDK 7添加了对 String 的支持

As part of Java SE 12, switch expressions were introduced and since Java SE 14, they have been standardized. How are they different from switch statements?

解决方案

The switch statement:

Unlike the if/else if/else statement, a switch statement can have a number of possible execution paths. A switch works with the primitive types, byte, short, char, and int, their respective wrapper types (Byte, Short, Character, and Integer), enumerated types, and the String type1. While an if-else statement is used to test expressions based on ranges of values or conditions, a switch statement is used to test expressions based only on a single value.

Demo

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);
    }
}

Output:

The order is partially paid. Some features will not be available. Please check the brochure for details.

The switch expression:

The switch expression was introduced with Java SE 12. However, it remained as a Preview feature in Java SE 12 and 13 and finally got standardized with Java SE 14. Like any expression, switch expressions evaluate to a single value, and can be used in statements. It also introduced "arrow case" labels eliminating the need for break statements to prevent fall through. As of Java SE 15, there is no change in the supported data types (mentioned in the switch statement section above).

Demo

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);
    }
}

Output:

The order is partially paid. Some features will not be available. Please check the brochure for details.

The switch expression with yield:

Since Java SE 13, you can use yield statement, instead of the arrow operator (->), to return a value from a switch expression.

Demo

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);
    }
}

Output:

The order is partially paid. Some features will not be available. Please check the brochure for details.


1 The support for String was added with JDK 7

这篇关于什么是switch表达式,它们与switch语句有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆