Skip to main content

difference between string object and string literal



what is difference between







String str = new String("abc");







and







String str = "abc";




Comments

  1. 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 two 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.

    ReplyDelete
  2. 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";


    are all 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

    ReplyDelete
  3. "abc" is a literal String. In java these literal strings are pooled internally and the same String instance of "abc" is used where ever you have that string literal declared in your code. So "abc" == "abc" will always be true as they are both the same String instance.

    Using the String.intern() method you can add any string you like to the internally pooled strings, these will be kept in memory until java exits.

    on the other hand, using new String("abc") will create a new string object in memory which is logically the same as the "abc" literal. "abc" == new String("abc") will always be false as although they are logically equal they refer to different instances.

    Wrapping a String constructor around a string literal is of no value, it just needlessly uses more memory than it needs to.

    ReplyDelete
  4. The long answer is available elsewhere, 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.

    ReplyDelete
  5. in first case there are two objects created.

    and in case 2 its just one.

    Altought both ways str is referring to "abc";

    ReplyDelete
  6. Some disassembly is always interesting...

    $ cat Test.java
    public class Test {
    public static void main(String... args) {
    String abc = "abc";
    String def = new String("def");
    }
    }

    $ javap -c -v Test
    Compiled from "Test.java"
    public class Test extends java.lang.Object
    SourceFile: "Test.java"
    minor version: 0
    major version: 50
    Constant pool:
    const #1 = Method #7.#16; // java/lang/Object."<init>":()V
    const #2 = String #17; // abc
    const #3 = class #18; // java/lang/String
    const #4 = String #19; // def
    const #5 = Method #3.#20; // java/lang/String."<init>":(Ljava/lang/String;)V
    const #6 = class #21; // Test
    const #7 = class #22; // java/lang/Object
    const #8 = Asciz <init>;
    ...

    {
    public Test(); ...

    public static void main(java.lang.String[]);
    Code:
    Stack=3, Locals=3, Args_size=1
    0: ldc #2; // Load string constant "abc"
    2: astore_1 // Store top of stack onto local variable 1
    3: new #3; // class java/lang/String
    6: dup // duplicate top of stack
    7: ldc #4; // Load string constant "def"
    9: invokespecial #5; // Invoke constructor
    12: astore_2 // Store top of stack onto local variable 2
    13: return
    }

    ReplyDelete
  7. As Strings are immutable when you do

    String a = "xyz"


    while creating the string the jvm searches in the pool of strings if there already exists a string value "xyz", if so 'a' will simply be a reference of that string and no new String object is created.

    But if you say

    String a = new String("xyz")


    you force jvm to create a new string reference even if "xyz" is in itz pool.

    For more information read http://javatechniques.com/public/java/docs/basics/string-equality.html

    ReplyDelete
  8. In addition to the answers already posted, also see this excellent article on javaranch.

    ReplyDelete
  9. According to String class documentation they are equivalent.

    Documentation for String(String original) also says that: Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.

    EDITED: Look for other responses becasue it seems that Java documentation is misleading :(

    ReplyDelete
  10. String s = new String("FFFF") creates 2 objects: "FFFF" string and String object, which point to "FFFF" string, so it is like pointer to pointer (reference to reference, i don't keen with terminology).
    It is said you should never use new String("FFFF")

    ReplyDelete
  11. There is a subtle differences between String object and string literal.

    String s = "abc"; // creates one String object and one reference variable

    In this simple case, "abc" will go in the pool and s will refer to it.

    String s = new String("abc"); // creates two objects,and one reference variable

    In this case, because we used the new keyword, Java will create a new String object
    in normal (non-pool) memory, and s will refer to it. In addition, the literal "abc" will
    be placed in the pool.

    ReplyDelete

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex