http://www.geocities.com/skmajji/Main.html question #5: The following code will print 1: int i = 1; 2: i <<= 31;<br /> 3: i >>= 31; 4: i >>= 1; 5: 6: int j = 1; 7: j >>= 31; 8: j >>= 31; 9: 10: System.out.println("i = " +i ); 11: System.out.println("j = " +j); A) i = 1 j = 1 B) i = -1 j = 1 C) i = 1 j = -1 D) i = -1 j = 0 why the answer is D? thanks in advance . I think i should be 0.
1: int i = 1; i is 1 2: i <<= 31; i is -1 (since the leftmost bit is 1)<br /> 3: i >>= 31; i is again 1 4: i >>= 1; i is -1, because the shift operation keeps the sign of the number (as opposed to >>>) Alex
int i = 1; i = "00000000000000000000000000000001" i<<=31; i = "10000000000000000000000000000000"<br /> i>>=31; i = "11111111111111111111111111111111" i>>=1; i = "11111111111111111111111111111111" so the result of i should be -1, (2's complement of 00000000000000000000000000000001 ) wei
I made a mistake in my earlier post. Wei's absolutely right. But the point is your confusion stems from the fact that >> operator inserts 0 or 1 as the leftmost bit depending on the sign of the operand (in this case negative, so it fills in with 1's). Alex
Rototillers convert rich soil into dirt. Please note that this tiny ad is not a rototiller:
Gift giving made easy with the permaculture playing cards