public static void main(String[] args) {
String str1 = "a";
String str2 = "b";
String str3 = "ab";
String str4 = "a" + "b";//在编译时就直接在字符串池中找到"ab",str4指向字符串池
String str5 = str1 + str2;//先在堆中创建两个String对象,分别为"a","b",再利用StringBuild的append(),创建"ab",把"ab"的堆地址赋给str5
String str6 = str1 + "b";//还是在堆中分配
System.out.println(str3 == str4);
System.out.println(str3 == str5);
System.out.println(str3 == str6);
}
result:
true
false
false |