Java 基本数据类型

八大基本数据类型

数据类型 内存 取值范围 包装类 默认值
byte 1字节8位 -128~127 Byte 0
short 2字节16位 -32768~32767 Short 0
int 4字节32位 -231~231-1 Integer 0
long 8字节64位 -263~263-1 Long 0L
float 4字节32位 3.4e45~1.4e38 Float 0.0f
double 8字节64位 4.9e324~1.8e308 Double 0.0d
boolean 1字节8位 true与false Boolean false
char 2字节16位,存储Unicode码 2^16 -1 Character \u0000

注意:JVM 在编译时期会把 boolean 类型的数据转换为 int,使用1表示 true,0表示 false

包装类型

基本类型都有对应的包装类型,基本类型与对应包装类型之间的赋值使用自动装箱和拆箱完成
由基本类型向对应的包装类型转换称为装箱
由包装类相对应的基本数据类型转换称为拆箱
基本类型的效率 优于 装箱类型

Integer x = 2;     // 装箱 调用了 Integer.valueOf(2)
int y = x;         // 拆箱 调用了 X.intValue()

缓存池

int a = 128, b = 128;
System.out.println(a == b);                        //true
        
Integer a1 = 127, b1 = 127;
System.out.println(a1 == b1);                      //true
        
Integer a2 = 128, b2 = 128;
System.out.println(a2 == b2);                      //false
System.out.println(a2.equals(b2));                 //true
System.out.println(a2.intValue() == b2.intValue());//true
Integer x = 127; //自动装箱,如果在-128到127之间,则值存在常量池 IntegerCache 中。等同于 Integer x = Integer.valueOf(127);
Integer y = new Integer(127); //普通的堆中的对象

对于装箱类型,正确的比较写法应该是 a2.equals(b2) 或者 a2.intValue() == b2.intValue()
Integer 内部使用了 IntegerCache,
默认情况下,对于在(-128 <= i <=  127)范围的值,装箱赋值时,直接取的缓存,是同一个对象,引用相同,所以 == 运算返回 true


基本类型对应的缓冲池如下:
    * boolean values true and false
    * all byte values
    * short values between -128 and 127
    * int values between -128 and 127
    * char in the range \u0000 to \u007F

调整缓存池大小:
    JVM参数设置 -XX:AutoBoxCacheMax=<size> 来指定这个缓冲池的大小
posted @ 2020-12-04 14:24  BreakZhang  阅读(60)  评论(0编辑  收藏  举报