更新时间:2022-06-21 23:19:58
如果java支持byte数据类型,那么为什么对byte进行操作会导致int
if java supports byte datatype then why operation on byte results int
因为这就是Java虚拟机的设计方式。没有指令集对字节类型执行操作。相反, int
类型的指令集用于 boolean
, byte
, char
,短
类型。
Because that's how the Java Virtual Machine is designed. There is no instruction set to perform operation on a byte type. Rather the instruction set for int
type is used for the operation on boolean
, byte
, char
, and short
types.
来自 JVM规范 - 第2.11.1节:
编译器对类型
byte
的文字值加载进行编码,short
使用Java虚拟机指令在编译时将这些值签名扩展为int
类型的值 - 时间。类型boolean
和char
的文字值的加载使用将文字零扩展为类型值的指令进行编码int
在编译时或运行时。 [..]。因此,对实际类型的值的大多数操作boolean
,byte
,char
和short
由运行于计算类型int
的值的指令正确执行。
A compiler encodes loads of literal values of types
byte
andshort
using Java Virtual Machine instructions that sign-extend those values to values of typeint
at compile-time or run-time. Loads of literal values of typesboolean
andchar
are encoded using instructions that zero-extend the literal to a value of typeint
at compile-time or run-time. [..]. Thus, most operations on values of actual typesboolean
,byte
,char
, andshort
are correctly performed by instructions operating on values of computational typeint
.
背后的原因也在该部分中指明:
The reason behind this is also specified in that section:
鉴于Java虚拟机的单字节操作码大小,将编码类型编码到操作码中会对其指令集的设计造成压力。如果每个类型化指令都支持所有Java虚拟机的运行时数据类型,则会有比在
字节
中表示的更多指令。 [...]可以根据需要使用单独的指令在不支持和支持的数据类型之间进行转换。
Given the Java Virtual Machine's one-byte opcode size, encoding types into opcodes places pressure on the design of its instruction set. If each typed instruction supported all of the Java Virtual Machine's run-time data types, there would be more instructions than could be represented in a
byte
. [...] Separate instructions can be used to convert between unsupported and supported data types as necessary.
有关所有内容的详细信息指令集可用于各种类型,您可以查看该部分中的表。
For the details on what all instruction sets are available for various types, you can go through the table in that section.
还有一个表指定实际类型到JVM计算类型的映射:
There is also a table specifying the mapping of actual type to the JVM computational type: