Need help, please | SoloLearn: Learn to code for FREE!

+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.

3/9/2018 12:02:35 PM

Nikola Djekic

4 Answers

New Answer

+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

+3

wow, never thought it could be that tricky. Thanks a lot, this really helped me understand how it works. :)

+3

I bet this code will never run. There are syntax errors. How the hell was it approved by Sololearn ?

+2

That's my bad, sorry. Instead of "=" comes ":" in switch statement.