Anand Anand - 5 months ago 13
Java Question

String object creation using new and its comparison with intern method

I read in Kathy Sierra book that when we create String using new operator like String s = new String("abc") In this case, because we used the new keyword, Java will create a new String object in normal (nonpool) memory, and s will refer to it. In addition, literal "abc" will be placed in the pool.

intern() says that if String pool already contains a string then the string from the pool is returned Otherwise, the String object is added to the pool and a reference to this String object is returned.

If string "abc" when created using new also placed the string in the pool, then wht does intern() says that string from the pool is returned if String pool contains the string otherwise the string object is added to the pool.

Also I want to know if we create a String using new then actually how many objects get created?

Answer

TL;DR: If you ever really need to do new String("abc"), you'll know you need to and you'll know why. It's so rare that it's almost valid to say you never need to. Just use "abc".


The long version:

When you have the code new String("abc") the following things occur at various times:

  • When the class containing that code is loaded, if a string with the characters "abc" is not already in the intern pool, it's created and put there.
  • When the new String("abc") code is run:
    • A reference to the "abc" string from the intern pool is passed into the String constructor.
    • A new String object is created and initialized by copying the characters from the String passed into the constructor.
    • The new String object is returned to you.

If string "abc" when created using new also placed the string in the pool, then why does intern() says that string from the pool is returned if String pool contains the string otherwise the string object is added to the pool.

Because that's what intern does. Note that calling intern on a string literal is a no-op; string literals are all interned automatically. E.g.:

String s1 = "abc";               // Get a reference to the string defined by the literal
String s2 = s1.intern();         // No-op
System.out.println(s1 == s2);    // "true"
System.out.println(s1 == "abc"); // "true", all literals are interned automatically

Also I want to know if we create a String using new then actually how many objects get created?

You create at least one String object (the new, non-interned one), and possibly two (if the literal wasn't already in the pool; but again, that bit happens earlier, when the class file's literals are loaded):

String s1 = "abc";            // Get a reference to the string defined by the literal
String s2 = new String(s1);   // Create a new `String` object (guaranteed)
System.out.println(s1 == s2); // "false"
String s3 = s2.intern();      // Get the interned version of the string with these characters
System.out.println(s1 == s3); // "true"