Java字符串声明

时间:2010-09-06 14:53:21

标签: java string

String str = new String("SOME")String str="SOME"之间有什么区别 这些声明是否会导致性能变化。

4 个答案:

答案 0 :(得分:40)

String str = new String("SOME")

总是在堆上创建一个新对象

String str="SOME" 

使用String pool

试试这个小例子:

        String s1 = new String("hello");
        String s2 = "hello";
        String s3 = "hello";

        System.err.println(s1 == s2);
        System.err.println(s2 == s3);

为避免在堆上创建不必要的对象,请使用第二种形式。

答案 1 :(得分:9)

两者之间存在细微差别。

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

第一个声明创建一个新的String,其值为常量SOME的值,并将其引用赋值给变量str

在第一种情况下,创建了第二个String,其值与SOME相同,这意味着更多的初始化时间。因此,你应该避免它。此外,在编译时,所有常量SOME都转换为相同的实例,使用的内存要少得多。

因此,总是喜欢第二种语法。

答案 2 :(得分:1)

String s1 = "Welcome"; // Does not create a new instance  
String s2 = new String("Welcome"); // Creates two objects and one reference variable  

答案 3 :(得分:0)

第一个将在堆中创建新的String对象,str将引用它。另外,literal也将放在String池中。这意味着将创建2个对象和1个参考变量。

第二个选项将仅在池中创建String文字,str将引用它。因此,只创建1个对象和1个引用。此选项将始终使用String池中的实例,而不是每次执行时都创建新实例。