Java - switch case, Multiple cases call the same function

You got error because you used comma between case queries. To define multiple cases, you have to use semi colon so like this.

switch (str) {
case "orange": case "pineapple": case "apple":
     handleFruit();
     break;
}

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

Java 12

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;