Course contentsShow
← Java
Lesson 80 of 2,8702. Variables and Primitive TypesFree lesson

Truncation in Integer Narrowing Casts

See how casting from long to int or int to byte truncates high-order bits, causing unexpected values.

Truncation in Integer Narrowing Casts

What you'll learn: How narrowing casts from larger integer types to smaller ones can chop off data and produce surprising results.

When you explicitly cast a larger integer type (like long or int) down to a smaller type (like int or byte), Java doesn't scale the value—it truncates it by discarding the high-order bits that don't fit.

How Truncation Works

Think of it like pouring water from a large bucket into a small cup. If the bucket holds more than the cup can contain, the excess simply spills over and is lost. Similarly, if a long value is too large for an int, the extra bits are discarded.

Java stores integers in binary. A long uses 64 bits, an int uses 32 bits, and a byte uses 8 bits. When you cast down, Java keeps only the low-order bits that fit in the target type and throws away the rest.

Example of Unexpected Behavior

long bigNumber = 300L;
byte smallNumber = (byte) bigNumber;
System.out.println(smallNumber);  // Prints 44, not 300!

Why 44? Because byte can only hold values from -128 to 127. The bits representing 300 don't fit in 8 bits, so only the lowest 8 bits are kept, resulting in 44.

int largeInt = 2147483647;  // Maximum int value
short cutOff = (short) largeInt;
System.out.println(cutOff);  // Prints -1, not 2147483647!

The cast doesn't fail or warn you—it silently produces a completely different value.

Why This Matters

Truncation is not an error—it's intentional behavior. Java trusts that you know what you're doing when you use an explicit cast. Always verify that your values fit within the target type's range before casting down.

Key Takeaway: Narrowing casts truncate by keeping only the low-order bits that fit, which can turn large values into unexpected, often negative, small values.