对Java创建String是否放入String pool作代码性的试验。
参考的优秀文章
JAVA面试题解惑系列(二)——到底创建了几个String对象?
public String(String original) API
版本说明
JDK 1.7.0_71
new String() 与 intern()
package com.nicchagil.commonstudy.No01String的池; public class Call { public static void main(String[] args) { String a = "abc"; String b = "abc"; String c = new String(a); String d = "ab" + "c"; String e = "abc".intern(); String f = new String(a).intern(); System.out.println("a == b : " + (a == b)); System.out.println("a == c : " + (a == c)); System.out.println("a == d : " + (a == d)); System.out.println("a == e : " + (a == e)); System.out.println("a == f : " + (a == f)); } }
日志
a == b : true a == c : false a == d : true a == e : true a == f : true
变量、常量字符串拼接,他们是否放入String Pool?
package com.nicchagil.commonstudy.No01String的池; public class Call2 { public static void main(String[] args) { final String A = "123"; final String B = "456"; String C = "123456"; String a = "123"; String b = "456"; System.out.println("C == (A + B) : " + (C == (A + B))); // A、B为final类型 System.out.println("C == ("123" + "456") : " + (C == ("123" + "456"))); // "123"、"456"为常量 System.out.println("C == (a + b) : " + (C == (a + b))); // a、b为变量 System.out.println("C == (a + "456") : " + (C == (a + "456"))); // a为变量 System.out.println("C == (a + b).intern() : " + (C == (a + b).intern())); // 使用intern()方法 } }
日志
C == (A + B) : true C == ("123" + "456") : true C == (a + b) : false C == (a + "456") : false C == (a + b).intern() : true
注意
本日志打印的结果为上文JDK所运行的结果。