I am relatively new to java. In a switch statement, do you have to put a break statement after each case?
No, you don't have to. If you omit the break statement, however, all of the remaining statements inside the switch block are executed, regardless of the case value they are being tested with.
This can produce undesired results sometimes, as in the following code:
switch (grade) {
case 'A':
System.out.println("You got an A!");
//Notice the lack of a 'break' statement
case 'B':
System.out.println("You got a B!");
case 'C':
System.out.println("You got a C.");
case 'D':
System.out.println("You got a D.");
default:
System.out.println("You failed. :(");
}
If you set the grade variable to 'A', this would be your result:
You got an A!
You got a B.
You got a C.
You got a D.
You failed. :(
You don't have to break after each case, but if you don't they will flow into each other. Sometimes you want to bundle multiple cases together by leaving out the breaks.
It is better you do. Otherwise the next statements will be executed too.
switch(someNumber) {
case thisCaseMatches:
doThat();
case thisCaseDoesNotMatch:
shouldntExecuteYetItWillBeExecuted();
default:
alsoWillbeExecuted();
}
You do if you are not exiting the switch statement with a return or other action.
Semantically yes. Otherwise all case statements after the first matching one would run.
It's a good practice to put break after each statement.
You're not forced.
But if you don't put breaks tatement you've cascade switch statement, namely more condition could be matched, and sometimes this can lead to logical errors.
However there are people which think that cascade statements can optimize the code, helping to write less code.
Related
I have a question. In a switch statement, is default tested for last even if it isn't last?
If so, in the following code snippet:
int i = 6;
int a=0, b=0, c=0;
switch (i)
{
case 1:
a++;
case 2:
default:
case 3:
b++;
case 6:
c++;
}
System.out.println(a + " " + b + " " + c);
After matching with case 6, and incrementing the value of c, since there is no break, will it go back to default?
I did try this code and it didn't seemly go to default and a fall-through did not occur. I just wanted to know?
switch is evaluated from matching case to either break or end of switch statement. If you pass 6 it will enter case for 6 and do only one increment. But if you enter 7 it will start from default and fall through to the end of switch doing two increments.
There is no additional testing of case labels beyond the initial testing at the beginning of the switch statement. Once i has been evaluated by the switch statement, control transfers to the case 6: label because that matches i. Statements are then executed in order until the end of the switch statement, or until a break statement is encountered. This means that only c is incremented.
A break statement will only end the execution of the entire switch statement; whether a break statement is present has no effect on retesting the switch expression, because retesting the switch expression will not occur either way.
If you want default to be the case label entered, then i must not match any case label at the start of the switch statement. If i is 99 at the start of the switch statement, then both b and c are incremented (fallthrough occurs).
There is no restriction on where in the order of case labels a default label appears, only that at most one default occurs in a switch statement.
Currently, all of your cases will fall through, as no case has a break; as well, your switch is conditionally based on i, so if you want to see each case, you need to change i.
Utilizing break; should not have any effect on where your cases reside in your switch state, this is also the "case" for default
Edit: As #Ivan mentioned, if fall through is intended, then the placement of your cases will matter
I'd like to know if there is any efficiency difference between using if statement or switch. For example:
if(){
//code
}
else if(){
//code
}
else{
//code
}
I believe that program needs to go and check all of the if statement even if the first if statement was true.
switch(i){
case 1:
//code
break;
case 2:
//code
break;
But in the switch, there is a break command. Is my approaching right? If not, could you explain the efficiency difference between them?
Switch perf is better than if else as in case of switch there will be one time evaluation . Once it evaluated the switch it knows which case needs to be executed but in case of if else it has to go through all conditions in case of worst scenario.
The longer the list condition, better will be switch performance but for shorter list (just two conditions), it can be slower also
From Why switch is faster than if
With switch the JVM loads the value to compare and iterates through
the value table to find a match, which is faster in most cases
Switch is faster.
Imagine you are at an intersection, with many paths.
With switch, you go to the right path at the first time.
With if, then you have to try all the paths before you find the right one.
Use switch whenever possible.
Of course, for computer this difference is very small that you don't even notice. But yeah, you get the point.
I think the code is quite clear. With if, you have to check each case and after case by case (in the worst case, last return gives back the result). With switch, some kind like a special byte code checking and jump to the correct case to return. So the switch is a bit faster than the if statement. However, I think we need to focus on the way we implement for easier to read. In some simple case, the if is also a choice to write code.
I'd like to know if there is any efficiency difference between using if statement or switch. For example:
if(){
//code
}
else if(){
//code
}
else{
//code
}
I believe that program needs to go and check all of the if statement even if the first if statement was true.
switch(i){
case 1:
//code
break;
case 2:
//code
break;
But in the switch, there is a break command. Is my approaching right? If not, could you explain the efficiency difference between them?
Switch perf is better than if else as in case of switch there will be one time evaluation . Once it evaluated the switch it knows which case needs to be executed but in case of if else it has to go through all conditions in case of worst scenario.
The longer the list condition, better will be switch performance but for shorter list (just two conditions), it can be slower also
From Why switch is faster than if
With switch the JVM loads the value to compare and iterates through
the value table to find a match, which is faster in most cases
Switch is faster.
Imagine you are at an intersection, with many paths.
With switch, you go to the right path at the first time.
With if, then you have to try all the paths before you find the right one.
Use switch whenever possible.
Of course, for computer this difference is very small that you don't even notice. But yeah, you get the point.
I think the code is quite clear. With if, you have to check each case and after case by case (in the worst case, last return gives back the result). With switch, some kind like a special byte code checking and jump to the correct case to return. So the switch is a bit faster than the if statement. However, I think we need to focus on the way we implement for easier to read. In some simple case, the if is also a choice to write code.
Here is a small confusion so kindly pardon my ignorance. Here is a code snippet.
public class SwitchTest {
public static void main(String[] args) {
int x = 2;
switch (x) {
case 1:
System.out.println("1");
break;
default:
System.out.println("helllo");
case 2:
System.out.println("Benjamin");
break;
}
}
}
Here, if value of x is 2, only Benjamin is printed. That's perfectly fine. Now lets suppose, i change value of x to 3, not matching any case, than its a fall through from default case. Ain't compiler needs to match every case for 3, by that time CASE 2 will be passed, than why it goes back to default and prints hello Benjamin. Can someone explain please?
Thanks,
You need to add a break; statement to break out of the switch block.
switch (x) {
case 1:
System.out.println("1");
break;
default:
System.out.println("helllo");
break; // <-- add this here
case 2:
System.out.println("Benjamin");
break;
}
Generally speaking, it is also better coding practice to have your default: case be the last case in the switch block.
In this case, the switch is following the pattern:
x==1? No, check next case
default? Not done yet, check other cases
x==2? No, check next case
//No more cases, so go back to default
default? Yes, do default logic
// no break statement in default, so it falls through to case 2: logic without checking the case
output case 2 logic
break
Notice how the block will jump over the default case, and save it until a later time unless we have exhausted all other possible cases.
It prints both strings because you do not have a break in your default case, so it continues into case 2, printing Benjamin. You could fix this by adding a break or moving case 2 above the default case.
'switch' case is other form of 'if-then-else', the default case is for the final else part. It is advisable to write default at the end of switch.
Default is checked as last. Thats why it feels like the compiler 'went' back.
Here is my code:
int x = 10;
switch(x) {
case 10:
System.out.println("10");
break;
case 5+5:
System.out.println("5+5");
break;
}
Here in this case, both cases are true, what will be executed? first case, or both?
It's invalid: 5+5 resolves to 10, and you cannot have two case clauses with the same constant.
As 5+5 is compiled as 10, your code has duplicate conditions, which is illegal in java switch statements.
From the specification :
No two of the case constant expressions associated with a switch
statement may have the same value.
So nobody can "explain the execution" : there is no execution.
You will get a "duplicate case" error.
According to your comment, this is the issue you observed.
The explaination is that 5+5 is evaluated to 10 at compile time by the compiler, which means that you have two case branches with the same value. This is not allowed (which one should the code take?)
Each case statement in a switch block must be unique. case 10 and case 5 + 5 are the same thing, and as such your code will not compile.