Why byte and short division results in int in Java?

后端 未结 5 785
孤城傲影
孤城傲影 2020-12-21 10:14

In Java, if we divide bytes, shorts or ints, we always get an int. If one of the operands is long, we\'ll ge

5条回答
  •  情书的邮戳
    2020-12-21 10:35

    The main reason is that machines usually have only add instructions for their native integer type (and floats). This is why for many languages the least used type in an arithmetic expression is int (usually the type that correspond in some way to the basic machine integer type).

    For example, i386 spec says:

    ADD performs an integer addition of the two operands (DEST and SRC). The result of the addition is assigned to the first operand (DEST), and the flags are set accordingly. When an immediate byte is added to a word or doubleword operand, the immediate value is sign-extended to the size of the word or doubleword operand.

    This means that internally any byte value is extended to an integer (or similar). After all this is reasonable as the processor is 32/64 bits and then perform any arithmetic in these sizes. If it could be possible to make arithmetic in bytes this is generally not considered as useful.

    The JVM specs says that (for addition) you have : iadd, ladd, fadd, dadd. This just reflect the fact that underlying machines usually behave such. Any other choice could have been possible, probably at the price of performance degradation.

提交回复
热议问题