String s1 = "spring"; // a reference is created in string pool String s2 = s1 + "summer"; // a reference is created in string poool and one object is created in heap s1.concat("fall"); // one object is created and it is available for Garbage collection s2.concat(s1); // one object is created and it is available for Garbage collection s1 += "winter"; // one object is created in heap System.out.println(s1 + " " + s2); // one object is created in heap
In the first line 2 objects will get created. In the second line 1 object will get created.
The explanation is something like this, When you specify a String as Literal, one object will get created in the heap and the reference will be put in the String pool. Then when you create a String object by "New" operator, specifically a new object will get created with the value provided in the argument.
String str = new String("mausam");
first "mausam" will get created and its reference will be placed in String literal pool when the class loads. And because of the "New" operator, a new object will get created and the reference will be given to "str".
in case of second statement, we dont have "New" operator. So, just reference of the String will be given.
Hope it will clarify your doubt, otherwise there is a good "Journal" post in JavaRanch itself, which will help you to clarify the concept.