New String vs String s =" something" ,有什么区别?

时间:2014-03-24 09:19:01

标签: java string new-operator

考虑代码:

public class Strings {

    public static void createStr()
    {
        String s1 = new String("one");
        String s2 = "one";

        System.out.println(s1);
        System.out.println(s2);
    }

    public static void main(String args[])
    {
        createStr();
    }

}

String s1 = new String("one");String s2 = "one";之间的区别是什么?

2 个答案:

答案 0 :(得分:7)

  String s1 = new String("one"); // will be created on the heap and not interned unless .intern() is called explicityly. 
  String s2 = "one";  // will be created in the String pool and interned automatically by the compiler.

答案 1 :(得分:0)

String s1 = new String("one");在内存中创建一个新的字符串对象,而String s2 = "one";使用字符串池。

在java中处理字符串时使用new关键字不是一个好习惯。