What is the usage of return in a switch statement in Java?
In Java, the switch statement can be used to choose different code blocks to execute based on the value of an expression. You can use a return statement within the switch statement to terminate it and return a value.
Using the return statement in a switch statement is mainly used to immediately return a value when a specific case is executed, and it terminates the execution of the switch statement. This can help reduce code redundancy and improve the readability and maintainability of the code.
Here is an example code showing how to use a return statement in a switch statement.
public class SwitchExample {
public static int getValue(int num) {
switch(num) {
case 1:
return 10;
case 2:
return 20;
case 3:
return 30;
default:
return 0;
}
}
public static void main(String[] args) {
int result = getValue(2);
System.out.println("Result: " + result); // 输出结果为:Result: 20
}
}
In the example above, when the method getValue(2) is called, the switch statement will select the corresponding case based on the value of the parameter num, and return the respective value using the return statement. In this case, the return value is 20 because the value of num is 2, corresponding to case 2, which returns 20.