why string concatenation yields no interned one

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值