Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting String objects created by Java code

Tags:

How many String objects are created by the following code?

String x = new String("xyz"); String y = "abc"; x = x + y; 

I have visited many websites where some say that this line of code creates 3 objects and some say it creates 4. I just wanted to know how many objects are created after this line of code is executed.

like image 897
Harsh Shah Avatar asked Apr 01 '15 12:04

Harsh Shah


People also ask

How many string objects are created in Java?

The answer is: 2 String objects are created.

How many objects are created in Java?

So, only 1 object is ever created because Java is pass-by-reference.


Video Answer


1 Answers

By the end of the run there will be four String objects:

  1. A String that corresponds to the interned "xyz" literal
  2. Its copy created by new String("xyz")
  3. A String that corresponds to the interned "abc" literal
  4. A String that corresponds to concatenation "xyz" + "abc"

The real question is attributing some or all of these objects to your program. One can reasonably claim that as few as two or as many as four Strings are created by your code. Even though there are four String objects in total, objects 1 and 3 may not necessarily be created by your code, because they are in a constant pool, so they get created outside your code's direct control.

like image 132
Sergey Kalinichenko Avatar answered Sep 23 '22 18:09

Sergey Kalinichenko