Vinay Dinakar wrote:what i can see from this example
is that, line1 creates one object in heap ("abc") and in line 2, "def" goes to string constant pool and sb (line 1 's object) value gets modified. so total 2 objects. line 3 does not have any effect.
My understanding is that "abc" creates a String Literal (Obj1) , and it's value is transfered to the StringBuffer (object 2) , "def" creates a 3rd object (another String Literal)(Obj3), but is appended to the sb object rather than creating a new "abcdef" String. Line 3 does not create a new object.
So thats 3 objects. If the code was
Then we would have 4 String objects. The String sb is a String reference (OBJ1), "abc" is a literal that is copied to the reference(OBJ2). When we create a 3rd string "def"(OBJ3) and a 4th string "abcdef"(OBJ4) which is assigned to the String Reference variable sb. In this example you would have 4 object and 3 String Literals in the String Constant Pool.
Someone feel free to jump in if I am not correct.