Why do we need break after case statements?

Sometimes it is helpful to have multiple cases associated with the same code block, such as

case 'A':
case 'B':
case 'C':
    doSomething();
    break;

case 'D':
case 'E':
    doSomethingElse();
    break;

etc. Just an example.

In my experience, usually it is bad style to "fall through" and have multiple blocks of code execute for one case, but there may be uses for it in some situations.


Java comes from C and that is the syntax from C.

There are times where you want multiple case statements to just have one execution path. Below is a sample that will tell you how many days in a month.

class SwitchDemo2 {
    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);
    }
}

Historically, it's because the case was essentially defining a label, also known as the target point of a goto call. The switch statement and its associated cases really just represent a multiway branch with multiple potential entry points into a stream of code.

All that said, it has been noted a nearly infinite number of times that break is almost always the default behavior that you'd rather have at the end of every case.


I think it is a mistake. As a language construct it is just as easy to have break as the default and instead have a fallthrough keyword. Most of the code I have written and read has a break after every case.


You can do all sorts of interesting things with case fall-through.

For example, lets say you want to do a particular action for all cases, but in a certain case you want to do that action plus something else. Using a switch statement with fall-through would make it quite easy.

switch (someValue)
{
    case extendedActionValue:
        // do extended action here, falls through to normal action
    case normalActionValue:
    case otherNormalActionValue:
        // do normal action here
        break;
}

Of course, it is easy to forget the break statement at the end of a case and cause unexpected behavior. Good compilers will warn you when you omit the break statement.