java boolean byte_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 。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值