Yes. Switches break the language block operator pattern, but this is mainly because of the C / C ++ that the switch statement used by Java is based on.
In all three languages, the switch statement takes the following form:
switch(variable) { case n: statement 1; statement n; (optional) break; case n+1: statement 1; statement n; (optional) break;
Since the switch statement violates the traditional language pattern, many programmers transfer their multiple statements to the case using the traditional block style: {}
This is due to the fact that most constructions in all three languages ββallow us to consider block style statements as a single statement, but the switch statement does not require that the block style execute several statements in one case.
Without the break statement separating each case, it will βfailβ - if case n was agreed and had no gap, the code below it (case n + 1) would be executed - if case n + 1 was not broken and matched, the code by default it will be executed if none of them had a break, if case n matches, the code for case n, case n + 1 and default will be executed.
The default value is optional and indicates the default action for the switch statement to execute. Typically, the default condition is either a general handler or a good place to throw an exception if the value cannot be logically different than the values ββin the switch statement.
To illustrate the switch statement that runs inside the switch statement, look at this contrived example:
String message = null; int outerVariable = getOuterVariable(); switch(outerVariable) { case n: statement 1; statement n; break; case n+1: int innerVariable = getInnerVariable(); switch(innerVariable) { case 1: message = "IT WAS 1"; break; default: message = "WHY WOULD YOU DO THIS? OH THE HUMANITY!"; } break;
MetroidFan2002
source share