Switch Case Statement in Java

A switch statement in java allows us to selectively execute a block of statements based on the value of a variable or constant expression. In a switch case statement a variable or value of an constant expression is tested for equality against a list of possible case labels and when match is found, the block of code associated with matched case is executed.

It is similar to if..else ladder statement, but the syntax of switch statement is more readable and easy to understand.

Syntax of Switch Statement in Java

switch(expression) {
    case value1 :
       /* Code to be executed when value of expression equals value1 */
    case value2 :
       /* Code to be executed when value of expression equals value2 */
    case value3 :
       /* Code to be executed when value of expression equals value3 */
    default :   /* Optional */

Java Switch Statement Control Flow Diagram
Important points about Switch Case Statement
  • The expression in switch case must evaluates to char, byte, short, int or enum.

  • You can use any number of case labels within a switch. Case labels must be unique. We cannot write two case blocks with same constants.

  • Switch case performs only equality check of the value of expression/variable against the list of case values.

  • The default code block gets executed when none of the case matches with expression. default case is optional and doesn't require a break statement.

  • The break statement is optional.The break statement at the end of each case cause switch statement to exit. If break statement is not used, all statements below that case statement are also executed until it found a break statement.

  • One switch statement can have maximum of one default label. Default block can be placed anywhere in switch statement.

Disadvantages of Switch Case

Switch statements can only be used to perform equality comparison, we cannot perform conditional checks using relational or logical operators like <, >, <=, &&, || etc.