本文介绍了Java字符串连接和实习的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题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

在第一种情况下,我知道这是两个字符串文字的串联,因此将对结果"I Love Java"进行检查,使结果正确.但是,我不确定第二种情况.

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.

问题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

以上返回false,但是如果我注释掉第1行和第2行,则返回true.为什么会这样?

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

推荐答案

问题的第一部分很简单:Java编译器将多个字符串文字的串联视为单个字符串文字,即

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"

"I Love Java"

是两个完全相同的字符串文字,可以正确地进行固定.

are two identical string literals, which get properly interned.

不适用于字符串上的+=操作,因此b1b2实际上是在运行时构造的.

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

第二部分比较棘手.回想一下b1.intern()可能返回b1或与其相等的其他String对象.保留a1a2时,您会从呼叫返回到b1.intern()a1.当您注释掉a1a2时,没有要返回的现有副本,因此b1.intern()会给您b1本身.

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.

这篇关于Java字符串连接和实习的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 00:42