Reputation: 231
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
Reputation: 91017
The bitwise representation of the respective values are truncated so that they fit into a byte
.
E. g.:
Upvotes: 1