大家都知道在java中有八种基本数据类型,他们所占得空间当然也是不一样的。所占空间如下:
byte:1字节
short:2字节
int:4字节
long:8字节
char:2字节
float:4字节
double:8字节
boolean:不确定
本来boolean应该只占用1bit也就是1/8字节的,但实际上,由于Java的实际寻址单元最小是byte即1字节,所以所以实际上boolean占用的是可能是1bit,也可能是更多,这个是不确定的。下面是Sun的官方介绍。
boolean: 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.
再下面是JVM虚拟机规范的介绍(JVM规范第2版 3.3.4节):
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.
所以只是单纯的boolean b = true;这里的b占用4个字节,和int一样。
而紧接着下面还有一段:
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.
所以说boolean[] b = new boolean[10];这样的数组中每个值占用的空间是1字节。
博客已搬家,请访问http://irfen.me