12

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?

Zargontapel
  • 298
  • 1
  • 2
  • 12

4 Answers4

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.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
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;
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • what if 3 and 4 has some common part, but 4 does some additional stuff – Kalpesh Soni Aug 30 '13 at 22:33
  • In that case you can let 3 "fall through" to 4. The question here indicates that 3 and 4 have no shared functionality – Reimeus Aug 30 '13 at 22:46
  • 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). – Ted Hopp Dec 30 '15 at 07:17
4

Below is the best you can do

case 1:
case 2:
case 3:
     aMethod();
     break;
 case 4:
     anotherMethod();
     break;
Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327
4

It's called the "fall through" pattern:

case 1:  // fall through
case 2:  // fall through
case 3: 
   aMethod(); 
   break; 
case 4: 
   anotherMethod(); 
   break; 
Gene
  • 46,253
  • 4
  • 58
  • 96