Since I have multiple String cases which should be handled the same way, I tried:
switch(str) {
// compiler error
case \"apple\", \"orange\", \"
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