以下讨论基于32位cpu卤煮整理的一些背景知识:1. JAVA规范没有明确指出boolean占几个字节
2. JVM规范指出boolean当做int处理,也就是4字节,boolean数组当做byte数组处理。
3. JVM以计算机的字长作为最小处理单位。卤煮的问题:既然JVM以字长作为最小处理单元,那么byte,short 类型也要占用一个字长即32位吗?
如果不是,也就是说可以把byte当1字节处理,short当2字节处理,那么为什么要把boolean作为4字节处理,岂不是更浪费内存空间。
2. JVM规范指出boolean当做int处理,也就是4字节,boolean数组当做byte数组处理。
3. JVM以计算机的字长作为最小处理单位。卤煮的问题:既然JVM以字长作为最小处理单元,那么byte,short 类型也要占用一个字长即32位吗?
如果不是,也就是说可以把byte当1字节处理,short当2字节处理,那么为什么要把boolean作为4字节处理,岂不是更浪费内存空间。
对这句话存在怀疑,jvm的最小处理单元不太可能是计算机字长吧.,所谓字长是同一时间中处理二进制数的位数,
字长可以是很多字节数组的加起来进行处理。
我认为是一个字节,boolean在表示的时候是只有0和1,为八分之一个字节,但是放到jvm中运行的时候,
最小单位为一个字节,将提升为1byte
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html:
The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
2)boolean[] b = new boolean[10];//数组时,每一个boolean在JVM中占一个字节。
理由:
1)JAVA规范中没有定义boolean类型的大小。
2)但是:在JVM规范第2版中讲得十分清楚。我上边的结论就是从它当中取出来的。
根据:(JVM规范第2版 3.3.4节)
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.
Where Java programming language boolean values are mapped by compilers to values of Java virtual machine type int, the compilers must use the same encoding. 而:Java virtual machine type int, whose values are 32-bit signed two's-complement integers。
Arrays of type boolean are accessed and modified using the byte array instructions
In Sun's JDK releases 1.0 and 1.1, and the Java 2 SDK, Standard Edition, v1.2, boolean arrays in the Java programming language are encoded as Java virtual machine byte arrays, using 8 bits per boolean element.