Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Output stream: int read() AND write(int)! Why int?  RSS feed

 
Captain Cooper
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It may sound very dumb ... asking such a basic question. Anyway, I'm really curious to know if someone could please share w/ me ... why do one of the read()/write() methods deal w/ int while working w/ "byte" in OutputStream?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, it's a good question, I think. For InputStream there's the fact that we need to be able to return a special value to indicate an end of stream. So all possible byte vaues are mapped to the 0-255 range, and -1 is used to indicate end of stream - meaning we need more than 256 values, and the return type needs to be larger than byte. And the same situation for a Reader means that the return type for read() needs to be larger than short. It seems that int is the logical candidate for both - Java was written with the assumption that the natural word length on any machine it runs on, would be at least 4 bytes - so there's no performance difference in using an int where only a short or byte was needed. As for OutputStream and Writer though, I don't see any good reason why their write() methods should expect ints. Maybe it's just for consistency with the read() methods. Maybe it's because int operands are so common, that they didn't want to force an explicit cast whenever write(x) is used. But that seems a weak reason to me. It would be better if users were forced to write the cst, so they'd realize that bits could be lost in the operation. Perhaps someone else knows a better answer...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!