Written by - Yash Agrawal

Java Switch Statement


The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. The switch statement works with almost all primitive data type. Since Java 7, you can use strings in the switch statement.

There are certain points you should remember while working with switch statements.

  • There can be one or N number of case values for a switch expression.
  • The case value can have a default label which is optional.
  • Each case statement can have a break statement which is optional. When control reaches to the break statement, it jumps the control after the switch expression. If a break statement is not found, it executes the next case.
  • Syntax:

    switch(expression){    
    case value1:    
     //code to be executed;    
     break;  //optional  
    case value2:    
     //code to be executed;    
     break;  //optional  
    ......    
        
    default:     
      code to be executed if all cases are not matched;  
    }