简体   繁体   English

Java SE 7 switch语句,默认情况何时执行?

[英]Java SE 7 switch statement, when will the default case executed?

I'm preparing OCA Java SE 7 example. 我正在准备OCA Java SE 7示例。 A question about the switch statement: here is the code: 有关switch语句的问题:这是代码:

int a = 5;
switch(a){
    default: //print 0
    case 1: //print 1
    case 5: //print 5
    case 8: //print 8
}

what's the output of the code? 代码的输出是什么? Here is something I don't understand: the default will usually be the last condition. 这是我不了解的内容:默认设置通常是最后一个条件。 What if default is the first condition? 如果默认是第一个条件怎么办? will the default case been matched first? 默认情况下会先匹配吗?

one step further: if I change the code, make i = 10, which certainly won't match the rest 3 condition, but will match the default condition. 进一步:如果更改代码,则使i = 10,这肯定不匹配其余3个条件,但将匹配默认条件。 Given that no break; 鉴于没有休息; in my code, will the program output : 0 1 5 8 ?? 在我的代码中,程序将输出:0 1 5 8吗?

update I don't think I state my question clear... As been suggested, I tried it with code and I do understand the rules about fall through. 更新我不认为我的问题很清楚...如所建议的,我尝试使用代码进行了尝试,并且我了解有关失败的规则。

And if i = 10, the result will be: 0 1 5 8. 如果i = 10,结果将是:0 1 5 8。

what confused me is that: if i = 10 让我感到困惑的是:如果我= 10

and when we enter the switch statement, which line executed first? 当我们输入switch语句时,首先执行哪一行?

default: //print 0 默认值://打印0

or 要么

case 1: //print 1 情况1://打印1

update update thank you guys... I think I get it... 更新更新谢谢...我想我明白了...

the default case will only be triggered when there is no matches. 默认情况下只会在没有匹配项时触发。

Which means in this case, the execution sequence should be: 这意味着在这种情况下,执行顺序应为:

case 1:
case 5:
case 8:
//and no found yet..trigger the default case
// given that my default case is at the top and no break;
//it fall through and print: 0 1 5 8

FYI: I do know how to run the code. 仅供参考:我确实知道如何运行代码。 And I didn't expect such a huge volume of criticisms saying that "do it yourself", "don't just read and no practice".. 而且我没想到会有如此多的批评说“自己动手”,“不要只是阅读,不要练习”。

anyway, thanks. 还是谢谢你。

You should try it and see. 您应该尝试一下看看。 But one thing I'll point out is that there are no break statements. 但我要指出的一件事是,没有break语句。 This means it will fall through from where ever it ends up. 这意味着它将从最终的位置掉下来。

So what will happen is it'll evaluate the switch and jump to the appropriate case. 因此,将会发生的事情是它将评估开关并跳转到适当的情况。 From there it will fall through. 从那里它将跌倒。

switch is just a specific goto pattern deemed safe for general use. 开关只是一种通常认为安全的特定goto模式。

Gives something like this: 给出这样的东西:

if (i == 1) goto lbl1;
if (i == 5) goto lbl2;
if (i == 8) goto lbl3;
lbl4: print 0;
Lbl1: print 1;
Lbl2: print 5;
Lbl3: print 8;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM