+ 2

Can anyone explain the logic? I've tried many times

How is the output 52? public class Program { public static void main(String[] args) { int x=0,y=0; for(int j=1;j<5;j++){ if(++x>2&&++y>1) { x++; } } System.out.print(x+""+y); } }

10th May 2017, 6:40 AM
Prathamesh Jadhav
Prathamesh Jadhav - avatar
4 Réponses
+ 8
ok well the first thing is to remember how java evaluates multiple conditions. if (++x > 2 && ++y > 1) if ++x > 2 is false, then java wont evaluate the other side, because if one side is false, then false && anything will always be false, hence the right side isnt evaluated (++y isnt incremented) so with that in mind, if ++x > 2 is true, it will evaluate ++y > 1 and if that is also true, then the if branch is executed. now lets go through it: j x y ------------ 1 1 1 2 2 0 3 3 1 4 4 2 5 the inside of the if branch is executed when j = 4 because then both conditions of the if statement are true, so finally x is incremented from 4 to 5 so x is 5 and y is 2 if i did it correctly
10th May 2017, 6:44 AM
Edward
+ 6
@Edward: Nice Answer!
10th May 2017, 6:50 AM
jay
jay - avatar
+ 4
thanks @jay. and no problem @prathamesh. i also didnt know that when i first started learning java. same goes for || if (x > 2 || y > 7) if x> 2 is true, then the body is executed because true || anything else is always true. only evaluates the right side if x > 2 is false
10th May 2017, 6:53 AM
Edward
+ 3
Didn't know java evaluated conditions like this. Thanks for the explanation. You are awesome!
10th May 2017, 6:51 AM
Prathamesh Jadhav
Prathamesh Jadhav - avatar