java中boolean类型的长度

本文探讨了Java中boolean类型的存储细节。通过JVM规范说明,单个boolean变量在编译时以int形式存在,而boolean数组则以byte数组形式存储,每个元素占用1字节。文章还解释了JVM如何处理boolean类型及其编译过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    在最近地总结中,发现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。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值