Java Switch Statement: A Comprehensive Guide
The switch statement in Java is used to select one of many code blocks to be executed. It's similar to a series of if-else statements but provides a more concise and structured way to handle multiple conditions.
The syntax of a switch statement in Java is as follows:
switch (expression) {
case value1:
// code to be executed if expression matches value1
break;
case value2:
// code to be executed if expression matches value2
break;
// more cases...
default:
// code to be executed if expression doesn't match any case
}
Here's an example to illustrate the usage of a 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;
// more cases...
default:
dayName = 'Invalid day';
}
System.out.println('The day is: ' + dayName);
In this example, the switch statement is used to assign a corresponding day name based on the value of the day variable. If day is 3, the output will be 'The day is: Wednesday'.
Note that the break statement is used to exit the switch statement after each case block. If you omit the break statement, the execution will continue to the next case until a break is encountered or the switch statement ends.
原文地址: https://www.cveoy.top/t/topic/pTi6 著作权归作者所有。请勿转载和采集!