switch 语句能否作用在 byte 上;作用在 long 上;作用在 String 上?
在 Java 中,switch 语句可以作用于多种类型,具体情况如下:
-
可以作用于 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类型。
浙公网安备 33010602011771号