108k views
3 votes
Examine the following section of code:

String strA = new String("Roasted ");
strA = new String("Toasted ");
strA = new String("Fried ");
strA = new String("Baked ");
strA = 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 Sirmak
by
7.8k points

1 Answer

4 votes

Final answer:

Five objects are created in total, but after the last statement, only the "Beans " object is accessible. The others are eligible for garbage collection.

Step-by-step explanation:

The code provided illustrates the creation of several string objects in Java. Five objects are created in total, one for each new String instantiation. These strings are "Roasted ", "Toasted ", "Fried ", "Baked ", and "Beans ". However, after the last statement has executed, only one object, "Beans ", is accessible. The previous strings created by 'new String(...)' are no longer accessible as they have been replaced in the reference variable strA. These inaccessible objects are eligible for garbage collection in Java.

In the given code, each time a new String object is created, the previous object is replaced, resulting in a total of 5 objects created. However, after the last statement has executed, only the last object 'Beans' is accessible. The previous objects are no longer accessible and can be considered as garbage.

User CMOS
by
8.0k points