When is an int not a byte?

A nice little surprise waiting for you in ByteArrayOutputStream.write(int byte)

I was recently working with a ByteArrayOutputStream and noticed a bug in some code that used the following:

public void write(int b)
  Writes the specified byte to this byte array output stream.
  b - the byte to be written.

As you can see although the method expects a byte it accepts an int. In other words as long as our int is between -128 and 127 we’ll get the expected behaviour:

final ByteArrayOutputStream boas = new ByteArrayOutputStream();
boas.write(-128);
boas.write(127);
final byte[] bytes = boas.toByteArray();
// bytes contains { -128 and 127 }

But there is nothing to stop us doing this and getting potentially `unexpected` results:

final ByteArrayOutputStream boas = new ByteArrayOutputStream();
boas.write(-256);
boas.write(999);
final byte[] bytes = boas.toByteArray();
// bytes contains { 0 and -25 }

One to watch out for!

Show your support

Clapping shows how much you appreciated Richard Cole’s story.