Nested switch case statement
Writting one switch statement into another switch statement is known as Nested switch statement.
Java allows us to write any number of nested switch statements.
Syntax
switch (expression 1)
{
case constantN:
// statemets;
switch (sub-expression1)
{
case statantN:
// statemets;
}
break;
}
Example
Below program contains two expressions switch executes different cases.
public class NestedSwitch
{
public static void main(String[] args)
{
int a = 2;
int b = 1;
switch(a)
{
case 1:
System.out.println("I'm outer case 1");
break;
case 2:
System.out.println("I'm outer case 2");
switch(b)
{
case 1:
System.out.println("I'm inner case 1");
break;
case 2:
System.out.println("I'm inner case 2");
break;
default:
System.out.println("Wrong inner case");
break;
}
break;
default:
System.out.println("Wrong outer case");
break;
}
}
}
Output
I'm outer case 2
I'm inner case 1