灵魂拷问:为什么short、byte会被提升为int?boolean到底多大?( 二 )


参考stackoverflow中的回答 Size of a byte in memory - Java,注意标注高亮的部分 。
更多对基本类型的描述,可以查看Primitive Data Types
说完byte、char、short,我们再来看看对于 boolean 的描述,摘取部分信息 2.3.4. The boolean Type:
Although the Java Virtual Machine defines a boolean type, it only provides very limited support for it. There are no Java Virtual Machine instructions solely dedicated to operations on boolean values. Instead, expressions in the Java programming language that operate on boolean values are compiled to use values of the Java Virtual Machine int data type.
 
The Java Virtual Machine does directly support boolean arrays. Its newarray instruction (§newarray) enables creation of boolean arrays. Arrays of type boolean are accessed and modified using the byte array instructions baload and bastore (§baload, §bastore).
 
In Oracle’s Java Virtual Machine implementation, boolean arrays in the Java programming language are encoded as Java Virtual Machine byte arrays, using 8 bits per boolean element.
翻译大概如下:
尽管Java虚拟机定义了一种 boolean 类型,但对它的提供支持非常有限,没有专门的虚拟机指令用来操作 boolean 类型 。但是,对于有 boolean 值参与运行的表达式,都会被编译成 int 类型的数据 。
 
虚拟机直接支持了 boolean 数组,它使用newarray指令来创建数组,并可以使用 baload 和 bastore 来访问和修改 boolean 类型的数组
 
在 Oracle 的Java虚拟机实现中,boolean 类型的数组被编码成和 byte类型的数组,每个 boolean 元素使用 8 bit 。
所以虚拟机规范是这样定义的:boolean 单独使用时,占 4 字节,在数组中使用时,占 1 字节 。但最终如何实现,还是要看各个虚拟机厂商是否遵守规范了 。




推荐阅读