One thing I don’t get about InputStream
s and OutputStream
s is this. Why do you need to cast those returned int
s into byte
s to get their real values? Aren’t those higher bits going to be zeros (as long as the byte capacity is not exceeded)?
Because when you read or write bytes from a file using an input or output stream in Java, you get back an integer representing the byte value. However, you need to cast this integer value to a byte before using it, because Java treats bytes as 8-bit signed values ranging from -128 to 127. When you cast the integer value to a byte, Java only takes the lowest 8 bits and throws away the rest. This ensures that the byte value you get is within the correct range of -128 to 127, even if the higher-order bits are not zero.
But I need to cast even small integers, don’t I? Why is, say, ten not the same before and after casting it to byte
?
When you read or write bytes from a file in Java, you get back an integer representing the byte value. However, bytes in Java are treated as 8-bit signed values, meaning they can only hold values in the range of -128 to 127.
So, when you cast the integer value to a byte, Java only takes the lowest 8 bits and discards the rest. This ensures that the resulting byte value is within the correct range.
However, if the integer value you’re casting is outside of the range that can be represented by a byte, you’ll lose some of the original value when you cast it. Therefore, you need to cast the integer value to a byte to make sure it’s within the correct range and to avoid any loss of precision.
if the integer value you’re casting is outside of the range
My question related to what if it’s not? It seems there’s no need for casting, but I still have to cast, don’t I?