Fork me on GitHub

java学习笔记day01

一.数据类型


基本类型

复制代码
byte 8字节

char 16字节

short 16字节

int 32字节

float 32字节

long 64字节

double 64字节

boolean
复制代码

boolean 只有两个值,true,false ,可以使用1 bit来存储但是具体大小没有明确规定;JVM会在编译时期将boolean类型的数据转换成int,使用1来表示true,使用0来表示false。JVM支持boolean数组,但是是通过读写byte数组来实现的。

 

包装类型

基本类型都有对应的包装类型,基本包装类型与其对应的包装类型之间的赋值使用自动装箱与拆箱完成

Integer x = 2; //装箱 调用了 Interger.valueOf(2)

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

 

缓存池


new Integer(123) 与 Integer.valueOf(123)的区别在于:

new Integer(123) 每次都会新建一个对象;

Integer.valueOf(123) 会使用缓存池中的对象,多次调用会取得同一个对象的引用

 

复制代码
Integer x = new Integer(123);

Integer y = new Integer(123);

System.out.println(x == y); //false

Integer z = Integer.valueOf(123);

Integer k = Integer.valueOf(123);

System.out.println(z == k); //true
复制代码

 

valueOf()方法的实现比较简单,就是先判断值是否在缓存池中,如果在的话就直接返回缓存池的内容。

复制代码
public static Integer valueOf(int i){

if ( i >= IntegerCache.low && i <= IntegerCache.high)

return IntegerCache.cache[ i + (-IntegerCache.low)];

return new Interger(i)

}
复制代码

 


在Java8中,Integer缓存池的大小默认为 -128~127

复制代码
static final int low = -128;
static final int high;
static final Integer cache[];
static{
//high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSacveProperty("java.lang.Integer.IntegerCaceh.high");
if(integerCacheHighPropValue != null){
try{
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i,127);
//Maximum array size is Integer.MAX_VALUE
h = Math.min(i,Integer.MAX_VALUE - (-low) -1 );
}catch(NumberFormatException nfe){
//if the property cannot be parsed into an int, ignore it.
}
}
high = h;

catch = new Integer[(high - low) +1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);

//range [-128,127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
复制代码

 

编译器会在自动装箱过程调用valueOf()方法,因此多个值相同且值在缓存池范围内的Integer实例使用自动装箱来创建,那么就会引用相同的对象

Integer m = 123;
Integer n = 123;
System.out.println(m == n); //true

 

基本类型对应的缓冲池如下:

boolean values true and false
all byte values
short values between -128 and 127
int valules between -128 and 127
char in the range \u0000 to \u007F

 


在使用这些基本类型对应的包装类型时,如果该数值范围在缓冲池范围内,就可以直接使用缓冲池中的对象。

在jdk1.8所有的数值类缓冲池中,Integer的缓冲池IntegerCache很特殊,这个缓冲池的下界是-128,上界默认是127,但是这个上界是可调的,在启动jvm的时候,通过 -XX:AutoCacehMax=<size>来指定这个缓冲池的大小,该选项在JVM初始化的时候会设定一个名为java.lang.IntegerCache.high系统属性,然后IntegerCache初始化的时候就会读取该系统属性来决定上界。
————————————————
版权声明:本文为CSDN博主「yqqbz」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_52120338/article/details/123927377

posted @   yqqbz  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示