question about the return type of the method read() of the InputStream class
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   yang_shuai
Posted On:   Thursday, December 13, 2007 03:06 PM

i saw the following text in the sun's java tutorial Notice that read() returns an int value. If the input is a stream of bytes, why doesn't read() return a byte value? Using a int as a return type allows read() to use -1 to indicate that it has reached the end of the stream. now, i have a question that, if the return type is byte, -1 is also include in the byte value range -128 to 127, why must use int to achieve this? and, there is a book from oreilly Java™ I/O, 2nd Edition By Elliotte Rusty Harold ............................................... Publisher: O'Reilly Pub Date: May 2006 Print ISBN-10: 0-596-52750-0 Print ISBN-13: 978-0-59-652750-1    More>>

i saw the following text in the sun's java tutorial

			
Notice that read() returns an int value. If the input is a stream of bytes, why doesn't read() return a byte value? Using a int as a return type allows read() to use -1 to indicate that it has reached the end of the stream.

now, i have a question that, if the return type is byte, -1 is also include in the byte value range -128 to 127, why must use int to achieve this?

and, there is a book from oreilly
			
Java™ I/O, 2nd Edition
By Elliotte Rusty Harold
...............................................
Publisher: O'Reilly
Pub Date: May 2006
Print ISBN-10: 0-596-52750-0
Print ISBN-13: 978-0-59-652750-1


in the book, the author said that:

			
The fundamental method of the InputStream class is read( ). This method reads a single unsigned byte of data and returns the integer value of the unsigned byte. This is a number between 0 and 255:

public abstract int read( ) throws IOException


i think this explanation is right, what do you think???
Great thanks!    <<Less

Re: question about the return type of the method read() of the InputStream class

Posted By:   Robert_Lybarger  
Posted On:   Thursday, December 13, 2007 09:33 PM

What's the problem exactly? It returns the value of an unsigned byte (0-255) or returns -1. You can't very well distinguish between 255 and -1 using only 8 bits. Thus you need 16 bits. So the return type is integer. Provided the value is not -1, cast the return type down to a (byte).
About | Sitemap | Contact