下面文章转自 http://www.blogjava.net/Sunday/archive/2007/06/26/126380.html
整理一下今天下午同事出的一道题:
1)
1
public
class
Switch {
2 public static void main(String[] args){
3 int x = 0 ;
4 switch (x){
5 default :
6 System.out.println( " default " );
7 case 1 :
8 System.out.println( 1 );
9 case 2 :
10 System.out.println( 2 );
11 }
12 }
13 }
输出结果如下:2 public static void main(String[] args){
3 int x = 0 ;
4 switch (x){
5 default :
6 System.out.println( " default " );
7 case 1 :
8 System.out.println( 1 );
9 case 2 :
10 System.out.println( 2 );
11 }
12 }
13 }
default
1
2
2)
1
public
class
Switch {
2 public static void main(String[] args) {
3 int x = 0 ;
4 switch (x) {
5 default :
6 System.out.println( " default " );
7 case 0 :
8 System.out.println( 0 );
9 case 1 :
10 System.out.println( 1 );
11 case 2 :
12 System.out.println( 2 );
13 }
14 }
15 }
2 public static void main(String[] args) {
3 int x = 0 ;
4 switch (x) {
5 default :
6 System.out.println( " default " );
7 case 0 :
8 System.out.println( 0 );
9 case 1 :
10 System.out.println( 1 );
11 case 2 :
12 System.out.println( 2 );
13 }
14 }
15 }
输出结果如下:
0
1
2
3)
1
public
class
Switch {
2 public static void main(String[] args) {
3 int x = 0 ;
4 switch (x) {
5 case 0 :
6 System.out.println( 0 );
7 case 1 :
8 System.out.println( 1 );
9 case 2 :
10 System.out.println( 2 );
11 default :
12 System.out.println( " default " );
13 }
14 }
15 }
2 public static void main(String[] args) {
3 int x = 0 ;
4 switch (x) {
5 case 0 :
6 System.out.println( 0 );
7 case 1 :
8 System.out.println( 1 );
9 case 2 :
10 System.out.println( 2 );
11 default :
12 System.out.println( " default " );
13 }
14 }
15 }
输出结果如下:
0
1
2
default
总结:
switch表达式的值决定选择哪个case分支,如果找不到相应的分支,就直接从"default" 开始输出。
当程序执行一条case语句后,因为例子中的case分支中没有break 和return语句,所以程序会执行紧接于其后的语句。
下面是我的一点补充:如果在每个case语句后面加上break语句,那么会象我们想象中的输出,如果不加break的话,只要满足了一个case条件,则后面的语句将直接输出而不会再去判断。