Why does "switch" in Java rely on "break"?
class switch1
{
public static void main(String args[])
{
int a = 10;
switch(a)
{
default: System.out.println("Default");
case -1: System.out.println("-1");
}
}
}
I understand that this program will execute both "default" and "case -1" statements as break is not specified after the matching condition (in this case after "default").
But what I fail to understand is
a) why is break
needed in a switch
statement?
b) why does it even execute the invalid matching conditions' statements (ie executing "case -1")) if all it does is matching?
Sometimes you need multiple cases to execute the same function. For example, I am letting a user specify either mode 1 or mode 32 to represent 32-bit mode, and mode 2 or mode 64 for 64-bit mode.
switch (input) {
case 1:
case 32:
/* Do 32-bit related code */
break;
case 2:
case 64:
/* Do 64-bit related code */
break;
default:
System.out.println("Invalid input");
}
This is why breaks are important. They tell the switch statement when to stop executing code for a given scenario. Additionally, the default is generally used for when the switch does not match ANY case.
switch
statements without break
s let you do things like this:
// Compute the most significant bit set in a number from 0 to 7
int topBit = -1;
switch(n) {
case 0:
topBit = 0;
break;
case 1:
topBit = 1;
break;
case 2:
case 3:
topBit = 2;
break;
case 4:
case 5:
case 6:
case 7:
topBit = 3;
break;
}
Essentially, it lets you create a set of labels, and have a condition at the top to let you jump to the initial label once. After that, the execution continues until a break
, or reaching the end of the switch
. This technique is old - it has been around since the assembly times, and by virtue of being included in C has made its way into Java and several other languages.
The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
check this documentation : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
链接地址: http://www.djcxy.com/p/84494.html上一篇: 用if和else循环