javabeginner
javabeginner

Reputation: 61

Help with switch statement

I am relatively new to java. In a switch statement, do you have to put a break statement after each case?

Upvotes: 6

Views: 556

Answers (6)

user278064
user278064

Reputation: 10180

It's a good practice to put break after each statement.

You're not forced.

But if you don't put breaks tatement you've cascade switch statement, namely more condition could be matched, and sometimes this can lead to logical errors.

However there are people which think that cascade statements can optimize the code, helping to write less code.

Upvotes: 2

Evan Mulawski
Evan Mulawski

Reputation: 55354

You do if you are not exiting the switch statement with a return or other action.

Upvotes: 3

fireshadow52
fireshadow52

Reputation: 6516

No, you don't have to. If you omit the break statement, however, all of the remaining statements inside the switch block are executed, regardless of the case value they are being tested with.

This can produce undesired results sometimes, as in the following code:

switch (grade) {
    case 'A':
        System.out.println("You got an A!");
        //Notice the lack of a 'break' statement
    case 'B':
        System.out.println("You got a B!");
    case 'C':
        System.out.println("You got a C.");
    case 'D':
        System.out.println("You got a D.");
    default:
        System.out.println("You failed. :(");
}

If you set the grade variable to 'A', this would be your result:

You got an A!
You got a B.
You got a C.
You got a D.
You failed. :(

Upvotes: 7

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103145

Semantically yes. Otherwise all case statements after the first matching one would run.

Upvotes: 2

MByD
MByD

Reputation: 137422

It is better you do. Otherwise the next statements will be executed too.

switch(someNumber) {
case thisCaseMatches:
    doThat();
case thisCaseDoesNotMatch:
    shouldntExecuteYetItWillBeExecuted();
default:
    alsoWillbeExecuted();
}

Upvotes: 3

jpredham
jpredham

Reputation: 2199

You don't have to break after each case, but if you don't they will flow into each other. Sometimes you want to bundle multiple cases together by leaving out the breaks.

Upvotes: 5

Related Questions