Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

In my code, the program does something depending on the text entered by the user. My code looks like:

switch (name) {
        case text1: {
            //blah
            break;
        }
        case text2: {
            //blah
            break;
        }
        case text3: {
            //blah
            break;
        }
        case text4: {
            //blah
            break;
        }

However, the code inside cases text1 and text4 is the same. I was therefore wondering if it would be possible for me to implement something like

case text1||text4: {
            //blah
            break;
        }

I know that the || operator won't work in the case statement but is there something similar I can use.

share|improve this question
71  
Why so many upvotes? Search for "java switch" in the internet and read one of the thousand explanations. – Chris May 23 at 9:20
2  
Was wondering the same thing, such a trivial question... – MMM May 23 at 9:22
6  
Being a basic question makes it if anything more eligable for upvotes if its not a duplicate as its widely useful. And its something that didn't occure to me as possible but now that I realise it its blindingly obvious. So all in all a pretty awesome Q&A – Richard Tingle May 23 at 12:58
1  
@RichardTingle - are you familiar with Duff's Device - en.wikipedia.org/wiki/Duff%27s_device – user93353 May 24 at 4:25
5  
One lucky guy who got free reputation.. so jealous – Java Enthusiast May 24 at 5:14

8 Answers

up vote 77 down vote accepted

You can use have both CASE statements as follows.

  case text1: 
  case text4:{
            //blah
            break;
        }

SEE THIS EXAMPLE:The code example calculates the number of days in a particular month:

 class SwitchDemo {
    public static void main(String[] args) {

        int month = 2;
        int year = 2000;
        int numDays = 0;

        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                numDays = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                numDays = 30;
                break;
            case 2:
                if (((year % 4 == 0) && 
                     !(year % 100 == 0))
                     || (year % 400 == 0))
                    numDays = 29;
                else
                    numDays = 28;
                break;
            default:
                System.out.println("Invalid month.");
                break;
        }
        System.out.println("Number of Days = "
                           + numDays);
    }
}
This is the output from the code:

Number of Days = 29

FALLTHROUGH:

Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.

EXAMPLE CODE:

 public class SwitchFallThrough {

    public static void main(String[] args) {
        java.util.ArrayList<String> futureMonths =
            new java.util.ArrayList<String>();

        int month = 8;

        switch (month) {
            case 1:  futureMonths.add("January");
            case 2:  futureMonths.add("February");
            case 3:  futureMonths.add("March");
            case 4:  futureMonths.add("April");
            case 5:  futureMonths.add("May");
            case 6:  futureMonths.add("June");
            case 7:  futureMonths.add("July");
            case 8:  futureMonths.add("August");
            case 9:  futureMonths.add("September");
            case 10: futureMonths.add("October");
            case 11: futureMonths.add("November");
            case 12: futureMonths.add("December");
            default: break;
        }

        if (futureMonths.isEmpty()) {
            System.out.println("Invalid month number");
        } else {
            for (String monthName : futureMonths) {
               System.out.println(monthName);
            }
        }
    }
}
This is the output from the code:

August
September
October
November
December

FROM Java Docs

share|improve this answer
oh ok. That was easy. Didn't know I could do that – Ankush May 23 at 6:14
6  
It's worth to mention that this language feature is called fallthrough. Cases without break are basically appended with next case block which is visually below, hence fall through. – Emperor Orionii May 23 at 7:40
@EmperorOrionii i updated my answer as you are suggested.Thanks – PSR May 23 at 8:12
5  
@Kobor42 first learn how to talk in public sites.Any how your suggestion is help ful.Thanks – PSR May 23 at 16:22
1  
@Kobor42 How about: Why have you used that formatting? Putting cases horisontally makes the code less readable and is generally considered bad practice [Reference optional but desired]. I have always felt that switch statements are a particularly readable format but presented this way they lose all that. – Richard Tingle May 25 at 20:11
show 4 more comments

you can do like:

case text1:
case text4: {
            //blah
            break;
}
share|improve this answer
for OP: read this also Java switch cases: with or without braces? – Grijesh Chauhan May 23 at 6:25

The case values are just codeless "goto" points that can share the same entry point:

case text1:
case text4: 
    //blah
    break;

Note that the braces are redundant.

share|improve this answer
4  
It's always a good thing when your entry points are sane. – TRiG May 23 at 10:19
@trig lol. I'm doing that kind of thing a lot lately - blaming iPhone thumb typing. Cheers – Bohemian May 23 at 12:17

Just do

case text1: case text4: 
     do stuff;
     break;
share|improve this answer

The fallthrough answers by others are good ones.

However another approach would be extract methods out of the contents of your case statements and then just call the appropriate method from each case.

In the example below, both case 'text1' and case 'text4' behave the same:

