Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The write() method defined in java.io.OutputStream takes an integer argument of type int intended to be between 0 and 255. Because an int is designed to store 4 byte numbersa value of type int may well be outside of this range, failure to range check may lead to truncation of the higher order bits of the input.

...

The noncompliant code example accepts a value from the user without validating it. Any value with greater more than eight bits set is truncated. For instance, write(303) prints / because the lower order bits of 303 are preserved while the top 24 order bits are lost (303 mod 256 is 47 and / has ASCII code 47). That is, the result is remainder modulo 256 of the absolute value of the input.

...

Alternatively, perform range checking to be compliant. While this particular solution still does not display the original invalid integer correctly, it behaves well when the corresponding read() method is used to convert the byte back to an integera value of type int. This is because it guarantees that the byte will contain representable data.

...