switch 语句能否作用在 byte 上;作用在 long 上;作用在 String 上?

在 Java 中,switch 语句可以作用于多种类型,具体情况如下:

  1. 可以作用于 byte 类型: byte 类型可以隐式转换为 int,因此可以用作 switch 语句的条件表达式。

  

public class SwitchByteExample {
    public static void main(String[] args) {
        byte b = 2;
        switch (b) {
            case 1:
                System.out.println("Byte is 1");
                break;
            case 2:
                System.out.println("Byte is 2");
                break;
            case 3:
                System.out.println("Byte is 3");
                break;
            default:
                System.out.println("Byte is unknown");
                break;
        }
    }
}

  2.不能作用于 long 类型: long 类型不能隐式转换为 int,因此不能直接用作 switch 语句的条件表达式。

public class SwitchLongExample {
    public static void main(String[] args) {
        long l = 2L;
        // 编译错误:cannot switch on a value of type long
        switch (l) {
            case 1L:
                System.out.println("Long is 1");
                break;
            case 2L:
                System.out.println("Long is 2");
                break;
            case 3L:
                System.out.println("Long is 3");
                break;
            default:
                System.out.println("Long is unknown");
                break;
        }
    }
}

  3.可以作用于 String 类型(JDK 1.7 之后): 在 JDK 1.7 及更高版本中,switch 语句可以使用 String 类型的条件表达式。

public class SwitchStringExample {
    public static void main(String[] args) {
        String str = "two";
        switch (str) {
            case "one":
                System.out.println("String is one");
                break;
            case "two":
                System.out.println("String is two");
                break;
            case "three":
                System.out.println("String is three");
                break;
            default:
                System.out.println("String is unknown");
                break;
        }
    }
}

总结:

  • switch 语句可以作用于 byte 类型,因为 byte 类型可以隐式转换为 int
  • switch 语句不能作用于 long 类型,因为 long 类型不能隐式转换为 int
  • 从 JDK 1.7 开始,switch 语句可以作用于 String 类型。
posted @ 2024-06-17 21:48  Stars-125  阅读(126)  评论(0)    收藏  举报