106k views
1 vote
Examine the following section of code:

String strA = new String("Roasted ");
String strB = strA;
String strC = strA;
String strD = strA;
String strE = strA;
How many objects (total) are created? After the last statement has executed, how many objects are now accessible (don't count garbage)?

1 Answer

3 votes

Final answer:

The given code creates a total of 1 object. After the last statement executes, 1 object is accessible.In the given code, only one object is created, and that single object is accessible through all the references from strA to strE.

Step-by-step explanation:

In the given code, the following objects are created:

  1. A new object is created when the line String strA = new String("Roasted "); is executed. This object is referenced by the variable strA.
  2. When String strB = strA; is executed, no new object is created. Instead, strB now references the same object as strA.
  3. Similarly, strC, strD, and strE all reference the same object as strA. No new objects are created.

Therefore, a total of 1 object is created.

After the last statement has executed, a total of 1 object is accessible. This is because all the variables strA, strB, strC, strD, and strE are referencing the same object.

User Davir
by
7.7k points