What is the result that will be printed out here ? int i = - 128; System.out.println((byte)i << 1);
answer is -256 ..please explain how to calculate the same...
Jay Pawar
Ranch Hand
Joined: Aug 27, 2004
Posts: 411
posted
0
Originally posted by pravin kumar: What is the result that will be printed out here ? int i = - 128; System.out.println((byte)i << 1);
answer is -256 ..please explain how to calculate the same...
-128 is represented as 1111 1111 1111 1111 1111 1111 1000 0000
when you perform (byte)i << 1 last 8 bits of i are considered which are 1000 0000 and then left shift operation is carried out. Now point to be noted here is whenever a bit operation is performed the number is represented as int (32 bit) so -128 is represented as 1111 1111 1111 1111 1111 1111 1000 0000 and then when you left shift by 1 you get 1111 1111 1111 1111 1111 1111 0000 0000 which is -256
There would be big difference in the answer if you try to print this System.out.println((byte)(i<<1));
Hope that helps [ December 10, 2005: Message edited by: Jay Pawar ]
Cheers,<br />Jay<br /> <br />(SCJP 1.4)<br />Heights of great men were not achieved in one day, they were toiling day and night while their companions slept.
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.