Quiz question: increments | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Quiz question: increments

Please explain why the answer is 1 and not 0. Int x = 0; int y = 0; if(++x > 4 && ++y > 2) x++; System.out.println(x); I understand that ++x would increment 0 to 1, and ++y would increment 0 to 1, but 1 is not greater than 4 and 1 is not greater than 2, so the statement x++ would be skipped, and x should still be 0. Why is the correct answer 1?

27th Mar 2020, 9:56 PM
Joshua Stamps
Joshua Stamps - avatar
3 Answers
+ 2
Joshua Stamps , the if clause is false , because the first part of the expression is false (that's why the second part is not evaluated and y is not incremented) => 1 > 4 is false (but x is becoming 1 - preincrement operation => ++x). So it prints 1 🐱
27th Mar 2020, 10:04 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
0
Ok, so regardless whether the if statement is true or false, x is still preincremented to 1?
28th Mar 2020, 9:07 PM
Joshua Stamps
Joshua Stamps - avatar
0
Joshua Stamps , yes because first part of the if expression includes preincrement operation.
28th Mar 2020, 11:14 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar