Jin
Jin

Reputation: 165

end of stream in JAVA

I am confused by the following statement that appears here

The basic read() method of the InputStream class reads a single unsigned byte of data and returns the int value of the unsigned byte. This is a number between 0 and 255. If the end of stream is encountered, it returns -1 instead; and you can use this as a flag to watch for the end of stream.

Since one byte can represent up to 256 integers, I fail to see how it can represent 0 to 256 and -1. Can someone please comment on what I am missing here?

Upvotes: 3

Views: 1094

Answers (3)

utopianheaven
utopianheaven

Reputation: 1277

The return type of InputStream#read() is an int, where the value can be read as a byte if it falls in the range of 0-255.

Upvotes: 3

aaazalea
aaazalea

Reputation: 7930

It returns an int, not a byte, so though it normally will only contain 0-255, it can contain other values.

Upvotes: 3

Jack
Jack

Reputation: 133629

Although the read() operation just reads a byte it actually returns an int so there is no problem.

Just values in range 0-255 are returned though, aside from the special -1 end of stream value.

Upvotes: 3

Related Questions