Nested switch Statements Java Help

Nested switch Statements

You can use a switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines its own block, no conflicts arise - between the case constants in.the inner switch and those in the outer switch. For example, the following fragment js perfectly valid:

Here he case 1: statement in the inner switch does not conflict 'With the statement in the outer.switch, The count variable is only compared  list of cases . . at the outer level. If count is 1, then target is compared with the inner list cases. In summary, there are three important  of the switch statement to note: the switch diffracts the that can test for here as if can evaluate any type of Boolean expression. :mat is, the switch looks only for a match between the value of the expression and one  case constants No two case stats in the same switch can have identical' values. Of course a switch statement  by an outer switch cart have: constants in common    A switch statement is usually more efficient than a-set of ifs.

The last point is particularly interesting it gives insight in how the Java' compiler works, When it compiles a switch'statement, the Java compiler will inspect each of the case constants and create a that it will use (or selecting the path of expedition depending on the value of the expression. Therefore you need to  select among a large grate ,Jp of values, a switch statement will run much  than the' equivalent logic coded using sequence of i elses. The compiler can do this because it shows that the case constants-are all the same type and. simply must be compared for  equality with the a It expression. The compiler has no such knowledge of along list of if expressions.

Posted on September 16, 2014 in The Complete Reference

Share the Story

About the Author

Back to Top
Share This