switch中的default,一般用在最后,表示非以上的任何情况下而发生的情况,我们一般习惯在他的后面加上个break。但是,如果default不是在最后,而是在前面或中间会发生什么情况呢:

先看看default在句首的情况:
int i = 2;
switch (i) {
  default:
   System.out.println("default");
  case 0:
   System.out.println("0");
  case 1:
   System.out.println("1");
  case 2:
   System.out.println("2");
    break;
  case 3:
   System.out.println("3");
  case 4:
   System.out.println("4");
    break;
}
他的输出结果是:2! 很明显,不是先执行的default语句!
再看看下面语句:
int i = 8;
switch (i) {
  default:
   System.out.println("default");
  case 0:
   System.out.println("0");
  case 1:
   System.out.println("1");
  case 2:
   System.out.println("2");
    break;
  case 3:
   System.out.println("3");
  case 4:
   System.out.println("4");
    break;
}
他的输出结果是:
default
0
1
2
出人意料!!从default开始向后执行!
再看看default在句中的情况:
int i = 2;
switch (i) {
  case 0:
   System.out.println("0");
  case 1:
   System.out.println("1");
    break;
  default:
   System.out.println("default");
  case 2:
   System.out.println("2");
    break;
  case 3:
   System.out.println("3");
  case 4:
   System.out.println("4");
    break;
}
结果是2!显然还是没执行default!
int i = 8;
switch (i) {
  case 0:
   System.out.println("0");
  case 1:
   System.out.println("1");
    break;
  default:
   System.out.println("default");
  case 2:
   System.out.println("2");
    break;
  case 3:
   System.out.println("3");
  case 4:
   System.out.println("4");
    break;
}
结果:
default
2
显然是从default开始向后执行的!

从上面可以看出:
switch default 之前的case按顺序执行(首先确定是否命中case,命中case,从命中case开始执行),最后执行default,如果default 没有break,继续执行default之后语句,直到跳出switch

 

 

相关文章:

  • 2021-07-21
  • 2022-12-23
  • 2021-12-14
  • 2021-04-27
  • 2022-01-16
  • 2022-12-23
  • 2022-01-13
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-14
  • 2021-05-29
  • 2021-11-07
  • 2022-12-23
  • 2021-07-10
相关资源
相似解决方案