Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java switch statement with += / -= operators

Tags:

java

Really simple question, but can't figure this out. Why does y compute to 2 in the (Java) code below?

int x = 2;
int y = 2;
switch (x * 2) {
    case 4: y += 1;
    case 6: y -= 2;
    default: y += 1;
}
like image 389
user1689640 Avatar asked Sep 21 '12 18:09

user1689640


2 Answers

It falls through from case 4 to case 6 to the default, so it increments (new value: 3), decrements by 2 (new value: 1) and then increments (new value: 2).

The compiler should have warned you about the fall-through, at least if you use -Xlint. Never ignore compiler warnings out of hand, and always compile with -Xlint :)

like image 178
Jon Skeet Avatar answered Nov 14 '22 21:11

Jon Skeet


You forgot to add break:

int x = 2;
int y = 2;
switch (x * 2) {
    case 4: 
        y += 1;
        break;
    case 6:
        y -= 2;
        break;
    default: y += 1;
}
like image 44
arshajii Avatar answered Nov 14 '22 23:11

arshajii