Boolean logic in switch case statement - Java

14,644

Solution 1

Of course.

Just use

if(i.equals("+") || i.equals("/")) {
    setOperator("i");
}

OR if you have to use a switch statement, you can do it this way:

switch(i) {
    case "+":
    case "/":
        setOperator("i");
        break;
}

Basically, you can't really have multiple cases the way you had thought about it. It's not the same structure as an if statement, where you can do various logical operations. Java does not go through and do an if statement for each of the cases.

Instead, each time you have case("foo"), Java sees this as something called a Case Label. It is the reason that we sometimes opt to use switch statements, even though they are very primitive and sometimes not very convenient. Because we have case labels, the computer only has to do one evaluation, and it can jump to correct place and execute the right code.

Here is a quote from a website that may help you:

A switch statement, as it is most often used, has the form:

switch (expression) {
   case constant-1:
      statements-1
      break;
   case constant-2:
      statements-2
      break;
      .
      .   // (more cases)
      .
   case constant-N:
      statements-N
      break;
   default:  // optional default case
      statements-(N+1)
} // end of switch statement

This has exactly the same effect as the following multiway if statement, but the switch statement can be more efficient because the computer can evaluate one expression and jump directly to the correct case, whereas in the if statement, the computer must evaluate up to N expressions before it knows which set of statements to execute:

if (expression == constant-1) { // but use .equals for String!!
    statements-2
} 
else if (expression == constant-2) { 
    statements-3
} 
else
    .
    .
    .
else if (expression == constant-N) { 
    statements-N
} 
else {
    statements-(N+1)
}

Solution 2

yes you can do as: Fall through in swith case

      switch (i) {
        case "+":
        case "/":
            setOperator(i);
            break;
      }

Solution 3

switch (i) {
    case ("+"):
    case ("/"):
        setOperator("i");
        break;
    }
Share:
14,644
Jack
Author by

Jack

Software Engineer at Shutl Ruby, Rails, Java, Python, AI

Updated on June 04, 2022

Comments

  • Jack
    Jack almost 2 years
     switch (i) {
         case ("+" || "/"):  
            setOperator("i");
            break;
     }
    

    What is the best way to do this in Java?