Java Switch是否支持字符串比较

发布时间:2025-04-12 02:47:03 作者:小樊
来源:亿速云 阅读:97

是的,从Java 7开始,switch语句支持字符串比较。在这之前,switch语句只支持整数、字符、枚举类型和字节、短整型、整型和长整型。使用字符串作为switch表达式的值时,需要确保字符串不为null,否则会抛出NullPointerException。

以下是一个简单的示例:

public class SwitchStringExample {
    public static void main(String[] args) {
        String day = "Monday";

        switch (day) {
            case "Monday":
                System.out.println("It's Monday, the start of the workweek.");
                break;
            case "Tuesday":
                System.out.println("It's Tuesday, second day of the week.");
                break;
            case "Wednesday":
                System.out.println("It's Wednesday, middle of the week.");
                break;
            case "Thursday":
                System.out.println("It's Thursday, almost weekend.");
                break;
            case "Friday":
                System.out.println("It's Friday, the end of the workweek.");
                break;
            case "Saturday":
                System.out.println("It's Saturday, enjoy your weekend!");
                break;
            case "Sunday":
                System.out.println("It's Sunday, relax and prepare for the next week.");
                break;
            default:
                System.out.println("Invalid day");
        }
    }
}

在这个例子中,我们使用字符串变量day作为switch表达式的值,并根据其值执行相应的代码块。

推荐阅读:
  1. java比较字符串是否相等的方法
  2. java中用什么方法比较字符串?

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Java Switch如何实现多路分支

下一篇:索引对数据库性能影响

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》