public class Test {
public static void main(String[] args) {
String a = "tes";
String b = a + "t";
String c = new String("test");
System.out.println(a.intern() == a); //true
System.out.println(b.intern() == b); //false
System.out.println(b.intern() == c.intern()); //true
}
}
操作符+用于字符串时进行了重载,基本可以推测是借用了String的concat方法
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
char buf[] = new char[count + otherLen];
getChars(0, count, buf, 0);
str.getChars(0, otherLen, buf, count);
return new String(0, count + otherLen, buf);
}
该方法就是返回堆中新生成对象的,而不是the interned one
从定义上讲:
String a = "tes";
String b = a + "t";
a是literal,而b就不是literal,也不是string valued constant expression,因为a不是constant
详见:jls §3.10.5:http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#101083
再通过这个验证:
String b = "tes" + "t";
System.out.println(b.intern() == b);
结果为true,ci是string值的常量表达式(string-valued constant expression),属于例外吧。
The following are examples of string literals:
"" // the empty string "\"" // a string containing " alone "This is a string" // a string containing 16 characters "This is a " + // actually a string-valued constant expression, "two-line string" // formed from two string literals
All literal strings and string-valued constant expressions are interned.