+ 1

How is the output for this code is 2 and not 19

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

29th Mar 2018, 6:09 AM
Shumendra Tripathi
Shumendra Tripathi - avatar
3 ответов
+ 3
when in if statements there are some conditions, like this if ( a && b && c && d ) when the result found, other conditions will not check, so if a be false, the result will be false, so b && c && d will not check and ignored in your question while z>2 is false ++x will not execute and so x not increase
29th Mar 2018, 6:15 AM
🇮🇷 M N
+ 2
To add to the previous answer, it's part of Java's optimization that in boolean expressions it evaluates up the point it can know the result, (not for & and | though, for && and ||). So in (a > 2 || b < 4) if a was more than 2 the second part isn't checked, because we whether it is true or false the optimization kicks in. This can be useful to avoid null pointer exceptions, if we do if (obj != null && obj.getField() == value) ... in the case where obj is null the second part isn't evaluated, if it were the program would crash with an NPE
29th Mar 2018, 7:10 AM
Dan Walker
Dan Walker - avatar
+ 1
thanks!
29th Mar 2018, 6:21 AM
Shumendra Tripathi
Shumendra Tripathi - avatar