How many String object are created
I am studying for the SCJP I cant seem to get my head round this String problem. I seem to see several possible answers depending on how i look at a question.
In the following initialization, how many string objects are created?
String s1 = "A" + "B" + "C" + "D";
System.out.println(s1)
Initially i thought 5 objects, i.e.
"A"
"B"
"C"
"D"
"ABCD"
But then thinking about it i am not really sure because for example will the compiler concatenate "A" + "B"
as one object? i.e creating 7 objects?
"A"
"B"
"C"
"D"
"AB"
"ABC"
"ABCD"
Also, how many objects will be created if the code was changed to be
String s1 = new String("A" + "B" + "C" + "D");
System.out.println(s1);
And finally how about:
String s1 = "A";
String s2 = new String("A");
In the above example i think only 2 objects will be created
object 1 - "A"
object 2 - a String object that refers to the "A" object above.
Is this correct or will they not be related? i.e. the object referred to from the constant pool will be different from the one referred to by the s2 reference.
Thanks
Edit
Also, please note i am interested in knowing the total number of objects created including those that are discarded not just those that eventually end up in the constant pool.
Edit
Looking at Jon's answer i might have totally misunderstood the way the objects are created. I know that a String is created only once in the constant pool and it is reused but im not sure of the process that goes through when the 'final' string is constructed. Here is the section from the book i am reading which seems to suggest that temporary objects get created which is a complete opposite to the answers here. (Or maybe the book is wrong or i misunderstood the book)
The code sample was
String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat("fall ");
s2.concat(s1);
s1 += "winter";
System.out.println(s1 + " " + s2);
The question was
What is the output? For extra credit, how many String objects and how many reference varibles were created prior to the println statement.
And the answer
The result of this code fragment is
spring water spring summer
. There are two reference variables, s1 and s2. There were a total of eight String objects created as follows "spring", "summer" (lost), "spring summer", "falls"(lost), "spring fall" (lost), "spring summer spring" (lost), "winter" (lost), "spring winter" (at this point "spring" is lost). Only two of the eight String objects are not lost in this process
Thanks
s1 = "A"; s2 = s1 + "B"
vs"A" + "B"
. The compiler turns the second one into"AB"
before anything ever runs. The first one runs as-is when you execute the code. – Leptospirosis