Showing posts with label Java Nested Switch. Show all posts
Showing posts with label Java Nested Switch. Show all posts

Thursday, 10 March 2016

Nested Switch in Java

How Nested Switch work in Java


               We can use the switch inside another switch as like the same way we use Nested-if conditions. Use switch as a part of statement sequence of an outer switch. This is called Nested Switch. Each switch has its own block hence there is no conflicts between the inside and outside switches

General Model of Nested Switch


switch(outer)
{
     case 1:

          System.out.println("Outer Switch");
          break;

     case 2:
          switch(inner)
          {
               case 1:
                    System.out.println("Inner Switch");
                    break;

               case 2:
                    System.out.println("Inner Switch case 2");
                    break;

               default:
                    System.out.println("Outer Switch");
                     break;
          }

     default:
          System.out.println("Outer Switch");
          break;
}
          

Important features of Switch Statements

  • The switch differs from the if statement in that switch can only test for equality, whereas if can evaluate any type of Boolean expression. That is, the switch looks only for a match between the value of the expression and one of its case constants.
  • No two case constants in the same switch can have identical values. Of course, a switch statement and an enclosing outer switch can have case constants in common.
  • A switch statement is usually more efficient than a set of nested ifs.