- switch 语句中的变量类型可以是: byte、short、int 或者 char和String类型(JAVA7)。
- case 语句中的值的数据类型必须与变量的数据类型相同,而且只能是常量或者字面常量。
public class Test { public static void main(String[] args) { int a = 10; int b = 20; final int constA = 10; final int constB = 20; switch(a) { case constA: { System.out.println("命中 10"); break; } case constB: { System.out.println("命中 20"); break; } } } }
输出:
命中 10
- switch 语句可以包含一个 default 分支,该分支一般是 switch 语句的最后一个分支(可以在任何位置,但建议在最后一个)。default 在没有 case 语句的值和变量值相等的时候执行。default 分支不需要 break 语句。
public class Test { public static void main(String[] args) { int a = 10; int b = 20; final int constA = 10; final int constB = 20; switch(a) { default: { System.out.println("匹配default,并且没有break语句"); } case constB: { System.out.println("命中 20"); break; } } } }
输出结果:
匹配default,并且没有break语句
命中 20
switch语句的注意点
最新推荐文章于 2023-07-11 21:39:10 发布