Java String 对象创建
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2956202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java String object creation
提问by Ajay
Possible Duplicate:
What is the purpose of the expression “new String(…)” in Java?
Hi,
你好,
1) What is difference in thers two statements:
1)这两个陈述有什么区别:
String s1 = "abc";
and
和
String s1 = new String("abc")
2) as i am not using new in first statement, how string object will be created
2) 因为我没有在第一条语句中使用 new,所以将如何创建字符串对象
Thanks
谢谢
回答by Bruno Unna
In the first case, the compiler knows the value of the String s1. Thus, all strings with the same value will use the same memory locations:
在第一种情况下,编译器知道字符串 s1 的值。因此,具有相同值的所有字符串将使用相同的内存位置:
String s1 = "abc";
String s2 = "abc";
Although there are two String references (s1 and s2), there is only one "abc" sequence in memory. The newoperator is not needed because the compiler does the job.
尽管有两个字符串引用(s1 和 s2),但内存中只有一个“abc”序列。在new不需要操作员,因为编译器做这项工作。
In the second case, the compiler doesn't perform the evaluation of the String value. Thus, the sentence will generate a new instance of String, at runtime:
在第二种情况下,编译器不执行 String 值的计算。因此,这句话将在运行时生成一个新的 String 实例:
String s1 = "abc";
String s2 = new String("abc");
The constant "abc" in line 1 references the same memory as the constant "abc" in line 2. But the net effect of line 2 is the creation of a new String instance.
第 1 行中的常量“abc”与第 2 行中的常量“abc”引用了相同的内存。但第 2 行的最终效果是创建了一个新的 String 实例。
回答by Marc
The first will use a fixed String that will be compiled in the code. The second variant uses the fixed String and creates a new String by copying the characters. This actually creates a new separate object in memory and is not necessary, because Strings are immutable. For more information, you can read this thread.
第一个将使用将在代码中编译的固定字符串。第二个变体使用固定字符串并通过复制字符创建一个新字符串。这实际上在内存中创建了一个新的单独对象并且不是必需的,因为字符串是不可变的。有关更多信息,您可以阅读此线程。
The main advantage of having internalized strings is that the performance is better (e.g. through caching etc.).
内部化字符串的主要优点是性能更好(例如通过缓存等)。
As a programmer there is no real upside to creating a new String, unless you come by the following example:
作为一个程序员,创建一个新的 String 并没有真正的好处,除非你看到下面的例子:
String sentence = "Lorem ipsum dolor sit amet";
String word = sentence.substring(5);
Now the word has a reference to the sentence (substring does not copy the characters). This is efficient while the sentence is also used, but when this one is thrown away you use a lot more memory than needed. In that case a new String can be created:
现在这个词有一个对句子的引用(子字符串不复制字符)。这在句子也被使用时很有效,但是当这个句子被扔掉时,你会使用比需要的更多的内存。在这种情况下,可以创建一个新字符串:
word = new String(word);

