Switch Statement In Java


Java provides a multiple branch selection statement known as switch. This selection statement successively tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed.

The general form of switch is:



case 1:

   segment 1

case 2:

   segment 2


case n:

   segment n


   default segment



A switch statement is used for multiple way selection that will branch to different code segments based on the value of a variable or an expression . The optional default label is used to specify the code segment to be executed when the value of the variable or expression does not match with any of the case values. if there is no break statement as the last statement in the code segment for a certain case, the execution will continue on into the code segment for the next case clause without checking the case value.



We can use switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines in its own block, no conflicts arise between the case statements in the inner switch and those in the outer switch.




   case 1:



       case 0:

       System.out.println(“target is zero”);


       case 1:

       System.out.println(“target is one”);




    case2: //. . .


Here the case 1: statement is inner switch does not conflict with the case 1: statement in the outer switch. The count variable is only compared with the list of cases at the outer level. if the count is 1 , then target is compared with the inner list cases.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s