任何人都可以解释一下 String- 的以下实现之间的区别吗
1)
{
String comma=",";
return finalStr = "Hello"+comma+"Welcome"+comma+"to"+comma+"Stack"+comma+"overflow";
}
2)
{
return finalStr = "Hello,Welcome,to,Stack,overflow";
}
将在第一个 (1) block 中创建多少个字符串对象,是否只有一个字符串 finalStr
引用 Hello,Welcome,to,Stack,overflow 的内存位置
被存储或者它会为每个单词创建多个位置,然后一旦附加它就会创建一个新的内存位置。
最佳答案
在这两种情况下,都只会为每个创建一个 String 对象。因为,编译器足够聪明,可以理解编译时的连接。这些是字符串文字,它们将在编译时进行评估,并且只会为每种情况创建一个字符串。
根据 JLS
A long string literal can always be broken up into shorter pieces and written as a (possibly parenthesized) expression using the string concatenation operator + [...] Moreover, a string literal always refers to the same instance of class String.
- Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
- Strings computed by concatenation at run-time are newly created and therefore distinct.
关于java - 追加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21847679/