14

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?

0

3 Answers 3

17

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

Sign up to request clarification or add additional context in comments.

2 Comments

I believe the new switch statement syntax is available in Java 14, not 12. More info here: docs.oracle.com/en/java/javase/14/language/…
@ArielMirra thank you for the info, I'm not sure about this information, take a look to this docs.oracle.com/en/java/javase/13/language/… or mkyong.com/java/java-12-switch-expressions
6

Java supports fall-through when you have no break:

case "apple":
case "orange":
case "pieapple":
    handleFruit();
    break;

Comments

4

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.