Java为很多基本类型的包装类/字符串都建立常量池
常量池:也称作缓存,相同的值只存储一份,节省内存,共享访问
包装类:
基本类型 | 包装类型 | 常量池(缓存) 范围 |
---|---|---|
boolean | Boolean | true, false |
byte | Byte | \ u0000_-\u007f(-128~ 127) |
short | Short | -128~ 127 |
int | Integer | -128~ 127 |
long | Long | -128~ 127 |
char | Character | \ u0000_-\u007f(-128~ 127) |
float | Float | - |
double | Double | - |
Float, Double:没有缓存(常量池)
基本类型的包装类和字符串有两种创建方式
- 常量式(字面量)赋值创建,放在栈内存(将被常量化) :
Integer a= 10; .
String b="abc" ;
- new对象进行创建,放在堆内存(不会常量化):
Integer C = new Integer(10);
String d二new String("abc”);
这两种创建方式导致创建的对象存放的位置不同
栈内存与堆内存区别:
栈内存 | 堆内存 |
---|---|
栈内存读取速度快但容量小 | 堆内存读取速度慢但容量大 |
Integer类型示例:
public class BoxClassTest {
public static void main(String[] args)
{
int i1 = 10;
Integer i2 = 10;//自动装箱I
System . out. println(i1 == i2);//true
//自动拆箱基本类型和包装类进行比较,包装类自动拆箱
Integer i3 = new Integer(10);
System . out. println(i1 == i3); //true
//自动拆箱基本类型和包装类进行比较,包装类自动拆箱
System . out. println(i2 == i3); //false
//两个对象比较,比较其地址。
// i2是常量,放在栈内存常量池中,i3是new出对象,放在堆内存中
Integer i4 = new Integer(5);
Integer i5 = new Integer(5);
System.out.println(i1 == (i4+i5));//true
System.out.println(i2 == (i4+i5));//true
System.out.println(i3 == (i4+i5));//true
//i4+i5操作将会使得i4,i5自动拆箱为基本类型并运算得到10.
//基础类型10和对象比较,将会使对象自动拆箱,做基本类型比较
Integer i6 = i4 + i5; // +操作使得i4,i5自动拆箱,得到10,因此i6 == i2.因为Integer对象加法会自动拆箱,所以Integer i6=i4+ i5;等价于Integer i6=10;
System . out. println(i1 == i6); //true
System. out. println(i2 == i6); //true
System . out. println(i3 == i6); //false
}
java为常量字符串都建立了常量池缓存机制
字符串常量:
public class StringConstantTest {
public static void main(String[] args) { .
String s1 = "abc";//放在栈内存中
String s2 = "abc";//放在栈内存中
String s3 = "ab" + "c"; //都是常量,编译器将优化,下同,放在栈内存中
String s4 = "a" + "b" + "C";
System.out.print1n(s1 == s2); //true
System.out.print1n(s1 == s3); //true
System.out.println(s1 == s4); //true
}
}
String类型示例:
public static void main(String[] args) {
String s0 = "abcdef";//放在栈内存中
String s1 = "abc";//放在栈内存中
String s2 = "abc";//放在栈内存中
String s3 = new String("abc");//放在堆内存中
String s4 = new String("abc");//放在堆内存中
System. out. println(s1 == s2); //true
System.out.println(s1 == s3); //false 一个栈内存,一个堆内存
System.out.println(s3 == s4); //false两个都是堆内存.
System.out.println("=======================");
String s5 = s1 + "def";//涉及到变量,放在堆内存中,故编译器不优化
String s6 = "abc" + "def"; //都是常量,编译器会自动优化成abcdef
String s7 ="abc" + new String ("def");//涉及到new对象,放在堆内存中,编译器不优化
System.out.println(s5 == s6); //false
System.out.println(s5 == s7); //false
System.out.println(s6 == s7); //false
System.out.println(s0 == s6); //true
System.out.println("=========================");
}