Before answering the question itself, it is important to mention that this byte b = 5
statement is not changing the result at all. It could have been done directly byte b = (byte)i
.
On the result, you need to understand the types involved in the question, especially the type byte
.
In Java, the type byte
has a signal and has a size of 1 byte, therefore, 8 bits. Using 8 bits it is possible to map 256 characters, in this case, integers. Since the variable has a signal, then the range goes from [-128,127].
That said, if the integer you are casting to byte
is in this range, then it will print correctly, if it is not, an overflow will occur in the byte
variable and what will be printed will be a number in that range, but not the int
for which you are casting.
See this: link
Update
The question has been changed in a meaningful way which made me edit the answer.
The result was not 10
as previously mentioned, but 20
, since a sum of b+=i
is made after the cast . However, this does not change the explanation, since 20 is a number that is in the range of byte
in Java.