Jim
Jim

Reputation: 231

What result should I expect when casting an over-sized int literal to a byte variable?

Please explain the expected behavior when casting from int literal, which is out of range of a byte java primitive type.

public static void main(String[] args) {

    byte a1 = 30 ; // int literal within valid range
    System.out.println(a1); // 30
    
    byte b1 = (byte) 128; // needs a cast as soon as the int literal exceeds the maximum value.
   System.out.println(b1); // -128 (Why?)
    
    byte b2 = (byte) 129;        
    System.out.println(b2); // -127 (Why?)
    
    byte b3 = (byte) 1292;        
    System.out.println(b3); // 12 (Why?)

    byte b4 = (byte) 1293;        
    System.out.println(b4); // 13 (Why?)

}

Upvotes: 0

Views: 61

Answers (1)

glglgl
glglgl

Reputation: 91017

The bitwise representation of the respective values are truncated so that they fit into a byte.

E. g.:

  • 128 = 10000000 in binary, but as signed bytes, the 1 means the value is negative and that 256 must be substracted from the unsigned value. 128 - 256 = -128.
  • 129 = 10000001 = 129 - 256 = -127, for the same reason.
  • 1292 = (101)00001100 = 12 (the leading 101 is removed, which is equivalent to substracting 1280 = 1024 + 256)
  • 1293 = (101)00001101 = 13 (the same)

Upvotes: 1

Related Questions