在Java字符串中+和+=的区别是什么?

huangapple go评论80阅读模式
英文:

Difference between + and += on Java Strings

问题

我想了解在Java中使用+和+=操作字符串时内存是如何分配的。
我知道字符串字面值存储在字符串常量池中,在情况#1中,s1和s2都引用字符串常量池中相同的内存。

在情况#2中,即使我使用+运算符,它仍然引用字符串常量池中的相同对象。

我发现有趣的是情况#3。在这种情况下,内存是如何分配的?它与情况#2有何不同?

// 情况#1
String s1 = "Hello Java";
String s2 = "Hello Java";
System.out.println(s1 == s2); //true

// 情况#2
s1 = "Hello" + " Java";
s2 = "Hello Java";
System.out.println(s1 == s2); //true

s1 = "Hello";
s1 += " Java";
s2 = "Hello Java";
System.out.println(s1 == s2); //false

英文:

I would like to understand how memory is allocated when we use + and += on Strings in Java.
I know that String literals are stored in the String Constant Pool and in Case #1, both s1 and s2 reference the same memory in String Constant Pool.

In Case #2, eventhough I use a + operator, it still references the same object in String Constant Pool

What I find interesting is Case #3. How and where is memory allocated in this case? How is it different from Case #2

//Case #1
String s1 = "Hello Java";
String s2 = "Hello Java";
System.out.println(s1 == s2); //true

//Case #2
s1 = "Hello" + " Java";
s2 = "Hello Java";
System.out.println(s1 == s2); //true

s1 = "Hello";
s1 += " Java";
s2 = "Hello Java";
System.out.println(s1 == s2); //false

答案1

得分: 14

这实际上并不是++=之间的区别;如果您写成以下方式,您会得到与情况#3相同的行为:

s1 = "Hello";
s1 = s1 + " Java";
s2 = "Hello Java";
System.out.println(s1 == s2); //false

在情况#2中看到的行为的原因是"Hello" + " Java"是一个常量表达式,因此它实际上可以在编译时处理,就像它是"Hello Java"一样,并且需要像"Hello Java"一样进行汇编处理。

当您将其拆分为单独的语句时,情况就不同了,所以您会得到一个新创建的字符串。

英文:

This isn't actually a difference between + and +=; you'd get the same behavior as Case #3 if you wrote:

s1 = "Hello";
s1 = s1 + " Java";
s2 = "Hello Java";
System.out.println(s1 == s2); //false

The reason for the behavior you see in Case #2 is that "Hello" + " Java" is a constant expression [JLS8 §15.28], so it can actually be handled at compile-time exactly as if it were "Hello Java", and is required to be interned just as "Hello Java" is.

When you break it up into separate statements, that's no longer the case, so you get a newly created string [JLS8 §15.18.1].

huangapple
  • 本文由 发表于 2020年8月4日 01:08:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63233925.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定