+ 2

Need help, please

I did a challenge and I got this question: int a=5; switch(a) { case 1 = ++a; case 5 = ++a; default = ++a; } System.out.print(++a); System.out.print(--a); the answer was: 87. Can somebody please give me an explenation to this, why is that so, I just don't get it.

9th Mar 2018, 12:02 PM
Nikola Djekic
Nikola Djekic - avatar
4 Réponses
+ 13
If we ignore the syntax errors, case 5 will be executed: ++a will make a = 6 Since there is no break after case 5, default case will also be executed: ++a will make a = 7 When it prints ++a, pre-increment will assign 8 to both a and ++a So, it'll print 8 When it prints --a, pre-decrement will assign 7 to both a and --a So, it'll print 7 Both the values are printed without any space, so the output will be: 87
9th Mar 2018, 12:11 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 3
wow, never thought it could be that tricky. Thanks a lot, this really helped me understand how it works. :)
9th Mar 2018, 12:13 PM
Nikola Djekic
Nikola Djekic - avatar
+ 3
I bet this code will never run. There are syntax errors. How the hell was it approved by Sololearn ?
9th Mar 2018, 12:15 PM
cHiRaG GhOsH
cHiRaG GhOsH - avatar
+ 2
That's my bad, sorry. Instead of "=" comes ":" in switch statement.
9th Mar 2018, 1:17 PM
Nikola Djekic
Nikola Djekic - avatar