Core Java: Narrowing a cast from int to byte keeps only the low 8 bits

Casting an int to byte discards everything above the lowest 8 bits, so the result depends only on those bits and can flip sign.

Code
int i = 300;
byte b = (byte) i;
int j = -1;
byte b2 = (byte) j;
System.out.println("300 in binary: " + Integer.toBinaryString(i));
System.out.println("(byte) 300 = " + b);
System.out.println("(byte) -1 = " + b2);
Output
300 in binary: 100101100
(byte) 300 = 44
(byte) -1 = -1
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms