What will be the result of compilation and execution of the following code:

import java.io.*;
public class QTest {
	public static void main(String[] args) throws IOException {
		byte[] bytes = new byte[] { -1, 1, 0x0 };
		InputStream in = new ByteArrayInputStream(bytes);
		System.out.println(in.read() + in.read() + in.read());
	}
}
Explanation
Method read() reads one byte from the array bytes, which was passed to the constructor of ByteArrayInputStream, but the value that was read is returned as int. Type byte in Java is represented with 8 bits, and type int - with 32 bits, therefore 24 high zero-bits are added to the value. Byte with value -1 is represented as 11111111, and it becomes 255 (decimal, int) after reading from the InputStream. Therefore, the result will be 256 (255 + 1 + 0).
It is how InputStream.read() works:
Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes