I have some switch statement as shown below. Notice there is no break. Findbugs is reporting error on the second case statement only. The error is : Switch statement found where one case falls through to the next case.
switch(x) { case 0: // code case 1: // code case 2: // code }
You can use the break statement to end processing of a particular labeled statement within the switch statement. It branches to the end of the switch statement. Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached.
Break will return control out of switch case.so if we don't use it then next case statements will be executed until break appears. The break statement will stop the process inside the switch.
The Break Is Optional In Switch case Java, the break statement is optional. Even if you remove the break, the control of the program will flow to the next case.
A switch statement is significantly faster than an if-else ladder if there are many nested if-else's involved. This is due to the creation of a jump table for switch during compilation. As a result, instead of checking which case is satisfied throughout execution, it just decides which case must be completed.
Findbugs is flagging up that falling through from one case
to the next is generally not a good idea if there's any code in the first one (although sometimes it can be used to good effect). So when it sees the second case
and no break
, it reports the error.
So for instance:
switch (foo) { case 0: doSomething(); case 1: doSomethingElse(); default: doSomeOtherThing(); }
This is perfectly valid Java, but it probably doesn't do what the author intended: If foo
is 0
, all three of the functions doSomething
, doSomethingElse
, and doSomeOtherThing
run (in that order). If foo
is 1
, only doSomethingElse
and doSomeOtherThing
run. If foo
is any other value, only doSomeOtherThing
runs.
In contrast:
switch (foo) { case 0: doSomething(); break; case 1: doSomethingElse(); break; default: doSomeOtherThing(); break; }
Here, only one of the functions will run, depending on the value of foo
.
Since it's a common coding error to forget the break
, tools like Findbugs flag it up for you.
There's a common use-case where you have multiple case
statements in a row with no intervening code:
switch (foo) { case 0: case 1: doSomething(); break; case 2: doSomethingElse(); break; default: doSomeOtherThing(); break; }
There, we want to call doSomething
if foo
is 0
or 1
. Most tools won't flag this up as a possible coding error, because there's no code in the case 0
prior to the case 1
and this is a fairly common pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With