0

Practice Test Question:

Consider the following code:

String entree = new String (“chicken”);
String side = “salad”;
entree = “turkey”;
String dessert;
entree = side;
String extra = entree + side;
dessert = “pie”;

How many String objects were created, and how many are accessible at the end?
How many aliases are present, and is there any garbage?

My logic: 3 literals created, one String with the new operator, and one concatenating entree and side, so 5 total objects.

dessert and extra is 2 objects, side and the 3rd assigning of entree. So 4 objects are accessible out of the 5 total created.

1 alias, entree refers to side.

Garbage, entree lost references to "turkey" and "chicken".

Could you help me assess my thought process on this question?

Rishi
  • 945
  • 2
  • 15
  • 23
  • Ignoring the discussion below, I suspect this is a "trick" question and they expect you to miss that `String entree = new String (“chicken”);` creates *two* objects. `"chicken" is a literal created in the string pool, and then the contents are copied. You have *four* literals created here. – Brian Roach Dec 15 '12 at 21:24

1 Answers1

1

The four literals will be created if they have not been created already.

The new String may create one or two new objects as a String contains a char[]

String literals are not freed until the class is unloaded.

When String + is used a StringBuilder, one or two char[], and a String are created.

String extra = entree + side;

can be translated into

String extra = new StringBuilder().append(entree).append(side).toString();

This means there is a new StringBuilder/String and one char[] each.

This means there is up to 6 objects which could be garbage collectioned.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    I wonder if the book/class asking the question expects you to include the transient objects inside the `StringBuilder`, heh. Or if they even know. – Brian Roach Dec 15 '12 at 21:01
  • Could you please elaborate? I do not understand your logic... Yeah, doesn't include the StringBuilder – Rishi Dec 15 '12 at 21:01
  • A String wraps a char[] which may or may not be created. – Peter Lawrey Dec 15 '12 at 21:02
  • @user1796994 - It's a poor question for a class/book to be asking. There's the answer they probably expect that only involves `String` objects, then there's the real answer which is far more complicated and requires an understanding of everything that's going on. And they used the word "aliases" which is just wrong. – Brian Roach Dec 15 '12 at 21:05