1

I was going through SCJP examination and found one line in one book.

String s = new String("abc");

And it was written that, two objects will be created on above line. one on HEAP and one on STRING POOL.

I am not satisfied by the declaration given there. Can someone make me understand why two objects are created ?

Thanks in advance.

trincot
  • 317,000
  • 35
  • 244
  • 286
Tilakraj Jayswal
  • 471
  • 4
  • 10
  • If you want only one object: `String s = "abc"` – ACV Oct 01 '15 at 10:59
  • 2
    The question is strange. The interned string may be created during the class loading along with tons of other objects (even if you don't execute this line you will have this `"abc"` interned). However if it was already interned before (for example, you have a method in another class with name `abc`), then it's not created during the loading of this class. Nevertheless upon *execution* of given line only one new object is created: new `String` instance. Also note that interned string pool is located in the heap as well these days. – Tagir Valeev Oct 01 '15 at 11:03
  • I am agree that interned string will be created in String pool while class loads or at compile time, But does that thing created either at compile time or at class loading in String pool, is called one separate object ? – Tilakraj Jayswal Oct 01 '15 at 11:12
  • The author is incorrect. The string object for the literal isn't created 'on the above line'. It is created during compilation and class loading. You could never execute the line and it would still be created. – user207421 Mar 23 '17 at 06:04

4 Answers4

4

Author is correct. When ever you used String literal, that literal goes to constant pool first.

Hence "abc" created in constant pool.

And when you use new key word a new Object called s created on heap.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

The literal "abc" is created and interned ("string pool").

The new operator will create a new String that is not interned.

Mena
  • 47,782
  • 11
  • 87
  • 106
1

Author is correct:

  • one object will be created in the string pool for "abc" literal; and
  • another object will be created on the heap for new String(...)
ioseb
  • 16,625
  • 3
  • 33
  • 29
1

Object 1 - "abc"

Object 2 - new String("abc")

Harish Ved
  • 560
  • 4
  • 17