• Post Reply Bookmark Topic Watch Topic
  • New Topic

ByteStreams  RSS feed

 
meeta gaur
Ranch Hand
Posts: 305
Notepad Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Xanadu.txt
In Xanadu did Kubla Khan
A stately pleasure-dome decree:
Where Alph, the sacred river, ran
Through caverns measureless to man
Down to a sunless sea.



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.


Why can't byte use -1 to indicate reached the end of the stream ?
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The read() method needs to be able to return any possible byte value, which gives 256 different possibilities, normally in the range -128 to 127. The read method also needs to be able to indicate an end of file. That means it needs 257 different possible values, what can't possibly fit into a byte. So they use int instead. (They could have used short instead, but Java was written at a time when 32-bit processors were common, so they basically assumed int would be easiest for everyone). Anyway, they chose to let -1 indicate an end of file, and valid values in the range -128 to -1 got remapped to 128 to 255 instead. They could have done this differently I suppose, but they didn't. That's just the way it is.
 
meeta gaur
Ranch Hand
Posts: 305
Notepad Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Mike
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!