public class StringInMemory {
public static void main(String[] args) {
String a1="hello";
String a2=new String("hello");
System.out.println(a1==a2); //结果为false,a2在堆上
String S1="hello";
String S2=new String("hello");
System.out.println(S1==S2.intern()); //结果为true,因为intern()是返回对象常量池中的值,如果常量池中没有它的值,那就创建一个
//然后再返回
String p1="hello";
String p2="he"+"llo";
System.out.println(p1==p2); //结果为true ,p2中两个值相加jvm可以做优化。
//对比:
String m1="hello";
String m2="he";
String m3="llo";
String m4=m2+m3;
System.out.println(m1==m4); //结果为false,m2m3两个变量相加,jvm没有办法优化成常量值,等于在堆上又生成一个对象,但并没有给他赋值
//所以堆上的对象和常量池中的对象相比是不等的
int i1=10;
Integer i2=10;
System.out.println(i1==i2); //结果为true
Integer w1=10;
Integer w2=10;
System.out.println(w1==w2); //结果为true
//Integer在-128到127范围内,它都在常量池中创建。如果有返回引用,没有就创建,再范围
Integer r1=128;
Integer r2=128;
System.out.println(r1==r2); //结果为false
//因为是128 超范围了,不在常量池里
//所以int等基本数据类型不管多少都在常量池里面,而Integer要看范围,范围内就在常量,超范围就不在了
}
}