pinaki
pinaki

Reputation: 331

How many objects are created (string pool+heap)

String s = new String("a");
    s.concat("b");
    s.concat("c");

As far as I understand, the no. of counts :

In pool - 3 ("a", "b", "c")

In heap - 3 ("a", "ab", "ac"), where "ab" and "ac" are eligible for garbage collection.

Am I right ?

I have this confusion. Please help.

Upvotes: 1

Views: 67

Answers (1)

Suresh Atta
Suresh Atta

Reputation: 121998

You are correct.

  • 3 objects in constant pool ("a","b","c"). All literals and
  • 3 in heap since String is immutable. Each concat creates a String object.

Total of 6.

Upvotes: 3

Related Questions