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

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

User Wooncherk
by
9.3k points

1 Answer

3 votes

Final answer:

Five String objects are created and all are accessible after the last statement since each one is assigned to a unique variable. None of these objects are eligible for garbage collection.

Step-by-step explanation:

When we examine the code provided, we can count the number of objects created by looking at the number of new String instantiations. There are five separate statements creating new String objects, so a total of five objects are created:

  • new String("Roasted ")
  • new String("Toasted ")
  • new String("Fried ")
  • new String("Baked ")
  • new String("Beans ")

After the last statement has executed, all five objects remain accessible because each one is assigned to a unique variable (strA, strB, strC, strD, strE), and none has been dereferenced or fallen out of scope. As such, no objects are eligible for garbage collection at this point. Thus, five objects have been created, and all five are accessible after the last statement has executed.

User Annika
by
7.9k points