This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes I/O and Streams and the fly likes Why read() method of FileInputStream returns int instead of byte? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Why read() method of FileInputStream returns int instead of byte?" Watch "Why read() method of FileInputStream returns int instead of byte?" New topic
Author

Why read() method of FileInputStream returns int instead of byte?

Suresh Rachuru
Greenhorn

Joined: Nov 26, 2011
Posts: 3
Hi All,

Oracle documentation (http://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html) says "Using a int as a return type allows read() to use -1 to indicate that it has reached the end of the stream."

My doubt is why can't be return type is 'byte' as it can hold value -1 ? Any clarification is appreciated. Thanks
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4339
    
    7

The method needs to be able to read a byte of data (256 possible values) or indicate there are no more values. So it needs to return 257 possibilities. A byte can only hold 256. If it returned a byte, how do you tell the difference between reading a -1 from the file and reaching the end of the stream?
 
Don't get me started about those stupid light bulbs.
 
subject: Why read() method of FileInputStream returns int instead of byte?
 
Similar Threads
Why does FileInputStream's read() method return integer?
byte to int??
What's wrong with the program?
IO
RANDOMACCESSFILE