在最近地總結中,發現boolean 類型的大小挺糾結,後來在網上看了下,發現網上的觀點也是眾說紛紜。
帶著疑問我從oracle 公司的官網下載了最新的"The Java Virtual Machine Specification" 此版本是第七版本的,最終修訂日期是2012-7-27
在JVM 是這樣解釋的:
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 enables creation of boolean arrays. Arrays of type boolean are accessed and modified using the byte array instruction baload and bastore .
In Oracle 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 .
The java virtual machine encodes boolean array components using 1 to represent true and 0 to represent false . 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 類型變數在編譯的時候是使用的int 類型。而對於boolean 類型的數組時,在編譯的時候是作為byte array來編譯的所以boolean 數組裡面的每一個元件佔一個位元組,這是確定的。
個人認為:單個的boolean 類型變數,即boolean b; 在這裡說b 是和int 一樣佔有四個位元組,我覺得不合適。在上述的描述中對boolean 類型進行編譯的時候是把boolean類型的值以int 的形式映射到編譯器上的,並且在JVM 中都沒有專門處理boolean 類型的指令。應該是在程式讀到boolean 時,會在記憶體的 “data” 區開闢一塊空間用來存放true, 或者false。