Why does InputStream#read() return an int and not a byte?
Why does InputStream#read()
return an int
and not a byte
?
Solution 1:
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:
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:
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:
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[-128~127] has been changed to int value[0~255], so the return value can be used to represent the end of the stream.