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?
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:"abc"is not already in the intern pool, it’s created and put there.new String("abc")code is run:"abc"string from the intern pool is passed into theStringconstructor.Stringobject is created and initialized by copying the characters from theStringpassed into the constructor.Stringobject is returned to you.Because that’s what
interndoes. Note that callinginternon a string literal is a no-op; string literals are all interned automatically. E.g.:You create at least one
Stringobject (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):