Search code examples
javacoercion

Java byte to int Coercion


I have a question about the code below. The code is taken from my Programming Languages book.

byte x, y, z;
...
/* The values of y and z are coerced into int and int addition is performed */
/* The sum is converted into byte */
x = y + z;

My question is why Java does a coercion like that. Do you have any ideas?

Thanks in advance.


Solution

  • In the JVM, every stack element has a size of 32 bits. The actual addition works like this:

    1. The two bytes are pushed on the stack as 32bit values (therefore they are int)
    2. The iadd instruction is called, which pops two values from the stack and adds them
    3. The resulting integer is pushed on the stack again

    This is why you have to cast the resulting value (of type int) to a byte again.