- 需要知道 String a = "abd"; 和String b = new String();的区别。
要明确每次只要new一次堆内存就会开辟一个新的内存地址。
可以使用intern()方法手动将new出来的对象丢到字符串常量池中。
public class StringDemo { public static void main(String[] args) { String str = "Hello"; str = str + "World"; str += "!!!"; System.out.println(str); } }
public static void main(String[] args) { String stra = "hello" ; String strb = "hello" ; String strc = "hello" ; System.out.println(stra == strb);//true System.out.println(stra == strc);//true System.out.println(strb == strc);//true } }
String e = "123"; String f = new String("123").intern(); System.out.println(e==f); //true 手动入池 入池前检查字符串池里已经有123 直接将引用指向里面已经有的常量