0

Can you please explain why the answer is 3?

I have the question below but really dont know why is this answer Int a=2; Int x=0; Switch(a){ Case 1: ++x; Case 2: ++x; Case 3:++x; Default: ++x;} System.out.print(x);

18th Dec 2019, 6:12 AM
Sin Mar
Sin Mar - avatar
5 Answers
+ 3
a=2 so switch(2) will go to case 2 where x is incremented by 1 and x=1. But since there is no break statement, case 3 is also executed so x is again incremented by 1 and x=2. Again there is no break so default is also executed and x is incremented by 1 again so final value is x=3.
18th Dec 2019, 7:52 AM
Avinesh
Avinesh - avatar
+ 1
you forgot break after each increment in switch construction
18th Dec 2019, 6:19 AM
Igor Kostrikin
Igor Kostrikin - avatar
+ 1
Without break statement all the three conditions will be executed.
18th Dec 2019, 12:38 PM
Samavedam Praneeth
Samavedam Praneeth - avatar
0
Hi Igor, this is how the q is at tests
18th Dec 2019, 6:39 AM
Sin Mar
Sin Mar - avatar