Search code examples
javastreaminputstream

How is one byte read and returned as an int by read function in InputStream in java?


The read() function reads one byte at a time and the return type of this function is int. I want to know what happens under the hood so that byte is returned as an int. I have no knowledge of bitwise operators so can anyone answer in a way that i grasp it readily.


Solution

  • Under the hood, if the end of stream is reached, read() returns -1. Otherwise, it returns the byte value as an int (the value is thus between 0 and 255).

    After you've verified that the result is not -1, you can get the signed byte value using

    byte b = (byte) intValue;
    

    That will just keep the 8 rightmost bits of the int, and the 8th bit from the right is used as the sign bit, thus leading to a signed value, between -128 and 127.

    If the method returned a byte, there would be no way, other than throwing an exception, to signal that the end of the stream has been reached.