1.普通用法
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public static void test(){ int i = 5; switch (i){ case 5: System.out.println("是个5"); break; case 10: System.out.println("是个10"); break; case 4: System.out.println("是个4"); break; default: System.out.println("默认值"); break; } }
2.多值case
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public static void test(){ int i = 11; switch (i){ case 5:case 11:case 12: System.out.println("是个5"); break; case 10: System.out.println("是个10"); break; case 4: System.out.println("是个4"); break; default: System.out.println("默认值"); break; } }
3.面试一
下面的方法结果会是什么呢?
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public static void test(){ int i = 11; switch (i){ case 5:case 11:case 12: System.out.println("是个5"); case 10: System.out.println("是个10"); break; case 4: System.out.println("是个4"); break; default: System.out.println("默认值"); break; } }
结果是:
复制代码
1
2
3是个5 是个10
4.面试二
下面的方法结果会是什么呢?
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19public static void test(){ int i = 10; switch (i){ case 5:case 11:case 12: System.out.println("是个5"); case 10: System.out.println("是个10"); break; case 4: System.out.println("是个4"); break; default: System.out.println("默认值"); break; } }
结果是:
复制代码
1
2是个10
5.面试三
下面的方法结果会是什么呢?
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public static void test(){ int i = 4; switch (i){ case 5: System.out.println("是个5"); break; case 10: System.out.println("是个10"); break; case 4: System.out.println("是个4"); default: System.out.println("默认值"); break; } }
结果是:
复制代码
1
2
3是个4 默认值
结论:最终执行的方法体是什么呢?匹配上的case的冒号开始,一直到break为止,之间的case条件忽略,语句会执行。
最后
以上就是忧伤康乃馨最近收集整理的关于java switch case 用法详解的全部内容,更多相关java内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复