+ 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);
3 Answers
+ 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
+ 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
+ 1
thanks!