這篇文章主要介紹“Java中boolean占幾字節”,在日常操作中,相信很多人在Java中boolean占幾字節問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Java中boolean占幾字節”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
這是一個看似簡單,實則深究能發現其中一二玄機的問題
讓我們來看一下官方文檔中的說法
"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兩種,這個數據類型只代表1bit的信息,但是它到底占了多少空間,卻沒有嚴格的說法,也就是說,不論它的所占空間是多少,只有1bit的信息是有意義的
"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 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 類型,但是支持是很有限的,沒有專門的虛擬機指令。
同時在 Java 語言中,對 boolean 值的操作被替換成 int 數據類型。
再去看看 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."
“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 類型的時候,也是一樣的
到這里,得出一個結論:
boolean到底占幾個字節,依賴于JVM
第一,無論Boolean占用多少字節,只有1bit的值是有意義的
第二,boolean 類型被編譯成 int 類型來使用,占 4 個 byte 。
第三,在 Java 虛擬機里,1 表示 true ,0 表示 false 。
到此,關于“Java中boolean占幾字節”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。