Knowing byte and int
byte: The byte
data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).
int: By default, the int
data type is a 32-bit signed two's complement integer, which has a minimum value of -2³¹ and a maximum value of 2³¹-1
Reference: docs.oracle.com
I have a question. Why is this code generating an error?
a,b,c and d are all in the range of byte. I have not declared int anywhere in my code. Then why?
50*40 is 2000 which exceeds the range of byte, is it possible that 2000 which is the intermediate expression is converted automatically to an int and then the rest of the operations take place? Yes, this is what has happened. But what if I take a = 5 and b = 4, there still will be the same error although 5*4 = 20 is in the range of byte. This is because we don’t know if an expression might cross the range of byte as in the first case. To solve this problem Java automatically promotes every byte, short or char operand to int when evaluating an expression. And thus 50*40 is legal but in order to run this code we need to cast the int type back to byte.
But how is this integer (which has range more than byte data type) converted to byte again when we typecast it? As an example, take the number 257, it’s an integer and I have explicitly added a typecast to an integer. The following is the code and output
As we can see 257 now becomes 1. This is what happens.
When we cast it to byte, 24 bits are truncated and those 8 bits including LSB make the byte.
Here’s one more,
Consider the following code
First question. Why is byte typecasting explicitly required in the first assignment but while short hand operator, there is no explicit mention?That is because short hand operator converts the final result in to the type of first operand.
e*=2 meaning e=e*2. Here the first operand is of type byte, thus the final result will automatically be of that type.
Second question. Why -56 in second case?
Well first case is clear, since 100 comes in the range of byte, so the output. In second case we have 200 which is out of range of byte. But we need the final result as a byte value.
200 in Binary : 11001000
If byte would not have been a signed data type, the answer would be 200 itself as in that case 200 would come in range of byte and no truncating of bits would have taken place as it is represented by 8 bits only. But now what happened is byte being signed the MSB is sign bit and is which means the number is negative. Thus we find it’s 2’s complement and add 1 to it. We get 00111000 which when converted to decimal by adding a negative sign is -56.
Thank you for reading :)