经常把Java基本类型的字节数和位数等一些信息搞混,今天做一个表格,总结一下。
类型 | 字节数 | 位数 | 表示范围 |
---|---|---|---|
byte | 1字节 | 8位 | -128~127 = - 2 7 2^7 27~ 2 7 2^7 27-1 |
short | 2字节 | 16位 | -32768~32767 = - 2 15 2^{15} 215~ 2 15 2^{15} 215-1 |
int | 4字节 | 32位 | -2147483648~2147483647 = - 2 31 2^{31} 231~ 2 31 2^{31} 231-1 |
long | 8字节 | 64位 | - 2 63 2^{63} 263~ 2 63 2^{63} 263-1 |
float | 4字节 | 32位 | -3.4E38~3.4E38 |
double | 8字节 | 64位 | -1.7E308~1.7E308 |
char | 2字节 | 16位 | 0 ~ 2 16 2^{16} 216-1 |
boolean | 1字节 或4字节 | – | true和 false |
几点说明
1、1字节=8位(bit);
2、float和double表示范围:
float类型占32位,其中从高到低分为:1位的符号位;8位的指数位;23位尾数位。
double类型64位,其中从高到低分为:1位的符号位;11位的指数位;52位的尾数位。
3、char类型占16位,但是无符号位并且可表示中文字符;
4、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类型的“大小”并没有精确的给出来。
但是《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.
虽然Java虚拟机定义了一个布尔类型,但它只为它提供非常有限的支持。 没有Java虚拟机指令专门用于对布尔值的操作。 相反,Java编程语言中对布尔值进行操作的表达式被编译为使用Java虚拟机int数据类型的值
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
Java虚拟机支持boolean数组,可以创建boolean类型数据,当使用boolean数组的时候,允许使用byte数组去存储
也就是说,当单独使用的时候,以int形式,占4字节存储,当作为boolean数组的时候,就是以byte形式,占1字节去存储;