java中boolean類型的長度

來源:互聯網
上載者:User

    在最近地總結中,發現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。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.