Since I have multiple String
cases which should be handled the same way, I tried:
switch(str) {
// compiler error
case "apple", "orange", "pieapple":
handleFruit();
break;
}
But I get a compiler error.
Should I have to, in Java, call the same function case by case:
switch(str) {
case "apple":
handleFruit();
break;
// repeat above thing for each fruit
...
}
Is there no simpler style?
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.
The switch can includes multiple cases where each case represents a particular value. Code under particular case will be executed when case value is equal to the return value of switch expression. If none of the cases match with switch expression value then the default case will be executed.
The switch statement evaluates its expression, then executes all statements that follow the matching case label. Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing.
You have to use case
keyword for each String like this :
switch (str) {
//which mean if String equals to
case "apple": // apple
case "orange": // or orange
case "pieapple": // or pieapple
handleFruit();
break;
}
Edit 02/05/2019
From Java 12 there are a new syntax of switch case proposed, so to solve this issue, here is the way:
switch (str) {
case "apple", "orange", "pieapple" -> handleFruit();
}
Now, you can just make the choices separated by comma, the an arrow ->
then the action you want to do.
Another syntax also is :
consider that each case return a value, and you want to set values in a variable, lets suppose that handleFruit()
return a String
the old syntax should be :
String result; // <-------------------------- declare
switch (str) {
//which mean if String equals to
case "apple": // apple
case "orange": // or orange
case "pieapple": // or pieapple
result = handleFruit(); // <----- then assign
break;
}
now with Java 12, you can make it like this :
String result = switch (str) { // <----------- declare and assign in one shot
case "apple", "orange", "pieapple" -> handleFruit();
}
Nice syntax
Java supports fall-through when you have no break
:
case "apple":
case "orange":
case "pieapple":
handleFruit();
break;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With