日期:2014-05-20 浏览次数:20675 次
public static void main(String[] args) {
String s = "acb";
String s1 = "acb";
String s2 = new String("acb");
System.out.println(s == s1);
System.out.println(s == s2);
}
当直接String s = "***" 的时候对象中的值是放在常量池中的!!当再次String s1 = "***" 时先看常量池中是否有这个值如果有指向这个值如果没有在创建 String s2 = "****" 的时候是在堆里创建一个新的对象每次都是不同的!!!
String str1 = "a";//constant pool
String str2 = "b";//constant pool
String str3 = new String("a");//heap
System.out.println(str1 == str3);//false
String str4 = "a"+str2;//heap
String str5 = "a"+"b";//constant pool
String str6 = new String("ab");//heap
String str7 = "ab";//constant pool
System.out.println(str4 == str5);//false
System.out.println(str4.intern() == str5);//true
System.out.println(str4 == str6);//false
System.out.println(str5 == str7);//true
String str8 = str6;//heap
System.out.println(str6 == str8);//true
String str9 = new String("ab");//heap
System.out.println(str6 == str9);//false
下面的代码对楼主理解String的存储会有帮助
new出来的对象存在堆中,直接声明的在栈中(具体一点就是在常量池中)
String str1 = "a";//constant pool
String str2 = "b";//constant pool
String str3 = new String("a");//heap
System.out.println(str1 == str3);//false
String str4 = "a"+str2;//heap
String str5 = "a"+"b";//constant pool
String str6 = new String("ab");//heap
String str7 = "ab";//constant pool
System.out.println(str4 == str5);//false
System.out.println(str4.intern() == str5);//true
System.out.println(str4 == str6);//false
System.out.println(str5 == str7);//true
String str8 = str6;//heap
System.out.println(str6 == str8);//true
String str9 = new String("ab");//heap
System.out.println(str6 == str9);//false