Difference between string object and string literal

This question already has an answer here:

  • What is the difference between “text” and new String(“text”)? 9 answers

  • When you use a string literal the string can be interned, but when you use new String("...") you get a new string object.

    In this example both string literals refer the same object:

    String a = "abc"; 
    String b = "abc";
    System.out.println(a == b);  // true
    

    Here, 2 different objects are created and they have different references:

    String c = new String("abc");
    String d = new String("abc");
    System.out.println(c == d);  // false
    

    In general, you should use the string literal notation when possible. It is easier to read and it gives the compiler a chance to optimize your code.


    A String literal is a Java language concept. This is a String literal:

    "a String literal"
    

    A String object is an individual instance of the java.lang.String class.

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

    All are valid, but have a slight difference. s1 will refer to an interned String object. This means, that the character sequence "abcde" will be stored at a central place, and whenever the same literal "abcde" is used again, the JVM will not create a new String object but use the reference of the cached String.

    s2 is guranteed to be a new String object, so in this case we have:

    s1 == s2 // is false
    s1 == s3 // is true
    s1.equals(s2) // is true
    

    The long answer is available here, so I'll give you the short one.

    When you do this:

    String str = "abc";
    

    You are calling the intern() method on String. This method references an internal pool of String objects. If the String you called intern() on already resides in the pool, then a reference to that String is assigned to str . If not, then the new String is placed in the pool, and a reference to it is then assigned to str .

    Given the following code:

    String str = "abc";
    String str2 = "abc";
    boolean identity = str == str2;
    

    When you check for object identity by doing == (you are literally asking: do these two references point to the same object?), you get true .

    However, you don't need to intern() Strings . You can force the creation on a new Object on the Heap by doing this:

    String str = new String("abc");
    String str2 = new String("abc");
    boolean identity = str == str2;
    

    In this instance, str and str2 are references to different Objects , neither of which have been interned, so that when you test for Object identity using == , you will get false .

    In terms of good coding practice: do not use == to check for String equality, use .equals() instead.

    链接地址: http://www.djcxy.com/p/72126.html

    上一篇: 我怎么能加快比较std :: string与字符串文字?

    下一篇: 字符串对象和字符串文字之间的区别