-1

I understand that Java switch case are designed this way but why is this behavior in Java

    int x = 1;

    switch(x){
    case 1: System.out.println(1);
    case 2: System.out.println(2);
    case 3: System.out.println(3);
    default: System.out.println("default");

    }

output : 1
         2   
         3
         default

My question is why case 2 and 3 are executed? I know I omitted break statement
but x was never 2 or 3 but case 2 and case 3 still executes?

Paul Samsotha
  • 197,959
  • 33
  • 457
  • 689
supernova
  • 2,874
  • 4
  • 29
  • 30
  • 5
    Without a `break;` or `return;` it runs all the code in order. This is not strange but completely normal for a switch statement. – Peter Lawrey Nov 10 '13 at 15:49
  • Guys, I already mentioned I know I am not using break statements intentionally. Please don't suggest me to use break statements after each case statement. My intention was just to explore the reason for this behavior. – supernova Nov 10 '13 at 16:18
  • I am confused as to what the question is. When you put one statement after another, you want to know why they were executed in the order they appear? A case statement is just a label. It doesn't "execute" anything. – Peter Lawrey Nov 10 '13 at 16:44
  • @Raedwald Yeah that question better explains my concern and have better answers.So 'Fall through" have some benefits in many cases. – supernova Jan 26 '16 at 15:00

4 Answers4

4

There is no break statement so all case are executed

Use break statements

switch(x){
    case 1: System.out.println(1);break;
    case 2: System.out.println(2);break;
    case 3: System.out.println(3);break;
    default: System.out.println("default");

    }
Rahul Tripathi
  • 161,154
  • 30
  • 262
  • 319
3

I know I omitted break statement but x was never 2 or 3 but case 2 and case 3 still executes?

Straight from the doc :

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.

Alexis C.
  • 87,500
  • 20
  • 164
  • 172
1

You need to add break statement for each case. As there is no break statement all cases are getting executed.

Dark Knight
  • 8,002
  • 4
  • 34
  • 56
0

You are missing the Break statement.

switch(x){
case 1: System.out.println(1);
break;
case 2: System.out.println(2);
break;
case 3: System.out.println(3);
break;
default: System.out.println("default");
}

Check the The switch Statement

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.

Rahul Tripathi
  • 161,154
  • 30
  • 262
  • 319