Java switch statement multiple cases

369,064

Solution 1

Sadly, it's not possible in Java. You'll have to resort to using if-else statements.

Solution 2

The second option is completely fine. I'm not sure why a responder said it was not possible. This is fine, and I do this all the time:

switch (variable)
{
    case 5:
    case 6:
    etc.
    case 100:
        doSomething();
    break;
}

Solution 3

public class SwitchTest {
    public static void main(String[] args){
        for(int i = 0;i<10;i++){
            switch(i){
                case 1: case 2: case 3: case 4: //First case
                    System.out.println("First case");
                    break;
                case 8: case 9: //Second case
                    System.out.println("Second case");
                    break;
                default: //Default case
                    System.out.println("Default case");
                    break;
            }
        }
    }
}

Out:

Default case
First case
First case
First case
First case
Default case
Default case
Default case
Second case
Second case

Src: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Solution 4

Maybe not as elegant as some previous answers, but if you want to achieve switch cases with few large ranges, just combine ranges to a single case beforehand:

// make a switch variable so as not to change the original value
int switchVariable = variable;

//combine range 1-100 to one single case in switch
if(1 <= variable && variable <=100)
    switchVariable = 1;
switch (switchVariable) 
{ 
    case 0:
        break; 
    case 1:
        // range 1-100
        doSomething(); 
        break;
    case 101: 
        doSomethingElse(); 
        break;
    etc.
} 

Solution 5

According to this question, it's totally possible.

Just put all cases that contain the same logic together, and don't put break behind them.

switch (var) {
    case (value1):
    case (value2):
    case (value3):
        //the same logic that applies to value1, value2 and value3
        break;
    case (value4):
        //another logic
        break;
}

It's because case without break will jump to another case until break or return.

EDIT:

Replying the comment, if we really have 95 values with the same logic, but a way smaller number of cases with different logic, we can do:

switch (var) {
     case (96):
     case (97):
     case (98):
     case (99):
     case (100):
         //your logic, opposite to what you put in default.
         break;
     default: 
         //your logic for 1 to 95. we enter default if nothing above is met. 
         break;
}

If you need finer control, if-else is the choice.

Share:
369,064
FunJavaCode
Author by

FunJavaCode

Updated on July 08, 2022

Comments

  • FunJavaCode
    FunJavaCode almost 2 years

    Just trying to figure out how to use many multiple cases for a Java switch statement. Here's an example of what I'm trying to do:

    switch (variable)
    {
        case 5..100:
            doSomething();
        break;
    }
    

    versus having to do:

    switch (variable)
    {
        case 5:
        case 6:
        etc.
        case 100:
            doSomething();
        break;
    }
    

    Any ideas if this possible, or what a good alternative is?

  • Bala R
    Bala R about 13 years
    @FunJavaCode AFAIK you can do that in vb.net . Here's an example
  • Paŭlo Ebermann
    Paŭlo Ebermann about 13 years
    Groovy allows this too, and I think Pascal has also a similar syntax.
  • Bala R
    Bala R almost 12 years
    @YuryLitvinov do you want to expand why you think it's incorrect?
  • Blaine Mucklow
    Blaine Mucklow over 11 years
    The questioner said do this "versus" doing this. He understands that what you listed is valid, he was trying to do the first thing INSTEAD of that.
  • Admin
    Admin over 11 years
    My answer proves this is incorrect, it is OO and is a known and accepted pattern for dealing with this exact problem amoungst others that require many nested if/elseif/else statements, regardless of language.
  • Bdoserror
    Bdoserror over 11 years
    That is the same as the "versus" part of his question, which he wanted to avoid.
  • markus
    markus over 11 years
    Code only answers are almost as bad as link only answers. They're not really answers at all. A good answer contains explanations and reasoning and possibly some sources or authority.
  • animuson
    animuson about 11 years
    I'm sorry, but I don't see how listing out 95 cases in a row that go to the same thing is a solution to anything. If I encountered that in any code I would track them down, kidnap them, deliver them personally to GLaDOS, and hope she gives them the deadliest sequence of tests she can find.
  • Dzyann
    Dzyann about 11 years
    @JarrodRoberson Although I think the Chain of responsibility pattern is very good. The question was specific to the switch pattern. And the code you posted in the end has ifs too. So how the answer is wrong?
  • Admin
    Admin about 11 years
    its not about not using if or switch it is about using if or switch statements with dozens or hundreds of alternatives cases. The question specifically asks for a good alternative, my answer is the most relevant and OO answer so far.
  • JeremyK
    JeremyK over 10 years
    I thought the answer was just fine.
  • D4rWiNS
    D4rWiNS about 10 years
    It is better than nothing, some people take that as the best answer, simple and direct
  • kraxor
    kraxor almost 10 years
    I wouldn't recommend this. If you just run through the code, you will have the intuition that case 1 means variable == 1, which leads to confusion and a lot of pain in the long run. If you need to place comments in your code to make it readable, then you did something wrong IMHO.
  • Ravindra Kushwaha
    Ravindra Kushwaha almost 8 years
    It is possible to get the OR condition in the SWITCH case by using these link...plz check it out:- stackoverflow.com/a/16706729/3946958
  • Bohemian
    Bohemian over 7 years
    The question already offers this as a solution and asks if there's a way to specify a range without having to code every value in the range (OP would require 96 case statements!). I'm afraid I agree with the accepted answer.
  • anoop ghildiyal
    anoop ghildiyal over 7 years
    bro its possible use can write multiple case without using break and at the end of case you can write your logic like: case some_value: case some_value: case some_value: you_logic_goes_here break;
  • Kevin Robatel
    Kevin Robatel over 7 years
    @FunJavaCode Kotlin has it too, which is compatible with Java. kotlinlang.org/docs/reference/control-flow.html#when-express‌​ion
  • WesternGun
    WesternGun over 7 years
    Thanks for comment. See edit, maybe. I agree that it all depends on the scenario, and 5 vs 95 may not be the case.
  • user1735921
    user1735921 over 6 years
    You must be kidding me, its very much possible to do it. Simple don't apply a break in the end. Your answer is misleading.
  • user1735921
    user1735921 over 6 years
    The actual Answer which deserved thumbs up. Nice.
  • AechoLiu
    AechoLiu over 5 years
    Swift has it too. 'case 1 ... 100', or case 1 ..< 101.
  • killjoy
    killjoy over 5 years
    @animuson on top of which, he gets upvoted 60 times....go figure. I came here coz I didnt want to do the EXACT thing he answers
  • iheanyi
    iheanyi over 5 years
    Downvoting as this does not answer the question. . .heck, apparently, the question wasn't even read in order to write this answer.
  • Erikas
    Erikas over 5 years
    Golang also have it. tour.golang.org/flowcontrol/11 (9, 10 and 11 pages)
  • JBoy
    JBoy over 3 years
    Why is this the accepted answer? this operation is totally possible in Java
  • Osama Hussain
    Osama Hussain over 2 years
    It is possible using multiple switch cases see my answer
  • Marko Zajc
    Marko Zajc about 2 years
    Your solution uses three tenary operators and three switches for a problem that could be solved with an (ugly but arguably better) if-else chain.