In the latest stable release of Java and Eclipse (Kempler), entering the following code and executing it, assuming the package and class names exist:
package some_package;
public class what_the_heck {
public static void main(String[] args) {
int p = 2;
int x = 1;
switch(p){
case (1):
x--;
case (2):
x = 2;
case (3):
x = 3;
default:
x++;
}
System.out.println(x);
}
}
This prints the value 4. Originally, I thought it should print 2 because I thought that even if there were no break statements, each piece of code is still held in a case statement. Now I think that the issue lies in how it is compiled. For example, my current belief is that internally a boolean keeps track of whether or not a case statement was equal to the value. If it was, then the boolean is true and all case statements will be treated as true until a break is found. This makes sense, but I am still wondering if there are other reasons behind this, or if I am entirely wrong in my assumption.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…