This week's giveaway is in the Android forum. We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line! See this thread for details.

What would be printed during execution of the following program?

Answer :"B" and "D" I cannot understand how do we get such an output. Can anyone clear this part? Can any one tell me any good tutorial for shifts, I am still not able to understand the shift operators << >>> >> etc. I referred RHE, and many other notes..Still Unclear!!!.. Any Small, Short and Sweet tutorial for this part? Sonir

Originally posted by sonir shah: [QB]What would be printed during execution of the following program?

Answer :"B" and "D" I cannot understand how do we get such an output. Can anyone clear this part? shiftTest(1, "A" ) ; In this case when shiftTest method is invoked what happens is 1>>1 != 1>>>1 Here 1 is >> by 1. so the answer is 0 .EVen the same for 1 >>>1 . 1==1. so the if statement will be false and the system.out.println never execute in second case(1<<31,"B") 1<<31 => -2147483648 within method -2147483648>>1 != -2147483648>>>1 this will give -1073741824 != 1073741824 Hence B is printed In third case 1<<30,"C" 1073741824>>1 != 1073741824>>>1 Both are equal so C won't be printed Case 4 -1,"D" -1>>1 != -1>>>1 -1 != give some +ve answer. So D will be printed.

The *best* way to learn about something is to do it yourself until you understand it. Write a lot of little simple programs involving shift operations in various scenarios. Try to predict what the results will be, then run your program and see what you get. When you can correctly predict the outcome everytime, you know you understand it!! The key to understanding this example is the test in shitTest()

This test is asking does the result of i>>1 differ from i>>>1?. Both of these operations are right shifts. The first is sign extended (>> ) , the second is unsigned. You just have to memorize the fact that an unsigned shift (>>> ) shifts in zeros into the high order bit, and a signed shift (>> ) shifts in whatever was at the high byte before the shift. simple example: 2 >> 1 = ? Look at the bits: 0010 >> 1 = 0001 (we shifted all the bits RIGHT by one ) now this: 0010 >>> 1 = 0001 In this case, signed right shift and signed left shift both look the same, don't they? They do, because in both cases the high-order bit was zero. Now let's look at the same example for a negative number: 1000 >> 1 = 1100 //high-order bit same as original 1000 >>> 1 = 0100 //zero always shifted in. Now we see a difference in the two when the number we are shifting is negative. The first result is -4, the second result is positive 4. Just remember that the signed right shift (>> ) always preserves the sign of the original number by shifting in the same high-order bit as it had previously. The unsigned right shift (>>> ) *always* shifts in a zero. Rob [ January 17, 2002: Message edited by: Rob Ross ]