Page 1 of 1

About Question com.enthuware.ets.scjp.v6.2.286 :

Posted: Sun Aug 05, 2012 1:50 pm
by ETS User
Respected Sir,
The following question is:

What will the following code print?


int i = 0;
int j = 1;
if( (i++ == 0) && (j++ == 2) )
{
i = 12;
}
System.out.println(i+" "+j);

The answer given is it will print 1 2 ( i=1 and j=2)...

The explanation given says if( (i++ == 0) & (j++ == 2) ) is evaluated...
and rightfully gives 1 2 as answer..But the question as && operator which is a short circuit operator..
So only (i++ == 0) gets evaluated to true and the answer becomes 12 1..which is in option 4..

Please kindly correct this..

Thanks for the excellent Software,
Bharath K
Mysore,India

Re: About Question com.enthuware.ets.scjp.v6.2.286 :

Posted: Sun Aug 05, 2012 8:35 pm
by admin
Short circuit means the rest of the expression is NOT evaluated ONLY IF the value of the whole expression can be determined just by evaluating the first part of the expression. In the given expression, (i++ == 0) is true, but what if the next expression is false? In that case the value of the whole expression will be false. Therefore, in this case the first expression does not tell you the value of the whole expression, so the rest of the expression must be evaluated. Had the first expression been false, there was no need to evaluate the rest. Because no matter what is the value of the rest of the expression (true or false), the value of the whole expression will be false.

It is reverse with ||. Please read more about it.

HTH,
Paul.