Switch Statement


Java switch statement is used when we want to execute one of the multiple code blocks based on the return value of a specified expression.

For any switch case, the value should have the same data type as the variable and it must be a constant or literal.

The break keyword is used to stop the execution and exit from the switch block.

Note: Java switch statement is fall-through i.e. if the break statement is not used with the switch statement then it executes all the statements after the first match.

A java switch statement can have an optional default case which must appear at the end. The default case can be used to execute a task when no case is true.

We don’t need any break statement in the default case.


Syntax:

switch (expression)
{
    case 1: //code to be executed
            break;
    case 2: //code to be executed
            break;
            ...
    case n: //code to be executed
            break;
            
    default: //code to be executed if none of the above case is true
}

Example:

int a = 2;
switch (a)
{
    case 1: System.out.print(“case 1 is executed”);
		break;
    case 2: System.out.print(“case 2 is executed”);
		break;
    default: System.out.print(“default case is executed”);
}

Output:

case 2 is executed