-2

I am new to Java. So, I want to understand the working behind it.

int one_int = 1; 
byte one = 1;
one <<= 7;
one_int <<= 7;
System.out.println(one_int); //Output is 128 
System.out.println(one); //Output is -128

Why the output of left shift on int is 128 and on byte is -128?

  • 2
    first bit of byte is sign bit. so , 1000 0000 => -128 , but 8th bit of integer is just a part of integer. like, 0000 0000 0000 0000 0000 0000 1000 000. so, integer sign bit is different with byte's one from looking right – Adem Oct 02 '16 at 10:59
  • Possible duplicate of [How do shift operators work in Java?](http://stackoverflow.com/questions/10910913/how-do-shift-operators-work-in-java) – vatsal mevada Oct 02 '16 at 11:01
  • @vatsalmevada I don't think this is a good duplicate, because it does not address the sign bit specifically. – Sergey Kalinichenko Oct 02 '16 at 11:03
  • `(byte) 128 == -128` – Peter Lawrey Oct 02 '16 at 11:13

2 Answers2

3

In java

  • int consist 32 bits
  • byte consist 8 bits

When you shift the byte 7 times left:

00000001 -> 10000000

When you shift the int 7 times left:

00000000000000000000000000000001 -> 00000000000000000000000010000000

Because they are both used in order to present signed and unsigned number, we use the Two's complement operation.

this means that the first bit (MSB) represents the sign of the number (0 for +, 1 for -).

Erik
  • 221
  • 1
  • 7
0

Both shift operations produce the same binary value of 100000002. The difference is in interpretation of that value's most significant bit.

The most significant bit of a signed integer number determines if the number is positive (zero) or negative (one).

  • int is a 32-bit type, so its most significant bit is zero, hence 100000002 is interpreted as a positive 128
  • 'byte' is an 8-bit type, so its most significant bit is one, hence 100000002 is interpreted as a negative -128
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • @VishalSharma You are welcome. If this answers your question, please consider accepting one of the answers by clicking the check mark next to it. – Sergey Kalinichenko Oct 02 '16 at 15:24