In Java, a switch statement is a control flow statement that allows you to execute different blocks of code based on the value of a variable or expression. It provides an alternative to writing multiple if-else statements.
The basic syntax of a switch statement is as follows:
switch (variable) {
case value1:
// code to execute if variable is equal to value1
break;
case value2:
// code to execute if variable is equal to value2
break;
case value3:
// code to execute if variable is equal to value3
break;
default:
// code to execute if variable is not equal to any of the values
break;
}
Here, variable
is the variable or expression that is being tested, and value1
, value2
, value3
, etc. are the possible values that variable
could have. If variable
has the same value as one of the valueX
constants, the corresponding block of code is executed. If variable
does not match any of the valueX
constants, the default
block of code is executed (if it is present).
Each case block of code ends with a break
statement, which causes the execution of the switch statement to terminate and continue with the next statement after the switch statement.
For example, consider the following code that uses a switch statement to determine the day of the week based on a numerical value:
int day = 3;
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");
break;
}
In this case, the value of day
is compared against each case value, and the corresponding day of the week is printed to the console.
Switch statements are a useful programming construct when you have a variable with a limited number of possible values, and you want to execute different blocks of code based on each value.