Search code examples
javaprimitive

Casting java primitives, does the JVM try to save memory?


var foo = (short) 40 + (byte) 10

How many bytes does foo take up? What is its type?

I would expect that the result is stored in a short, but to save memory does the JVM test to see if it will fit in a smaller primitive?

If it were (short) 1 + (byte) 1 would it still be a short?


Solution

  • Rule of thumb: integer arithmetic operations are done as long and result in long if either argument is long, int otherwise.

    I also suspect that the JVM uses 4 bytes even to store byte and short (and boolean) variables - see JVMS 2.6.1. Local Variables and Table 2.11.1-B.


    Even var test = (byte)1 + (byte)1 will cause test to be an int.

    Not the case for var test = (byte)(1 + 1)