1

If we take this code as an example :

switch (PeriodEnum.getEnum(month).getValue()) {
            case 0: // Calendar.JANUARY
            case 2: // Calendar.MARCH
            case 4: // Calendar.MAY
            case 6: // Calendar.JULY
            case 7: // Calendar.AUGUST
            case 9: // Calendar.OCTOBER
            case 11: // Calendar.DECEMBER
                nbDays = 31;
            break;
            case 3: // Calendar.APRIL
            case 5: // Calendar.JUNE
            case 8: // Calendar.SEPTEMBER
            case 10: // Calendar.NOVEMBER
                nbDays = 30;                
            break;

What is the difference between the previous code and the code below?

   switch (PeriodEnum.getEnum(month).getValue()) {
            case 0: // Calendar.JANUARY
                 nbDays = 30;
                 break;
            case 2: // Calendar.MARCH
                 nbDays = 30;
                 break;
            case 4: // Calendar.MAY
                 nbDays = 30;
                 break;


   ....
}

As a beginner in java , I would love to understand the difference . The main thing I don't understand is how the IDE will detect the case based on the month and associate it?

Thank you

Novaterata
  • 4,356
  • 3
  • 29
  • 51
  • Wait... You know that you can use a switch statement with enum values, right? – fge Aug 30 '17 at 14:22
  • @fge: Those aren't enums, they're `static int`s (if you're talking about the `Calendar.JANUARY` etc.). – T.J. Crowder Aug 30 '17 at 14:23
  • @fge Right , but it's not even my question , I just don't understand how the grouping works –  Aug 30 '17 at 14:24
  • @T.J.Crowder I meant to use `JANUARY` etc as values – fge Aug 30 '17 at 14:24
  • The `switch` statements aren't doing the same thing. If you omit `break` from a case, then it falls through to the next case. – Tim Biegeleisen Aug 30 '17 at 14:25
  • your current second snippet is the worst way of doing it since you have a fall-through since you are missing the breaks, repeat the code of `nbDays = 30;` and if you would not repeat it, you would overwrite the same value multiple times. – luk2302 Aug 30 '17 at 14:25
  • So, the question is about what code is generated for those different cases? Yet you mention the IDE in your question – fge Aug 30 '17 at 14:26
  • @TimBiegeleisen Hi and thank you for taking time reading my post. So if I understand correctly , the case will group "cases" till it detect a break and if not it will fall into the other groups of "cases" . I'm a student and very beginner in the programming and JAVA world –  Aug 30 '17 at 14:28

3 Answers3

0

The simple answer is that the compiler is stupid :)

In the first code snippet, the generated JVM code will happily stuff all cases you bundled together into the same branch, and in the second snippet it would, equally happily, stuff each case into its own branch. And even if a set of branches did exactly the same, the compiler doesn't care and won't do the analysis for you.


Now, there is something else to consider in Java, which is that enums are objects like any other... Which means they can have instance variables. Therefore you can do this, and avoid that switch statement altogether:

public enum Calendar
{
    JANUARY(30),
    FEBRUARY(28),
    // etc etc
    ;

    private final int daysInMonth;

    Calendar(final int daysInMonth)
    {
        this.daysInMonth = daysInMonth;
    }

    public int getDaysInMonth()
    {
        return daysInMonth;
    }
}
fge
  • 119,121
  • 33
  • 254
  • 329
  • Indeed , I forgot to add the break statement in my second part of code . Thank you for your time explaining it for me .Also , I was looking to find a way to optimize the switch cases and you did it for me –  Aug 30 '17 at 14:35
  • Glad I could help :) However, do note that `Calendar` is already the name of a class in the JRE (`java.util.Calendar`). If I were you, I'd use another name ;) – fge Aug 30 '17 at 14:45
0

In the first part execution will come out of switch statement after break statement, while in second part the program will continue till the last case.

So for the first part whether the value will be 0, 2, 4.... or whatever the assignment nbdays = 31 will be executed and nbdays = 30 will be executed for 1, 3, 5.... Basically it is a way to minimize writing codes for multiple similar statements.

  • Any idea why some people use this approach? Do you have an idea if there is a better way grouping similar cases? –  Aug 30 '17 at 14:38
  • You may use if(x == 0 || x == 2 )...something like this..there will be more efficient and clear way, but i don't know much.. – Vikram Kumar Aug 30 '17 at 14:45
  • [link]https://stackoverflow.com/questions/5086322/java-switch-statement-multiple-cases – Vikram Kumar Aug 30 '17 at 14:48
  • @EvanBHOPS "omitting" the `break` in `switch` statements is often called a "fall through"; it does have genuine uses which are however quite rare. I wouldn't worry about it right now :) – fge Aug 30 '17 at 14:48
  • @fge You are right , "quite rare" the application I'm working on was developed in 2004 and I was 2 years old back then .... –  Aug 30 '17 at 14:50
  • @EvanBHOPS it's not a question of when the code was written in this case :) The `switch` statement is as old as the Java language itself and is in fact a copycat of C's `switch` in the way it works. I was referring to the fact that in some situations it is legitimate to not `break` between `case`s – fge Aug 30 '17 at 14:53
0

There is no grouping for switch statements. Consider this arbitrary example:

switch (PeriodEnum.getEnum(month).getValue()) {
            case 0: // Calendar.JANUARY
                   jan();
            case 2: // Calendar.MARCH
                   mar();
            case 4: // Calendar.MAY
                   may();
            case 6: // Calendar.JULY
                   jul();
            case 7: // Calendar.AUGUST
                   aug();
            case 9: // Calendar.OCTOBER
                   oct();
            case 11: // Calendar.DECEMBER
                   dec();
                break;

If the switch value is 0, then jan(), mar(), may(), jul(), aug(), oct(), and dec() ALL execute.

If the switch value is 9, then only oct(), and dec() execute.

See what I mean about it not being grouping? Just like if, while, and for, switch statements were a way of avoiding goto statements. We idiomatically use them as a map, or a grouping or whatever, but that's not what they literally are. They are literally: Start where the case matches, then exit at break/continue/return/throw. The process of continuing from one case to the next is called "falling through"

To save some code, wrap your switch in a method and instead of assigning a variable and breaking, just return the value and skip the intermediate variable.

Novaterata
  • 4,356
  • 3
  • 29
  • 51