日期:2014-05-20  浏览次数:20729 次

关于Boolean类型所占字节的问题
我知道某些高手已经对这种问题不屑一顾,但我还是要问一下,还请指教一二。


C++中有sizeof方法能看到具体类型所占字节数,Java里有类似的方法吗?

C++中Boolean是占几个字节?一个吗?为什么?

Java中是占几个字节?4byte还是8bit还是1bit?为什么?

如有高手能指点JVM里的知识,感激不尽!

------解决方案--------------------
java没有sizeof运算。
java boolean值占1字节(byte)的内存。而Boolean对象据说需要16字节。
楼主可以看看这个:
http://dustin.iteye.com/blog/42823

------解决方案--------------------
引用3.3.4 The boolean Type
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 instructions baload and bastore.2

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: 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.
------解决方案--------------------
探讨

引用3.3.4 The boolean Type
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 op……

------解决方案--------------------
这不一定占用 4 个字节,这与系统硬件环境有关,如果是 32 位架构 CPU 的话那么字长就是 4 个字节,一个字长的处理效率是最高的。因此,JVM 厂商一般以 1 个字长作为最小处理单元。

如果是 64 位架构的 CPU 那么字节就会达到 8 个字节。也就是说,如果是 64 位环境中一个 int 可能占据 8 个字节的空间,但这并不会影响到 int 值的范围。