public class TestString { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "abc";
String str1,str2,str3;
str1 = new String("abc");
str2 = str;
str3 = "abc";
// ==========================================================
System.out.println("str");
if (str == "abc") {
System.out.println("==");
} else {
System.out.println("!=");
} // ==========================================================
System.out.println("str1");
if (str1 == "abc") {
System.out.println("==");
} else {
System.out.println("!=");
}
// ==========================================================
System.out.println("str2");
if (str2 == "abc") {
System.out.println("==");
} else {
System.out.println("!=");
}
// ==========================================================
System.out.println("str3");
if (str3 == "abc") {
System.out.println("==");
} else {
System.out.println("!=");
} }}果然还是不是很明白啊!高手指教下
str
==
str1
!=
str2
==
str3
==
new的时候。jvm会在heap中创建一个String对象,然后把该对象的引用返回给用户。
直接赋值,jvm会在strings pool中查找是否存放有该String对象,如果有则返回已有的String对象。
并不会在heap中重新创建一个新String对象。
如果strings pool没有该String对象,jvm则在heap中创建新的String对象,并将引用返回给用户,同时将该引用添加至strings pool中。但是new的时候jvm并不会主动将string对象放入pool中。
是不是就是说new的时候是一定会新建对象,而不去看strings pool