About Question com.enthuware.ets.scjp.v6.2.286 :
Posted: Mon Jun 20, 2011 6:44 am
The Question stated:
In the explanation the answer stated:
This is not the same. The answer should be: 12 1 in stead of 1 2
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);
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