Why does InputStream#read() return an int and not a byte?

JavaInputstream

Java Problem Overview


Why does InputStream#read() return an int and not a byte?

Java Solutions


Solution 1 - Java

Because a byte can only hold -128 until 127, while it should return 0 until 255 (and -1 when there's no byte left (i.e. EOF)). Even if it returned byte, there would be no room to represent EOF.

A more interesting question is why it doesn't return short.

Solution 2 - Java

It returns an int because when the stream can no longer be read, it returns -1.

If it returned a byte, then -1 could not be returned to indicate a lack of input because -1 is a valid byte. In addition, you could not return value above 127 or below -128 because Java only handles signed bytes.

Many times when one is reading a file, you want the unsigned bytes for your processing code. To get values between 128 and 255 you could use a short, but by using an int you will align the memory registers with your data bus more efficiently. As a result, you don't really lose any information by using an int, and you probably gain a bit of performance. The only downside is the cost of the memory, but odds are you won't be hanging on to that int for long (as you will process it and turn it into a char or byte[]).

Solution 3 - Java

So it can return "-1" . It must do that when there is no more bytes to read.

You can't have it return a byte sometimes AND -1 for EOF/nobyte/whatever, so it returns an int ;)

Solution 4 - Java

as the Java doc says in InputStream#read, The value byte is returned as an int in the range 0 to 255. That is to say the byte value[-128127] has been changed to int value[0255], so the return value can be used to represent the end of the stream.

Solution 5 - Java

Because EOF (end of file or generally end of data) can't be represented using char.

Solution 6 - Java

Appending to BalusC answer:

  • not a byte to allow [0; 255] as main capacity and additionaly -1 as EOF result
  • int is used to adjust result to machine word (one of the main requirements to I/O operations - velocity, so they should work as fast as possible!)

Exception is not used because they are significantly slow!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser489041View Question on Stackoverflow
Solution 1 - JavaBalusCView Answer on Stackoverflow
Solution 2 - JavaEdwin BuckView Answer on Stackoverflow
Solution 3 - JavaNanneView Answer on Stackoverflow
Solution 4 - JavaandyView Answer on Stackoverflow
Solution 5 - JavawesolyView Answer on Stackoverflow
Solution 6 - JavaradistaoView Answer on Stackoverflow