user489041
user489041

Reputation: 28304

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

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

Upvotes: 60

Views: 14631

Answers (6)

Edwin Buck
Edwin Buck

Reputation: 70909

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[]).

Upvotes: 21

radistao
radistao

Reputation: 15504

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!

Upvotes: 0

andy
andy

Reputation: 4281

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.

Upvotes: 3

BalusC
BalusC

Reputation: 1108722

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.

Upvotes: 75

Nanne
Nanne

Reputation: 64399

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 ;)

Upvotes: 5

wesoly
wesoly

Reputation: 552

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

Upvotes: 2

Related Questions