-1
public class Test{
    public static void main(String[] args) {    
        byte i = 31;
        System.out.println(i<<3);
    } 
}

Why does this code print 248,not -8?

2 Answers2

0

The output is 256 and it is ok! You shift left it for 3. i is 32, it means 100000 as binary so if you shift left it for 3, it will be 100000000 that means 256 as dec.

Majva
  • 88
  • 1
  • 5
0

After you now edited your question:

byte b = 31 is 0b11111. If you now do i << 3 this turns to 0b11111000.

Which is 248.

You are expecting -8 which would be the result of (byte) (i << 3). The result of a bitshift is an integer. You can convert that explicitely to a byte if you want a byte-value.

Ben
  • 1,665
  • 1
  • 11
  • 22
  • Thank you very much! I did not know the result of a bitshift is an integer –  Bean Jelly May 15 '18 at 15:24
  • 1
    See [JLS 4.2.2](https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.2.2) "The numerical operators, which result in a value of type int or long" - **all** numeric operators promote byte, short or char to int (or long, in some circumstances). Including bitshift operators. – Erwin Bolwidt May 16 '18 at 13:31