Redirecting from Big Moose Saloon -->> I/O and Streams 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?
Since so many arithmetic operations end up with int, it is more convenient to define the read and write that way. Only the lower 8 bits get used either way. Bill
Joined: Jul 14, 2001
Some1 suggested ... in the "I/O and Streams"
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...
subject: Redirecting Problem about Output stream: int read() AND write(int)! Why int?