1. 栈:存放基本类型的变量和对象的引用
2. 堆:存放所有new出来的对象(new String("abc");)
3. 常量池:存放字符串常量和基本类型的常量(public static final)
String s = new String(“abc”);如果常量池中没有abc对象(有则不创建),则创建一个abc对象,然后堆中再创建一个常量池中abc对象的拷贝对象。
s存在栈中,abc存在堆中,abc也存在常量池中
jdk1.6之前运行时常量池是方法区的一部分,jdk1.7之后被转移到了堆内存中(来源)
String a = "abc"; String b = new String("abc"); System.out.println(a==b);//false,b有两个地址 System.out.println(a==b.intern());//true //intern - 返回字符串在常量池的引用(有则返回引用,没有建一个返回) String a1 = new String("123"); String a2 = new String("123"); System.out.println(a1==a2);//false String a3 = "123"; String a4 = "123"; System.out.println(a3==a4);//true
DEMO
int i1 = 1000; Integer i2 = 1000; Integer i3 = new Integer(1000); Integer i4 = Integer.valueOf(1000);// This method will always cache values in the range -128 to 127, System.out.println(i1==i2);//true System.out.println(i1==i3);//true System.out.println(i1==i4);//true System.out.println(i2==i3);//false System.out.println(i2==i4);//true:100换成1000=false,可以理解为>127时,i4指向了常量池 System.out.println(i3==i4);//false System.out.println("----------------------------"); String s1 = "abc"; String s2 = "abc"; String s3 = new String("abc"); String s4 = new String("abc"); String s5 = new String("abc").intern(); String s6 = String.valueOf("abc"); String s7 = new String("abc").toString();//s6和s7相似,结果一样 System.out.println(s1==s2);//true System.out.println(s3==s4);//false System.out.println(s1==s5);//true System.out.println(s3==s5);//false System.out.println(s1==s6);//true System.out.println(s3==s6);//false System.out.println(s5==s6);//true
This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.
Integer a1 = 200; Integer a2 = 200; Integer a3 = 100; Integer a4 = 100; System.out.println(a1==a2);//false System.out.println(a3==a4);//true System.out.println(a1>a3);//true
扩展阅读:java8中基本数据类型的封装类的自动装箱拆箱