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
You've got a point here , on a serious note, it seems an honest mistake that's all so no offenses...
SCJP 6.0 98%, SCWCD 5 98%, Javaranch SCJP FAQ, SCWCD Links The hardest moment is not when you lose someone and tears come out of your eyes, but its when you lose someone and still you have to manage a smile!