Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 808
user489041 Avatar asked Jan 11 '11 16:01

user489041


People also ask

What is the purpose of InputStream?

Input Stream : If you are reading data from a file or any other source , stream used is input stream. In a simpler terms input stream acts as a channel to read data. Output Stream : If you want to read and process data from a source (file etc) you first need to save the data , the mean to store data is output stream .

Why does InputStream read return an int?

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.

Why do we need InputStream in Java?

InputStream , represents an ordered stream of bytes. In other words, you can read data from a Java InputStream as an ordered sequence of bytes. This is useful when reading data from a file, or received over the network.

How does InputStream work in Java?

Methods of InputStream read() - reads one byte of data from the input stream. read(byte[] array) - reads bytes from the stream and stores in the specified array. available() - returns the number of bytes available in the input stream. mark() - marks the position in the input stream up to which data has been read.


2 Answers

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.

like image 137
BalusC Avatar answered Oct 11 '22 12:10

BalusC


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

like image 31
Edwin Buck Avatar answered Oct 11 '22 14:10

Edwin Buck