Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

java string concatenation and interning

Question 1

String a1 = "I Love" + " Java";
String a2 = "I Love " + "Java";
System.out.println( a1 == a2 ); // true

String b1 = "I Love";
b1 += " Java";
String b2 = "I Love ";
b2 += "Java";
System.out.println( b1 == b2 ); // false

In the first case, I understand that it is a concatenation of two string literals, so the result "I Love Java" will be interned, giving the result true. However, I'm not sure about the second case.

Question 2

String a1 = "I Love" + " Java"; // line 1
String a2 = "I Love " + "Java"; // line 2

String b1 = "I Love";
b1 += " Java";
String b2 = "I Love ";
b2 += "Java";
String b3 = b1.intern();
System.out.println( b1 == b3 ); // false

The above returns false, but if I comment out lines 1 and 2, it returns true. Why is that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The first part of your question is simple: Java compiler treats concatenation of multiple string literals as a single string literal, i.e.

"I Love" + " Java"

and

"I Love Java"

are two identical string literals, which get properly interned.

The same interning behavior does not apply to += operation on strings, so b1 and b2 are actually constructed at run-time.

The second part is trickier. Recall that b1.intern() may return b1 or some other String object that is equal to it. When you keep a1 and a2, you get a1 back from the call to b1.intern(). When you comment out a1 and a2, there is no existing copy to be returned, so b1.intern() gives you back b1 itself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...