Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why byte and short values are promoted to int when an expression is evaluated [duplicate]

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?

like image 318
Frederic Nault Avatar asked Dec 20 '14 16:12

Frederic Nault


1 Answers

Because the Java Language Specification says so. Section 5.6.1 defines unary numeric promotion for evaulation of certain operators, and it says:

  • If the operand is of compile-time type byte, short, or char, it is promoted to a value of type int by a widening primitive conversion (§5.1.2).

Section 5.6.2 on evaluation of binary numeric operators ('binary' meaning operators that have two operands, like '+') says something similar:

  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.

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.

like image 165
Boann Avatar answered Sep 29 '22 12:09

Boann