I would like to know the reason why byte
and short
values are promoted to int
whenever an expression is evaluated or a bit-wise operation is processed?
Why byte and short values are promoted to int when an expression is evaluated
4.5k views Asked by Frederic Nault At
1
Because the Java Language Specification says so. Section 5.6.1 defines unary numeric promotion for evaulation of certain operators, and it says:
Section 5.6.2 on evaluation of binary numeric operators ('binary' meaning operators that have two operands, like '+') says something similar:
Why was it defined this way? A major reason is that at the time of design of the Java language and Java virtual machine, 32-bit was the standard word size of computers, where there is no performance advantage to doing basic arithmetic with smaller types. The Java virtual machine was designed to take advantage of this, by using 32-bit as the int size, and then providing dedicated instructions in the Java bytecode for arithmetic with ints, longs, floats, and doubles, but not with any of the smaller numeric types (byte, short, and char). Eliminating the smaller types makes the bytecode simpler, and lets the complete instruction set, with room for future expansion, still fit the opcode in a single byte. Similarly, the JVM was designed with a bias towards easy implementation on 32-bit systems, in the layout of data in classes and in the stack, where 64-bit types (doubles and longs) take two slots and all other types (32-bit or smaller) take one slot.
So, the smaller types were generally treated as second-class citizens in the design of Java, converted to ints at various steps, because that simplified some things. The smaller types are still important because they take less memory when packed together (e.g., in arrays), but they do not help when evaluating expressions.