How many String objects are created
I am learning SCJP. I seem to be leaning towards this String problem. It seems that I see several possible answers depending on how I look at the question.
In the next initialization, how many string objects are created?
String s1 = "A" + "B" + "C" + "D"; System.out.println(s1)
At first I thought there were 5 objects, i.e.
"A" "B" "C" "D" "ABCD"
But then, thinking about this, I'm not sure, because, for example, the compiler will concatenate "A" + "B" as one object? those. create 7 objects?
"A" "B" "C" "D" "AB" "ABC" "ABCD"
In addition, how many objects will be created if the code has been changed to
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 that 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 connected? that is, the object mentioned from the constant pool will be different from the object referenced by the link to s2.
thanks
Edit
In addition, please note that I am interested in knowing the total number of objects created, including those that are discarded not only by those that end up in the constant pool.
Edit
Looking at John’s answer, I may have completely misunderstood how objects are created. I know that String is only created once in the constant pool, and it is reused, but I'm not sure about the process that goes through when the "final" string is built. Here is the section from the book that I am reading, which apparently involves the creation of temporary objects, which is completely opposite to the answers here. (Or maybe the book is wrong or I misunderstood the book)
Sample code 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 conclusion? For extra credit, how many String objects and how many reference variables were created before the println statement .
And the answer
The result of this code snippet is spring water spring summer . There are two reference variables, s1 and s2. There were eight in total String objects are created as follows: spring, summer (lost), spring summer, falling (lost), spring fall (lost), spring spring spring (lost), winter "(lost)," winter of winter "(currently" spring "lost). Only two out of eight String objects are not lost in this process.
thanks