Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Q#5 majji. Can any one explain this please??

Kuljit Singh
Greenhorn
Posts: 5
What is the output and why is so?
1: int i = 1;
2: i <<= 31;<br /> 3: i >>= 31;
4: i >>= 1;
5:
6: int j = 1;
7: j <<= 31;<br /> 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 = -1

------------------

anil bisht
Ranch Hand
Posts: 81
the answer is d -1 and -1..
try to print the value in the binary form
int i = 1;
System.out.println("initial i = " +i );
System.out.println("initail binary = " +Integer.toBinaryString(i));
i <<= 31;<br /> System.out.println("left shift by 31 i = " +i );<br /> System.out.println("left shift by 31 binary = " +Integer.toBinaryString(i));<br /> <br /> i >>= 31;
System.out.println("right shift by 31 i = " +i );
System.out.println("right shift by 31 binary = " +Integer.toBinaryString(i));
i >>= 1;
System.out.println("right shift by 1 i = " +i );
System.out.println("right shift by 1 binary = " +Integer.toBinaryString(i));
and see the values u get
here first u are doing the left shift so its ok.. here u get the MSB( 32nd bit) as 1 and rest as zero so u get the negetive value for i..
and as int is signed int so this number becomes nevgetive
now u are doing the signed right shift 31 bit. It says shift the bits to the right and fill left shifted bit with the value of bit in the MSB. As ur MSB is 1 so all the shifted bits are replaced by 1 Thus the the sign of the number dosent change.
Thats why its called signed right shift
u also try with the unsigned right shift (>>>). and see the answer
HTH
anil

sunilkumar ssuparasmul
Ranch Hand
Posts: 142
hai majji,
i guess this would be the case.
ans d ie i=-1, j=-1.
1. IF u shift 31 times 1 what u get is 10000000 00000000 00000000 00000000. when u tried 2 print it out ,since integer is signed and last bit is 1 it interprets 2 be a negative number and prints the value after taking 2,s complement of the number genertaed as indicated above.
2. when reverse shift occurs the sign bit is retained . so u get -1 again.
3. when u right shift -1 it is always -1 breaking the rule that shifting right divides the number by 2.it is only for negative numbers especially this case.
4. 1 and 2 holds good for j.
IF i am wrong some body plz correct
thanks
S.SUnil