标签:
对Java创建String是否放入String pool作代码性的试验。
JAVA面试题解惑系列(二)——到底创建了几个String对象?
public String(String original) API
JDK 1.7.0_71
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
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所运行的结果。
【Java】Java创建String时,什么情况放进String Pool?
标签:
原文地址:http://www.cnblogs.com/nick-huang/p/4785379.html