Writing Java Streams - Quiz Explanation

The correct answers are indicated below, along with text that explains the correct answers.
 
1. What data type does the write() method return?
Please select the best answer.
  A. byte
  B. int
  C. long
  D. void
  The correct answer is D. The write() method takes an int as an argument, and it actually truncates the int to a byte, but it returns void. If the data fails to be written, then an IOException is thrown. No error value is returned.


2. When should you explicitly flush an output stream?
Please select the best answer.
  A. Whenever you need to make sure data is sent before you're through with the stream
  B. Never, because all output streams automatically flush whenever a new line in written
  C. Always
  D. Whenever you've used the output stream for a very short time
  The correct answer is A. System.out, System.err, and some (but not all) other print streams automatically flush after each call to println() and after each time a newline character ('\n') appears in the string being written. If you only use a stream for a short time, you don't need to flush it explicitly. It will be flushed when you call the close() method.

3. The maximum number of bytes that can be written with one method call is:
Please select the best answer.
  A. 32,767
  B. 2,147,483,647
  C. 2,147,483,648
  D. 4,294,967,294
  The correct answer is C. Two variants of write() take arrays of bytes as arguments.
Arrays are indexed with signed, nonnegative ints. The largest number of bytes an array can have, and thus the largest number of bytes that can be written with one method call is the number of non-negative ints. Because of 0, this is one more than the largest int, or 2,147,483,648.
This limit is more theoretical than practical. Very few systems can create 2GB arrays without choking, but this is likely to become more plausible in the future (say around the year 2000) as memory prices continue to fall, RAM densities increase, and 64-bit CPUs become commonplace.


4. What does the following line of code print?
System.out.write(65 + 256);

Please select the best answer.
  A. 65
  B. 321
  C. 65256
  D. A
  The correct answer is D. Since System.out interprets all numbers as ASCII characters, answers A and B are ruled out.
C is incorrect because 65 and 256 are ints, and 65 + 256 is 321. The result of "65" + "256" would be "65256". The numeric value 321 is a capital L with a stroke in Unicode, but print streams like System.out don't use Unicode. They truncate all values to ISO Latin-1. Thus 321 is reduced modulo 256 back to 65, which is the ASCII capital letter A.