Hi, Can somebody please explain me the output of the following question- class MyClass{ public static void test(int i, String exp) { if((i>>1)!=(i>>>1)) System.out.println(exp); } public static void main(String[] args){ test(1<<32,"1<<32"); test(1<<31,"1<<31"); test(1<<30,"1<<30"); test(1,"1"); test(0,"0"); test(-1,"-1"); } } The given ouput is : 1<<31 and -1. thanx in advance Ira
Paul Anilprem
Enthuware Software Support
Ranch Hand
Joined: Sep 23, 2000
Posts: 2547
posted
0
This is actually quite simple. The point is, >> and >>> produce the same resule EXCEPT for the -ive integers. (And of course, if the RHS is not a multiple of 32/64) Here, only two are -ive 1 << 31 and -1! Hence, the answer.<br /> 1<< 31, puts 1 on the 32nd bit which is a sign bit making it -ive.<br /> I hope you know why >> and >>> produce different result for -ive integers. HTH, Paul.
------------------ Get Certified, Guaranteed! (Now Revised for the new Pattern) www.enthuware.com/jqplus [This message has been edited by Paul Anil (edited October 17, 2000).]
Paul is right, and just in case someone doesn't know why >> and >>> produce different answers for negative numbers, it is because >> looks at the highest bit value and that is what it adds to the beginning of the bit pattern, and >>> always adds 0's. Since negative numbers have a 1 at the highest bit value, they stay negative, while >>> doesn't. [This message has been edited by bill bozeman (edited October 17, 2000).]
Ira Jain
Ranch Hand
Joined: Sep 06, 2000
Posts: 70
posted
0
Thanks a lot Bill and Paul for clearing my doubts.