Given:import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
byte[] data = { 65, -1, 66 };
InputStream in = new ByteArrayInputStream(data);
int b;
while ((b = in.read()) != -1) {
System.out.print(b + " ");
}
}
}What is the result?
Choose one.
InputStream.read() returns the next byte as an int in the range 0 to 255, or -1 at end of stream.
The single-byte read() widens each byte to an unsigned value. That is exactly why it returns int and not byte: the extra range leaves -1 free to mean end of stream. The stored byte -1 (0xFF) is returned as 255, which is not equal to -1, so the loop continues and reads 66 as well. Only after the third byte does read() return -1. A candidate who thinks read() returns the signed byte value stops after 65 or prints -1.
- read() returns int, not byte.
- Data bytes are returned as 0 to 255; -1 means end of stream only.
- The byte -1 is therefore returned as 255 and the loop goes on.
- Each value is printed as a number followed by a space.
Exam tip: read() returns 0-255 for data and -1 only at end of stream; never store its result in a byte before comparing with -1.
Java I/O Streams: Console and File Readers, Writers and Streams (1Z0-831) — the lesson that teaches this.