How many string objects will be created in memory?

java, memory, object, string

Solution

I'll anwser to another, clearer question: how many String instances are involved in the following code snippet:

String s="";
s+=new String("a");
s+="b";

And the answer is 6:

- the empty String literal: `""`;

- the String literal `"a"`;

- the copy of the String literal "a": `new String("a")`;

- the String created by concatenating `s` and the copy of `"a"`;

- the String literal `"b"`

- the String created by concatenating `s` and `"b"`.

If you assume that the three String literals have already been created by previously-loaded code, the code snippet thus creates 3 new String instances.

Problem

How many string objects will be created by the following code? ``` String s=""; s+=new String("a"); s+="b"; ``` I had this question at exam. I want to know the right answer . I said 2 objects. The object from pool that contains "" , "b" and the object created by new String("a");

Original source