3
class switch1
{
    public static void main(String args[])
    {
        int a = 10;
        switch(a)
        {
            default: System.out.println("Default");
            case -1: System.out.println("-1");
        }
    }
}

I understand that this program will execute both "default" and "case -1" statements as break is not specified after the matching condition (in this case after "default").

But what I fail to understand is

a) why is break needed in a switch statement?

b) why does it even execute the invalid matching conditions' statements (i.e executing "case -1")) if all it does is matching?

icedwater
  • 4,701
  • 3
  • 35
  • 50
UnderDog
  • 3,173
  • 10
  • 32
  • 49
  • 4
    It's just because that's how it works in C, and Java looks enough like C that programmers would be surprised if it didn't do that. – Gabe Aug 22 '13 at 04:30
  • the switch likely evolved from the GOTO statements. if you've ever coded with GOTOs you can imagine why the switch behaves that way – aldrin Aug 22 '13 at 04:39
  • 2
    possible duplicate of [Why do we need break after case statements?](http://stackoverflow.com/questions/2710300/why-do-we-need-break-after-case-statements) – Raedwald Aug 22 '13 at 07:16
  • `switch` is defined in C the way it is because C is basically a macro language for assembler, and there is a specifically optimal way of implementing C's `switch` in terms of machine instructions. – Marko Topolnik Aug 23 '13 at 11:28

9 Answers9

14

Sometimes you need multiple cases to execute the same function. For example, I am letting a user specify either mode 1 or mode 32 to represent 32-bit mode, and mode 2 or mode 64 for 64-bit mode.

switch (input) {

    case 1:
    case 32:
        /* Do 32-bit related code */
        break;
    case 2:
    case 64:
        /* Do 64-bit related code */
        break;
    default:
        System.out.println("Invalid input");

}

This is why breaks are important. They tell the switch statement when to stop executing code for a given scenario. Additionally, the default is generally used for when the switch does not match ANY case.

hotforfeature
  • 2,558
  • 1
  • 16
  • 24
4

switch statements without breaks let you do things like this:

// Compute the most significant bit set in a number from 0 to 7
int topBit = -1;
switch(n) {
case 0:
    topBit = 0;
    break;
case 1:
    topBit = 1;
    break;
case 2:
case 3:
    topBit = 2;
    break;
case 4:
case 5:
case 6:
case 7:
    topBit = 3;
    break;
}

Essentially, it lets you create a set of labels, and have a condition at the top to let you jump to the initial label once. After that, the execution continues until a break, or reaching the end of the switch. This technique is old - it has been around since the assembly times, and by virtue of being included in C has made its way into Java and several other languages.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    "set of labels" - that's an important note. the case statements are not conditions, but rather labels. – aldrin Aug 22 '13 at 04:36
1

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.

check this documentation : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Dipak
  • 6,532
  • 8
  • 63
  • 87
1

As for a., requiring the use of break allows shorthand notation where common code can be placed at the bottom block. This may make code more readable in some cases.

See "Switch statement fallthrough in C#?" for more information on fallthrough.

As for b., since it matches the default case, that line is executed. Because no break is present in that block, the next line is also executed regardless of a match.

Try

switch (a)
{
    case 10: System.out.println("This is 10.");
    case 9 : System.out.println("This is 9.");
             break;
    case 8 : System.out.println("This is 8.");
             break;
    default: System.out.println("Default");
}

Because there is no break in the matching case, the output is

This is 10.
This is 9.

Compare this with setting a to 11, 9, or 8.

Community
  • 1
  • 1
icedwater
  • 4,701
  • 3
  • 35
  • 50
1

From the Java Language Specification section on the break statement:

A break statement transfers control out of an enclosing statement.

and...

a break statement ... always completes abruptly

a) It simply allows transfer of control out of the case statement.

b) The reason why it executes the conditions that aren't what you would expect to be matching is because there are particular conditions where falling through case statements would be considered valid (Taken from The Java Tutorials):

List<String> futureMonths = new 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");
             break;
    default: break;
}

for (String monthName : futureMonths) {
    System.out.println(monthName);
}

Which outputs:

August

September

October

November

December

Community
  • 1
  • 1
edwardsmatt
  • 2,034
  • 16
  • 18
1

a) why does a switch statement relies heavily on a break statement to achieve its purpose ?

Because that's the way they defined it. It's copied from C. Pascal doesn't have fall-through, so it doesn't have break either. It also has case ranges, which Java lacks. Languages are allowed to be different. Or the same.

b) why does it even execute the invalid matching conditions' statements (i.e executing "case -1"))

Because that's the way they defined it, with fall-through if you don't put a break.

if all it does is matching ?

I don't understand the question. It doesn't do matching. It does an indexed jump to the relevant case, and falls through to the next statement if you don't put a break.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

If you add break to a loop, it cancels out of the loop. so for a switch statement it goes to the correct case and once it is there it carries out the code until the break where it will then exit the switch statemnt. If you removed the break it would carry on to the next case and until is sees a break. If there are no break; the code will crash.

So basically it separates different cases

Cam Connor
  • 1,231
  • 2
  • 25
  • 40
0

In Switch case the 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.

The program SwitchDemoFallThrough shows statements in a switch block that fall through. The program displays the month corresponding to the integer month and the months that follow in the year:

public class SwitchDemoFallThrough {

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");
                 break;
        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

Technically, the final break is not required because flow falls out of the switch statement. Using a break is recommended so that modifying the code is easier and less error prone. The default section handles all values that are not explicitly handled by one of the case sections.

Look Here for complete information about switch

Dileep
  • 5,362
  • 3
  • 22
  • 38
0

a) Why fall-through / required break in switch?

The fall-through behavior is useful in some cases, but the problem is that it's extra work in the common case. Therefore it's reasonable to expect that the "break" keyword would not be required in a more modern language

So why is it there? To match the behavior of C++ (dominant language at the time Java was designed), which again matches the behavior of C (dominant language at the time C++ was designed). As for C, it (and B and BCPL, its predecessors) usually looks the way it does to make it easier to build an efficient compiler. Basically the way the switch statement works is the natural way to implement it in assembler.

b) The way it behaves follows logically from the decision to use fall-through.

Anders Johansen
  • 10,165
  • 7
  • 35
  • 52