This question already has answers here:
Why do we need break after case statements?
(17 answers)
Closed 7 years ago.
I understand that Java switch case are designed this way but why is this behavior in Java
int x = 1;
switch(x){
case 1: System.out.println(1);
case 2: System.out.println(2);
case 3: System.out.println(3);
default: System.out.println("default");
}
output : 1
2
3
default
My question is why case 2 and 3 are executed? I know I omitted break statement
but x was never 2 or 3 but case 2 and case 3 still executes?
There is no break statement so all case are executed
Use break statements
switch(x){
case 1: System.out.println(1);break;
case 2: System.out.println(2);break;
case 3: System.out.println(3);break;
default: System.out.println("default");
}
I know I omitted break statement but x was never 2 or 3 but case 2 and
case 3 still executes?
Straight from the doc :
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.
You need to add break statement for each case. As there is no break statement all cases are getting executed.
You are missing the Break statement.
switch(x){
case 1: System.out.println(1);
break;
case 2: System.out.println(2);
break;
case 3: System.out.println(3);
break;
default: System.out.println("default");
}
Check the The switch Statement
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.
Related
I'm confused about this example. if break is deleted then both Today is Saturday and Today is Sunday will be print. I need to know why this happends?
int day = 4;
switch (day) {
case 4:
System.out.println("Today is Saturday");
// break;
case 7:
System.out.println("Today is Sunday");
// break;
}
P.S: to those who are surprised why i asked such a simple question:
Its been a while i am learning Kotlin, that does not need to add break in when expression, so it made me confused when i was working on a java project that needs a switch statement
Your question is probably a duplicate of something else, but the reason is that case statement within a Java switch by default will flow onto the next case statement unless a break be explicitly mentioned. To better understand why the case statements behave this way, an example would make this clear. Let's say that you wanted the same logic to happen for Monday, Tuesday, and Wednesday. Then, you could use the following:
switch (day) {
case 1:
case 2:
case 3:
System.out.println("Today is Monday, Tuesday, or Wednesday");
break;
case 4:
System.out.println("Today is Thursday");
break;
case 7:
System.out.println("Today is Sunday");
break;
}
Break statement: Break statement is used to terminate the loop. When a break statement is encountered inside a loop, the loop is
immediately terminated.
Therefore, when we use the break statement inside the switch statement, it terminates the loop at that case, and the program control resumes at the next statement following the loop.
Answer to your Question: When the break statement is not used, the control of the program flows through each and every case until either it reaches the end of the switch block or a break statement is encountered.
For class I'm working on an interpreter, currently working on the scanner. Being a class that will be called many many times, I would like for it to be optimized for speed. In the scanner, to categorize an operator you have to compare the current token to the 6 or so operators. What method is best for speed, but for also for readability.
Many cases in an if statement
Loop through a char array of every operator and compare
Switch statement
These are the only cases I could think of. Which is best, or if you have a better approach please share. I implemented #2 because it takes up the least amount of lines of code.
Any sensible hand-written scanner is based on a switch statement. Note that if you return special characters directly to the parser as themselves, you can economize on case actions:
switch (ch) // the next incoming character
{
case '+':
case '-':
case '*':
case '/':
case '%':
// etc.
return ch;
case 'A':
case 'B':
// ...
case 'Z':
case 'a':
case 'b':
// ...
case 'z':
// start of an identifier: accumulate it, with a do/while loop,
// save it somewhere, return IDENTIFIER
return IDENTIFIER;
case '0':
case '1':
// ...
case '9':
// start of a numeric literal: ...
return NUMERIC_LITERAL;
// etc.
}
For just a few items, the difference is small. If you have many items you should definitely use a switch.
If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if where the last item takes much more time to reach as it has to evaluate every previous condition first.
And also as #Qix commented switch it more readable.
The following code prints out 1,2,3 , if i change int i = 3; it will print out 3. I was wondering the reason behind this. I used debugger and it seems if i = 3 it goes to case 3 and print out 3 then program terminated.I believe when i=5, it goes to default , does this mean case 1,case 2 and case 3 all belong to the default clause?
int i = 5;
switch(i){
default:
case 1:
System.out.println(1);
case 2:
System.out.println(2);
case 3:
System.out.println(3);
}
Edit:
This question was from a test and it asks for the output for this code. So I am trying to figure out why the output is 1,2,3, i understand break; is needed but that is not what i wanted for the answer.
i == 5 doesn't match any of your cases, so control goes to default clause.
default clause is empty, with no break statement, and it immediately falls through to the case below — case 1 in your code.
case 1 prints "1" and, as it also doesn't have a break statement, falls through to case 2, and so on.
cases 1, 2, 3 do not belong to default — what matters is their order.
If you would reorder your switch statement and would write default clause as the last one, it would print nothing.
If you don't have break at any case or default it will fall through until it find break or end of case block. So in you case since you don't have break in default it fall through all the way to the end. Without break your program will print 1,2,3 for i>3.
This question already has answers here:
Why do we need break after case statements?
(17 answers)
Closed 9 years ago.
I already searched in stackoverflow for reasons concerning the question, why switch does not break after having found a matching case.
For example, I have written some code which simulates a dice. For every throw, I count up for statistical reasons (one, ... = int).
switch (actualThrow) {
case (1): one++;
case (2): two++;
case (3): three++;
case (4): four++;
case (5): five++;
case (6): six++;
}
I DO know, that case(3)-case(6) will be checked, if my throw was a 3 (Why do we need break after case statements?) and it will be prevented by inserting break;, but I want to understand, why obviously the following cases seem to be checked, but execute, although the condition is not fulfilled.
Imagine this scenario:
switch(trafficLight.state) {
case GREEN:
car.drive();
break;
case YELLOW:
car.drive();
break;
case RED:
car.stop();
break;
}
Seems kinda wasteful since GREEN and YELLOW both do the same thing. Java lets us consolidate so that multiple conditions take the same action:
switch(trafficLight.state) {
case GREEN:
case YELLOW:
// Now both GREEN and YELLOW will use this code
car.drive();
break;
case RED:
car.stop();
break;
}
Less code, same effect. That's all. That's the simple case mind you, there are other ways to use this that are less obvious and more prone to abuse.
When parsing through a switch-case statement, each case is simply a label. If anything matches a case then it will just go through until it either finds a break or the end of the statement (a }).
It is similar to the Java opcode (assembly code essentially). You use labels to jump to. Besides that, they don't really serve a purpose in the code.
This question already has answers here:
Switch statement fall-through...should it be allowed? [closed]
(12 answers)
Closed 9 years ago.
After evaluating a case in a switch statement in Java (and I am sure other languages) the following case's are also evaluated unless a control statement like break, or return is used.
I understand this is probably an implementation detail, but what is/are the reasons for having this functionality happen?
Thanks!
Because it is useful to "fallthrough" from one case to another. If you don't need this (as is often the case), a simple break will prevent this. On the other hand, if case didn't fallthrough by default, there wouldn't be any easy way to do that.
It saves me a lot of duplicated code when the hardware changes.
void measureCPD (void) {
char setting;
switch (DrawerType) {
case 1:
setting = SV1 | SV7;
break;
case 0:
case 2:
setting = SV1;
break;
case 5:
PORTA |= SVx;
case 3:
case 4:
setting = SV1 | SV7;
break;
default: // Illegal drawer type
setting = SV1;
}
SetValves (setting);
}
It's because the case labels are goto destination labels.
There are times where you might want to have multiple case statement execute the same code.
So you would fall through and do the break at the end.
I tend to think of it in analogy to assembly programming, the case's are labels where you jump into, and it runs through the ones below it (program flows from up to down), so you will need a jump (break;) to get out.