Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

To keep the JVM instruction set simple, it doesn't implement an addition operator for each integral type. Specifically, it can't add bytes. (See the list of JVM ops) This makes the JVM simpler, and probably more portable.

This mirrors the java byte code, the jvm, java virtual machine, that in the specification uses an int to store a single byte variable on the stack. It uses iadd for adding two bytes. See the jvm instruction set.

One might argue that it is a bit of overspecification: mentioning an implementation choice of the reference implementation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top