Page 1 of 1

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

Posted: Mon Jun 20, 2011 6:44 am
by ETS User
The Question stated:

Code: Select all

What will the following code print?


  int i = 0;
  int j = 1;
  if( (i++ == 0) [b]&&[/b] (j++ == 2) )
  {
     i = 12;
  }
  System.out.println(i+" "+j);
In the explanation the answer stated:

Code: Select all

This question is based on 2 concepts:

1. i = = ++j is not same as i = = j++;
In the case of i == ++j, j is first incremented and then compared with i. While in the case of i == j++;, j is first compared with i and then incremented.

2. The | operator, when applied for boolean operands, ensures that both the sides are evaluated. This is opposed to || which does not evaluate the RHS if the result can be known by just evaluating the LHS.

Now, let us see the values of i and j at each step:

int i = 0;
int j = 1;
if( (i++ == 0) [b]&[/b] (j++ == 2) )    //compare i with 0 and increment i => returns true and i becomes 1. Evaluate next condition:
		//compare j with 2 and increment j => return false and j becomes 2.
		//true & false returns false so i= 12 is not executed.
{
	i = 12;
}
System.out.println(i+" "+j)); //print 1 and 2
This is not the same. The answer should be: 12 1 in stead of 1 2

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

Posted: Mon Jun 20, 2011 5:23 pm
by admin
Hello,
I just ran the code and it prints 1 2 as stated. Could you please specify why it should print 12 1?

HTH,
Paul.

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

Posted: Mon Mar 26, 2012 5:52 am
by Guest
yes, the explanation is misleading. The answer ist still correct but for a differetn reason: the && operator does not ensure that both the sides are evaluated. But in this case it needs to evaluate the second side also as the first side comes out as true.

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

Posted: Mon Mar 26, 2012 6:43 pm
by admin
I see the problem. You are right. The explanation is not for this question. This has now been fixed.

thank you for your feedback!