switch (name) {
        case text1: {
            method1();
            break;
        }
        case text2: {
            method2();
            break;
        }
        case text3: {
            method3();
            break;
        }
        case text4: {
            method1();
            break;
        }

I personally find this style of writing case statements more maintainable and slightly more readable, especially when the methods you call have good descriptive names.

share|improve this answer
1  
It is not more maintainable if text1 and text4 will ALMOST CERTAINLY do the same thing, regardless of a future change. If they should always be linked, making a change in the case for text1 (meaning changing which method it calls) would require a change in text4. In this case it is obviously not more maintainable. It depends on the situation. – Nick Freeman May 23 at 21:49
1  
I will say that this method should probably be combined with the other way anyway, since switch statements are not (IMHO) the prettiest programming structure. – Nick Freeman May 23 at 22:02

The brackets are unnecessary. Just do

case text1:
case text4:
  doSomethingHere();
  break;
case text2:
  doSomethingElse()
  break;

If anyone is curious, this is called a case fallthrough. The ability to do this is the reason why break; is necessary to end case statements. For more information, see the wikipedia article http://en.wikipedia.org/wiki/Switch_statement.

share|improve this answer

Simplest trick it to use same method from both cases.

 switch (name) 
{
case text1: 
{
method1();
break;
}
case text2: 
{
method2();
break;
}
case text3:
{
method3();
break;
}
case text4: 
{
method1();
break;
}
}

private void method1()
{
//do the logic which is same
}
share|improve this answer
1  
this doesn't answers because Ankush(OP) knows this, he was looking for combine both cases... – Grijesh Chauhan May 24 at 7:33
Both are almost same, In both cases switch case executes for two times – Rahul Saksule May 24 at 8:38

As stated in the other answers, the fallthrough feature of the switch statement in Java language is what you are looking for (the removal of the brackets sould be applied too):

switch (name) {
    case text1: 
    case text4:
        doActionOne();
        break;  
    case text2:
        doActionTwo();
        break;
    case text3:
        doActionThree();
        break;
}

But, while this solution answers your immediate question, I think it's important to highlight that the question itself should be widened to include alternative solutions, preferably to the usage of a switch statement and definitely considered as Best Practices in Object Oriented Programming.

  1. Switch and If statements should be avoided when possible. They will limit the Readability, Reusability, Replaceability, Testability and Maintainability of your code. All this reasons led to the birth of initiatives like the Anti-If-Campaign; you should not stop using ifs and switches at all, but it would be better to delegate them to perform trivial tasks only; complex tasks like your could be engineered in several ways;

  2. While Switch statements could be exploited in the C language to perform the loop unrolling technique and optimize the program's execution speed (like in the Duff's device mentioned by an commenter of your question), it would not be possible to speed up Java code that way. All the sacrifices of point n.1 will not lead to any benefit even by the virtual machine point of view... just to be sure it is clear.

  3. Generally, the Polymorphism OOP feature should be used to achieve tasks like your; it would be better to have 100 different objects and instantiate the right one instead of having 100 hard coded switch's case statements (for all the reasons of point n.1). Each different behaviour would be coded in a single, self-contained place, they could be tested, maintained, reused in other parts of your projects, and you would be able to export a subset of this objects to another project without the needs to edit and refactor any code (the huge switch for example); The entities used by your software could then be translated in objects like this:

    public Interface Action {
        public void doSomething();
    }
    
    public class ActionOne implements Action {
        public void doSomething(){
            System.out.println("doSomething One");
        }
    }
    
    public class ActionTwo implements Action {
        public void doSomething(){
            System.out.println("doSomething Two");
        }
    }
    
    public class ActionThree implements Action {
        public void doSomething(){
            System.out.println("doSomething Three");
        }
    }
    
  4. For an even stricter usage, instead of different objects you could create an enum as "polymorphic anti-if agent", like described in this great answer by Robert C. Martin (one of the founding fathers of the Agile Software Development).

  5. Since in your case, the conditions are not from, for example, a <select> (where each element of the Select List could have been translated to a different object in Java, like described above), but from a free inputable <input type="text">, for this specific case, I think that a nice solution would be the following: use an HashMap with multiple keys pointing to the same objects.

    on an initialization object:

    // initialization (performed once)
    HashMap<String,Action> map = new HashMap<String,Action>();
    ActionOne actionOne     = new ActionOne();
    ActionTwo actionTwo     = new ActionTwo();
    ActionThree actionThree = new ActionThree();
    map.put("text1", actionOne);
    map.put("text2", actionTwo);
    map.put("text3", actionThree);
    map.put("text4", actionOne); /* <-- here you are referencing 
                                    the first object with a new key */
    

    on one (of n) object(s) where you perform the business

    // usage ("parsing")
    String userInput = request.getParameter("userInput");
    if (map.contains(userInput))
        map.get(userInput).doSomething();
    

The last two lines could replace a huge switch statement, and they can be put in other 100 classes without rewriting your initialization object (that would be in a reusable class apart), nor any single Action object's business logic, located inside each Action object.

And what about adding new objects (let's say ActionFour) ?
It would only need creating of the object itself and adding it in the initializazion class. No matters if the parsing from the input will be performed in 100 different classes, none of them would need to be touched at all.
Pretty cool uh ?

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.