In Java, a switch statement is a control flow statement that allows the program to execute different blocks of code based on the value of an expression. It provides a way to test the value of an expression against a list of possible cases and execute the corresponding block of code.
The basic syntax of a switch statement in Java is as follows:
switch (expression) {
case value1:
// code to execute if expression is equal to value1
break;
case value2:
// code to execute if expression is equal to value2
break;
case value3:
// code to execute if expression is equal to value3
break;
default:
// code to execute if expression does not match any case
}
In this example, the expression is the value that is being tested against the different cases. Each case specifies a possible value of the expression and the code to execute if the expression is equal to that value. The default case is optional and specifies the code to execute if the expression does not match any of the other cases.
Note that each case block must end with a break statement, which causes the program to exit the switch statement and continue with the next line of code after the switch statement. Without the break statement, the program would continue to execute the code in the subsequent case blocks.
Switch statements in Java can be used with a variety of data types, including integers, characters, and strings. However, switch statements cannot be used with boolean expressions or floating-point values.
here's an example of how a switch statement can be used in Java:
int dayOfWeek = 4;
switch (dayOfWeek) {
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 of week");
break;
}
In this example, the dayOfWeek variable is assigned a value of 4, representing Thursday. The switch statement then tests the value of dayOfWeek against each of the possible cases. Since the value of dayOfWeek is equal to 4, the code in the case 4: block is executed, which prints "Thursday" to the console. The break statement causes the program to exit the switch statement and continue with the next line of code after the switch statement.
If dayOfWeek had been assigned a value that did not match any of the cases, the default: block would have been executed instead, printing "Invalid day of week" to the console.
Overall, switch statements provide a concise and readable way to execute different blocks of code based on the value of an expression in Java.