Java 字符串声明
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3652369/
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 declaration
提问by JavaUser
What is the difference between String str = new String("SOME")
and String str="SOME"
Does these declarations gives performance variation.
这些声明String str = new String("SOME")
和String str="SOME"
这些声明之间有什么区别,是否会导致性能变化。
采纳答案by PeterMmm
String str = new String("SOME")
always create a new object on the heap
总是在堆上创建一个新对象
String str="SOME"
uses the String pool
使用字符串池
Try this small example:
试试这个小例子:
String s1 = new String("hello");
String s2 = "hello";
String s3 = "hello";
System.err.println(s1 == s2);
System.err.println(s2 == s3);
To avoid creating unnecesary objects on the heap use the second form.
为了避免在堆上创建不必要的对象,请使用第二种形式。
回答by Riduidel
There is a small difference between both.
两者之间存在细微差别。
Second declaration assignates the reference associated to the constant SOME
to the variable str
第二个声明将与常量关联的引用分配SOME
给变量str
First declaration creates a new String having for value the value of the constant SOME
and assignates its reference to the variable str
.
第一个声明创建一个新的字符串,其值为常量的值,SOME
并将其引用分配给变量str
。
In the first case, a second String has been created having the same value that SOME
which implies more inititialization time. As a consequence, you should avoid it. Furthermore, at compile time, all constants SOME
are transformed into the same instance, which uses far less memory.
在第一种情况下,已创建第二个字符串,SOME
其具有相同的值,这意味着更多的初始化时间。因此,您应该避免它。此外,在编译时,所有常量SOME
都被转换为同一个实例,这样使用的内存要少得多。
As a consequence, always prefer second syntax.
因此,总是更喜欢第二种语法。
回答by Akash Aggarwal
First one will create new String object in heap and str will refer it. In addition literal will also be placed in String pool. It means 2 objects will be created and 1 reference variable.
第一个将在堆中创建新的 String 对象, str 将引用它。另外literal也会被放入String池中。这意味着将创建 2 个对象和 1 个引用变量。
Second option will create String literal in pool only and str will refer it. So only 1 Object will be created and 1 reference. This option will use the instance from String pool always rather than creating new one each time it is executed.
第二个选项将仅在池中创建字符串文字,而 str 将引用它。所以只会创建 1 个对象和 1 个引用。此选项将始终使用字符串池中的实例,而不是每次执行时都创建一个新实例。
回答by bhargava krishna
String s1 = "Welcome"; // Does not create a new instance
String s2 = new String("Welcome"); // Creates two objects and one reference variable