What is the switch statement in Java?

In Java, the switch statement performs different actions based on various conditions. It statement compares the value of a variable to the values specified in the case statements. The expression associated with that case is executed when a match is found. The switch statement can also include a default case that is executed if none of the other cases are matched.

Flowchart of the switch statement
Flowchart of the switch statement

The illustration above shows a flowchart of the switch statement. When a program starts, an expression is passed through the switch statement. It checks for the cases one by one, like an if-else statement. If the expression matches the case value, the expression followed by that case is executed, and the program exits the switch statement. If none of the case values matches the switch expression, the program executes the default expression to end the switch statement.

Syntax

switch(expression){
case statement_1:
// case expression to be executed
break; // We can add optional break to exit the switch statement
case statement_2:
// case expression to be executed
break; // We can add optional break to exit the switch statement
.
.
case statement_n:
// case expression to be executed
break; // We can add optional break to exit the switch statement
default:
// default expression to be executed
}

Coding example

The following program will demonstrate the use of the switch statement to find the name of the days of the week.

class Weekdays{
public static void main( String args[] ){
int day = 3; //change week day accordingly
switch (day){
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
}
}

Explanation

  • Line 3: We declare the variable name day and assign it a value.
  • Line 4: We pass the variable to the switch statement.
  • Line 5–25: We define different cases for different values of the day variable.
  • Line 26: We have a default expression that will print Invalid day if none of the cases matches.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved