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.
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 executedbreak; // We can add optional break to exit the switch statementcase statement_2:// case expression to be executedbreak; // We can add optional break to exit the switch statement..case statement_n:// case expression to be executedbreak; // We can add optional break to exit the switch statementdefault:// 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 accordinglyswitch (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
dayand assign it a value. - Line 4: We pass the variable to the
switchstatement. - Line 5–25: We define different
casesfor different values of thedayvariable. - Line 26: We have a
defaultexpression that will printInvalid dayif none of the cases matches.
Free Resources