Before answering the question itself, it is important to mention that this instruction byte b = 5
is not changing the result at all. It could have been done directly byte b = (byte)i
.
About the result, it is necessary to understand the types involved in the question, especially the type byte
.
In Java, the type byte
has signal size and 1 byte, therefore 8 bits. Using 8 bits it is possible to map 256 characters, in this case, integers. Since the variable has signal, then the interval goes from [-128,127].
That said, if the whole you’re doing cast for byte
is in this range, then it will be printed correctly, if it is not, an overflow will occur in the type variable byte
and what will be printed will be a number in that interval, but not the int
to which you are doing cast.
Look at this: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Updating
The question was significantly changed which made me edit the answer.
The result was not 10
as mentioned earlier, but 20
, since a sum of b+=i
after the cast. However, this does not change the explanation, since 20 is a number that is in the range of one byte
in Java.
Questão 127 do concurso
, coincidentally, the maximum possible value to store in the byte :D– Math
@Bia, I updated my answer based on the issue you asked the question.
– cantoni
@Bia what does this "judge" mean? Is it to say what you think of each statement? It is to say if she is wrong?
– Maniero
@bigown judge whether the statement is correct or not.
– Bia