String a = "abc"与String a = new String("abc")的区别
测试代码为:
String str = "ab"; /在常量池中看是否有ab这个值,要是有str就指向ab,如果没有就在常量池中创建ab,并且指向它/
String str1 = new String ("ab");/这里"ab"本身就是常量池中的一个对象,而在运行时执行new String()时,将常量池中的对象复制一份放到堆中,并且把堆中的这个对象的引用交给s持有。所以这条语句就创建了2个String对象。。/
String s1 = "a";
String s2 = "b";
String s = s1 + s2;/因为s1,s2在编绎时无法知道确定的值所以在运行时才执行故在内存的堆中。
// 等价于 StringBuffer s = new StringBuffer();
// s.append(s1).append(s2);
// String s = s.toString();/ String s3 = "a"+"b";/在编译时就确定了s3=ab,所以s3指向常量池中的ab而不是指向堆。/
System.out.println(s == str);//false
System.out.println(s.intern() == str); //true /而当调用s.intern()方法,却可以返回s在常量池中的地址值/
System.out.println(s == str1);//false//false
System.out.println(s.intern() == str1); //false
:roll: 不知道你在讲什么~