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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:11:56  来源:igfitidea点击:

Java String declaration

javastring

提问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 SOMEto the variable str

第二个声明将与常量关联的引用分配SOME给变量str

First declaration creates a new String having for value the value of the constant SOMEand assignates its reference to the variable str.

第一个声明创建一个新的字符串,其值为常量的值,SOME并将其引用分配给变量str

In the first case, a second String has been created having the same value that SOMEwhich implies more inititialization time. As a consequence, you should avoid it. Furthermore, at compile time, all constants SOMEare 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