Java中boolean佔的字節數

java中的8種基本數據類型基本都有明確的空間佔用大小,但是對於boolean類型,並沒有給出一個具體的大小。抱着疑惑在網上找了會,但是大家給出的說法有好幾種,都不盡相同,有說佔1bit,有1bite甚至是佔4bites的。都有自己的道理,但是爲什麼會有這麼些種情況也不是很瞭解。 直到看見了這個博客才弄明白了。一下便是他博客中些的內容,地址是

http://www.binkery.com/archives/346.html

在java官方文檔中介紹如下:
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.

**boolean 值只有 true 和 false 兩種,這個數據類型只代表 1 bit 的信息,但是它的“大小”沒有嚴格的定義。也就是說,不管它佔多大的空間,只有一個bit的信息是有意義的。**

在java虛擬機上介紹如下:
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.

**Java 虛擬機雖然定義了 boolean 類型,但是支持是有限的,沒有專門的虛擬機指令。**

在 Java 語言中,對 boolean 值的操作被替換成 int 數據類型。 
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).

java 虛擬機沒有直接支持 boolean 數組。boolean 類型數組和 byte 數組公用指令。
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.

在 Oracle 的 Java 虛擬機實現中,Java 語言中的 boolean 數組被編碼成 Java 虛擬機的 byte 數組,每個元素佔 8 比特。

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.

Java 虛擬機使用 1 表示 true ,0 表示 false 來編碼 boolean 數組。Java 語言的 boolean 值被編譯器映射成 Java 虛擬機的 int 類型的時候,也是採用一樣的編碼。

故可以總結出:

1. boolean 類型被編譯成 int 類型來使用,佔 4 個 byte 。
2. boolean 數組被編譯成 byte 數組類型,每個 boolean 數組成員佔 1 個 byte 。
3. 在 Java 虛擬機裏,1 表示 true ,0 表示 false 。
4. 可以肯定的是,不會是 1 個 bit 。
5. boolean只是包含了一個bit大小的信息,在不同情況下實際轉化成的大小不一樣。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章