13

I have multiple cases in a switch that do the same thing, like so: (this is written in Java)

 case 1:
     aMethod();
     break;
 case 2:
     aMethod();
     break;
 case 3:
     aMethod();
     break;
 case 4:
     anotherMethod();
     break;

Is there any way I can combine cases 1, 2 and 3 into one case, since they all call the same method?

0

4 Answers 4

25
case 1:
case 2:
case 3:
    aMethod();
    break;
case 4:
    anotherMethod();
    break;

This works because when it happens to be case 1 (for instance), it falls through to case 2 (no break statement), which then falls through to case 3.

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

Comments

7

Sure, you can allow case clause sections for 1 & 2 to 'fall through' to clause 3 and then break out of the switch statement after that:

case 1:
case 2:
case 3:
     aMethod();
     break;
case 4:
     anotherMethod();
     break;

3 Comments

what if 3 and 4 has some common part, but 4 does some additional stuff
In that case you can let 3 "fall through" to 4. The question here indicates that 3 and 4 have no shared functionality
Well, no, you can't let 3 fall through to 4. In that case, anything done for case 4 would always get done for case 3 as well and it would be 3 that would be doing the extra stuff (before falling through). Using a switch, you can only do the additional stuff before the common stuff. If you want other logic, you need to use other control structures (or if statements nested inside switch cases, which I find ugly).
4

Below is the best you can do

case 1:
case 2:
case 3:
     aMethod();
     break;
 case 4:
     anotherMethod();
     break;

Comments

4

It's called the "fall through" pattern:

case 1:  // fall through
case 2:  // fall through
case 3: 
   aMethod(); 
   break; 
case 4: 
   anotherMethod(); 
   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.