Java如何在switch语句中使用字符串?

从Java 7版本开始,您现在可以String在switch语句中使用。在以前的版本中,我们只能用常量型的byte,char,short,int (以及它们相应的参考/包装型)或enum在常量switch声明。

下面的代码为您提供了有关Java 7如何扩展以允许使用Stringinswitch语句的简单示例。

package org.nhooo.example.basic;

public class StringInSwitchExample {
    public static void main(String[] args) {
        String day = "Sunday";
        switch (day) {
            case "Sunday":
                System.out.println("doSomething");
                break;
            case "Monday":
                System.out.println("doSomethingElse");
                break;
            case "Tuesday":
            case "Wednesday":
                System.out.println("doSomeOtherThings");
                break;
            default:
                System.out.println("doDefault");
                break;
        }
    }
}