Example 1 — Narrow Numbers to byte
Convert a mix of small and large values and see which ones survive.
public class IntegerByteValueDemo {
public static void main(String[] args) {
Integer[] numbers = {100, 127, 128, 200, 255, 256, -129};
for (Integer number : numbers) {
System.out.println(number + " -> " + number.byteValue());
}
}
} How It Works
- In range stays the same. 100 and 127 fit in a
byte, so they come back unchanged. - One past the top. 128 needs a ninth bit, so it wraps to -128.
- 200 and 255. 200 minus 256 gives -56, and 255 minus 256 gives -1, because bit 7 is set and read as the sign.
- 256 and -129. 256 has no bits in the low 8 positions, so it gives 0, and -129 wraps the other way to 127.

