Java Switch Statement

In Java, the switch statement is used for executing one statement from multiple conditions. it is similar to an if-else-if ladder.

Switch statement consists of conditional based cases and a default case.

In a switch statement, the expression can be of byte, short, char and int type.

From JDK-7, enum, String can also be used in switch cases.

Following are some of the rules while using the switch statement:

  1. There can be one or N numbers of cases.
  2. The values in the case must be unique.
  3. Each statement of the case can have a break statement. It is optional.

Syntax:

Following is the syntax to declare the switch case in Java.

switch(expression)

{    

case value1:    

    //code for execution;    

    break;  //optional   

case value2:    

 // code for execution

 break;  //optional   

......    

......

......

......

Case value n:

// code for execution

 break;  //optional   

 

default:     

 code for execution when none of the case is true;    

}    

 

Powered by Froala Editor