Why does the read() in FileInputStream return an integer?

GrowinMan picture GrowinMan · Apr 8, 2012 · Viewed 10k times · Source

This page shows says that it is so that the method can return -1 when it wants to indicate that there are no more bytes to be read.

But a byte ranges from -128 to 127, right? And wouldn't it make more sense for the return type of read() to be byte since it returns a byte?

Thank you for your time.

Answer

wattostudios picture wattostudios · Apr 8, 2012

The reason for it returning the value as an int is that it needs to return a value between 0-255, as well as being able to indicate when there is no more bytes to read from the file. By using an int, you can return the full range of positive unsigned values 0-255, as well as indicate when the file is complete. It wouldn't be able to provide this with only the 256 distinct values of a byte value, half of which are negative by Java default.