Vinay Dinakar wrote:Arent these string literal also objects ? then how 3 objects gets created, it should be only one right. if it is 3 objects, then whats the difference between string and stringbuffer !!! ?
If you were using String instead of String Buffer then even more objects would be created. This isn't the best example of a StringBuffer or evena StringBuilder in use though. Repeat the append about 20 times and it becomes more apparent.
One thing I wonder though, when you append a non string literal to a StringBuffer / Builder and it appends the string representation, does it still create a String literal that gets added to the pool? I would imagine it would but I don't know the answer.
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.
Look! I laid an egg! Why does it smell like that? Tiny ad, does this smell weird to you?