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;
}
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
:)
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With