+ 1

Pls Explain how this results in 52 and not 85?

int x = 0; int y = 0; for (int z = 1; z < 5; z++) { if((++x > 2) && (++y > 1)) { x++; } } System.out.print(x + "" + y);

6th Jun 2019, 8:17 AM
Heisenberg
Heisenberg - avatar
1 Answer
+ 2
Just display the values of x and y at the beginning of each loop. Remember: when you do if(a && b) { then you only enter the if when a and b both evaluate to true. That means if a evaluates to false you already know that you won't enter the if. So you don't need to evaluate b, and in fact you don't. That means that with if((++x > 2) && (++y > 1)) { you'll spend some iteration evaluating ++x but not evaluating ++y as ++x > 2 was false. Therefore for some iterations x will be incrementing but y won't. It is true that this is rather confusing. It demonstrates that when you evaluate conditions, they **really should not** modify the state of variables (also called, have side-effects). The conditions should be about knowing whether something is true or false, and **not at all** about changing anything to anything.
6th Jun 2019, 9:53 AM
kumesana