I just observed a small error in K&B SCJP 6.0 in "Operators" chapter. The question 9 in the self test is incorrectly explained in the answer section. The question is as follows:
Given:
3. public class Spock{
4. public static void main(String args[]){
Which two answers are true about the value of mask and value of count?
A. mask is 0
B mask is 1
C mask is 2
D mask is 10
E mask is greater than 10
F count is 0
G count is greater than 0
The correct answer is "mask is 1 and count is 1";
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
In the answer's explanation, it is said that the non-short-circuit OR "|" allows the mask to be incremented which is conflicting. The short-circuit operator on that line makes the compiler not bother the right side of the equation. So effectively mask value is "1" after the line 7 is complete.
On line line 9, the left side of the && operator, !(mask>1) evaluates to true but right side value, ++count > 1 executes and evaluates to false and hence the "if" condition will not pass.
Thus finally the mask and count values are both "1".
Hi Harsha,
What I know is if left hand side of short circuit operator evaluates to true when short circuit OR is used or false when short circuit && is used then no evaluation of right hand side of short circuit operator occurs.
See the Java Language Specification for details.
Some words are included to clear the meaning due to this reason message edited.
This message was edited 1 time. Last update was at by Ninad Kulkarni
You have missed one set of '( )' in line 7 before '(5 <' & after '<10)', which makes all the difference. May be this is causing you confusion. You put the parenthesis there, and answer will correct according to K&B.
It should be:
if ( ( (5<7) || (++count<10) ) | mask++ < 10)
This message was edited 3 times. Last update was at by Madhu Desai
Thanks
Preparing for SCJP 6
harsha balluru
Greenhorn
Joined: Feb 06, 2009
Posts: 14
posted
0
Hi Madhu
Thanks for the clarification. As you quoted, the parantheses made the difference there. With that in place, K&B's explanation is correct...
João Martinho
Greenhorn
Joined: Aug 26, 2009
Posts: 12
posted
0
Sorry for bringing back to life this topic but i have a doubt on it.
the book also says:
At line 8 the ^ returns true only if exactly one operand is true.
but:
6>8 -> true
false -> false
So:
if(true ^ false) -> is true, after all only one operand is true or am i reading something wrong?