ABC of Programming
About Lesson

The switch statement is used to execute one block of code from multiple possible blocks based on the value of a single variable or expression.

The syntax of the switch statement is as follows:

switch (expression) {
case value1:
// code to execute if expression equals value1
break;
case value2:
// code to execute if expression equals value2
break;
...
default:
// code to execute if none of the cases match expression
}

Here, the expression is a variable or expression that is evaluated against each of the case values. If the value of the expression matches the value of a case, then the block of code associated with that case is executed. The break statement is used to exit the switch block after the code for the matching case is executed.

If none of the case values match the value of the expression, then the block of code associated with the default label is executed. The default label is optional.

It’s important to note that the expression in the switch statement must evaluate to a primitive data type (byte, short, int, or char), an enumerated type, or a String object.

Here’s an example of using the switch statement in Java:

int day = 3;
String dayName;

switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
default:
dayName = "Invalid day";
break;
}

System.out.println("Day: " + dayName);

In this example, the switch statement is used to assign a string value to the dayName variable based on the value of the day variable. Since the value of day is 3, the code associated with the case 3: label is executed, and the value “Wednesday” is assigned to the dayName variable.

Join the conversation