Multiple/repeating cases in a Java switch statement

Code Jockey picture Code Jockey · Aug 11, 2011 · Viewed 12.4k times · Source

I would like to know how Java handles multiple identical instances of the same case. I think the following makes sense, conceptually:

switch (someIntegerValue)
{
   case 1:
   case 2:
      DoSomethingForBothCases();
      break;
   case 3:
      DoSomethingUnrelated();
      break;
   case 1:
      DoSomethingForCase1ThatReliesUponExecutionOfTheEarlierFunctionCall();
      break;
   case 2:
      DoSomethingForCase2ThatReliesUponExecutionOfTheEarlierFunctionCall();
      break;
}

Essentially, I would like to have a chunk of code executed for either case 1 or 2 (using fall-through), but then later on, have a chunk of code only executed for case 2.

Rather, is the following necessary, instead?

switch (someIntegerValue)
{
   case 1:
      DoSomethingForBothCases();
      DoSomethingForCase1ThatReliesUponExecutionOfTheEarlierFunctionCall();
      break;
   case 2:
      DoSomethingForBothCases();
      DoSomethingForCase2ThatReliesUponExecutionOfTheEarlierFunctionCall();
      break;
   case 3:
      DoSomethingUnrelated();
      break;
}

My actual code is more complex, but would use the same principle (i.e. something like "case 1: nope; alright... case 2: yep! execute this code!; case 3: nope; case 1 again?: still nope!; case 2 again?: yep! execute this code; no more cases: All Done!")

Answer

Bohemian picture Bohemian · Aug 11, 2011

Anything wrong with two switch statements?

switch (someIntegerValue) {
   case 1:
   case 2:
      DoSomethingForBothCases();
      break;
   case 3:
      DoSomethingUnrelated();
      break;
}

switch (someIntegerValue) {
   case 1:
      DoSomethingForCase1ThatReliesUponExecutionOfTheEarlierFunctionCall();
      break;
   case 2:
      DoSomethingForCase2ThatReliesUponExecutionOfTheEarlierFunctionCall();
      break;
}

That's what I would do.