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

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
ETS User

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

Post 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

admin
Site Admin
Posts: 10385
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.

Post Reply

Who is online

Users browsing this forum: witek_m and 18 guests