Course contentsShow
← Java
Lesson 1907 of 2,87039. File I/O: Basic Byte StreamsFree lesson

The write(int) Method: Writing a Single Byte

How write(int) writes the low-order byte of the int argument to the output stream.

The write(int) Method: Writing a Single Byte

What you'll learn: How the write(int) method writes only the lowest 8 bits of an integer to an output stream, ignoring the rest.

Understanding write(int)

When you call write(int) on an OutputStream, you might expect it to write all four bytes of the integer. Surprisingly, it only writes the low-order byte (the rightmost 8 bits) and discards the upper 24 bits.

Why an int Parameter?

Java uses int as the parameter type for convenience and historical reasons, but the method signature is:

public abstract void write(int b) throws IOException

Even though you pass an int (32 bits), only the bottom 8 bits are written to the stream.

How It Works

Think of it like a coin sorter that only accepts pennies. You might pour in a handful of mixed coins (your 32-bit int), but the sorter only processes the pennies (the low-order byte) and discards everything else.

For example:

  • write(65) writes the byte 65 (ASCII 'A')
  • write(321) writes the byte 65 (because 321 & 0xFF = 65)
  • write(0x12345678) writes the byte 0x78 (120 in decimal)

The conversion happens automatically: (byte)(value & 0xFF)

Practical Implication

When writing a single byte, values 0–255 work intuitively. Values outside this range wrap around due to the masking behavior, so always ensure you're passing appropriate byte values when precision matters.

Key Takeaway: The write(int) method writes only the low-order byte (least significant 8 bits) of the int argument to the output stream, silently discarding the upper 24 bits.