Writing Single Bytes with write()
What you'll learn: How OutputStream.write(int) extracts and writes only the lowest 8 bits of an integer, ignoring the rest.
The Core Idea
When you call write(int) on an OutputStream, you might expect it to write the entire integer (4 bytes). Surprisingly, it doesn't! The method accepts an int parameter (32 bits) but only writes the lowest-order byte — the rightmost 8 bits — to the output stream. The upper 24 bits are completely ignored.
Think of it like a toll booth with a narrow gate: even if you arrive in a massive 18-wheeler truck (the full 32-bit int), only a motorcycle (the last 8 bits) can actually fit through.
Why an int Parameter?
Java uses int instead of byte for historical reasons and convenience. It allows you to pass literal numbers like 65 directly without casting. The method signature is:
void write(int b) throws IOException
When you write:
FileOutputStream fos = new FileOutputStream("output.bin");
fos.write(65); // Writes the byte value 65 (ASCII 'A')
Only the byte 65 is written to the file. If you wrote write(321), which in binary is 0000 0001 0100 0001, only the last 8 bits (0100 0001 = 65) would be written.
Practical Implications
This behavior means you can write values from 0–255 meaningfully. Anything outside that range gets truncated:
fos.write(255); // Writes byte 255
fos.write(256); // Writes byte 0 (256 wraps around)
fos.write(-1); // Writes byte 255 (common end-of-stream marker when reading)
Key Takeaway: OutputStream.write(int) writes only the low-order 8 bits of the integer parameter, discarding the upper 24 bits — allowing values 0–255 to be written as single bytes.