+ 3
value x result
//why does x return 2?. isnt it suppose to be 1 because of ++x; int x = 0; for (int z = 0; z<5 ; z++) { if ((z>2)&&(++x>2)) { x+=7; } } System.out.print(x); still dont get it **result : x =2
3 Answers
0
x is incremented twice, once when z = 3, once when z = 4.
0
Right, so x starts as 0, z as 0
Loop iteration 1:
z is 0, not > 2. Since the first part of && (namely z > 2) is false, we do not need to evaluate the second part (which is ++x > 2).
Iteration 2:
z is 1, x is still 0. z is still not > 2, so again we do nothing.
Iteration 3:
z 2, x 0. Still same.
Iteration 4:
z 3, x 0. z is finally > 2, so we evaluate the second part of &&. ++x is 1, not > 2, so false, (z > 2) && (++x > 2) = true and false = false, so we do not execute the if statement. x is incremented to 1.
Iteration 5:
z 4, x 1. z is > 2, so we evaluate the second part of &&. ++x is 2, not > 2, so false, and the condition is again false, so we still do not execute the if statement. x is incremented to 2.
Iteration 6:
z 5, x 2. Exit the loop.
In the end, x is 2.
- 1
You need to understand how && and ++ work. The Java Tutorial explains them well enough.