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

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.