Can someone explain this Java code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Can someone explain this Java code?

class Test { public static void main(String [] args) { int x= 0; int y= 0; for (int z = 0; z < 5; z++) { if (( ++x > 2 ) && (++y > 2)) { x++; } } System.out.println(x + " " + y); } } The output is: 6 3 I am unable to understand it as to why?

24th Jun 2017, 6:41 AM
Tamoghna Saha
4 Answers
+ 3
It's due to a comparison short circuit in the if statement. Since ++x > 2 is false the other comparison isn't checked until the 1st is true. for loop iterates 5 times 1st: ++x is ran in conditional and ++y is not x = 1 y = 0 and if body is skipped 2nd: ++x is ran again and ++y is not x = 2 y = 0 if body is skipped 3rd: ++x is ran and now ++y is ran x = 3 y = 1 if body is skipped 4th: ++x and ++y are ran x = 4 y = 2 if body is skipped 5th: ++x and ++y are ran x = 5 y = 3 if body is ran x++ is ran x = 6 y = 3
24th Jun 2017, 7:05 AM
ChaoticDawg
ChaoticDawg - avatar
+ 18
I guess you want to know the reason why y isn't 6? It is because the jre just checks if the first expression (++x>2) is true and then recognises the AND operator. It doesn't evaluate the second expression (++y>2) if the first is false, because it already knows that the result of the boolean expression is false (AND results in false if one of the operands is false).
24th Jun 2017, 6:56 AM
Tashi N
Tashi N - avatar
+ 2
ChaoticDawg nuce explanation
24th Jun 2017, 7:08 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 1
thanks everyone... understood :)
24th Jun 2017, 7:29 AM
Tamoghna Saha