Alex Rivera | Logout

How is StringBuffer implementing append function without creating two objects?

Asked 2011-11-04T15:05:38.410
28

It was an interview question. I was asked to implement the StringBuffer append function. I saw the code after the interview. But I cannot understand how the operation is done with creation of a single object.

I am thinking like this.

String s = "orange";
s.append("apple");

Here two objects are created.

But

StringBuilder s = new StringBuilder("Orange");
s.append("apple");

Now here only one object is created.

How is Java doing this operation?

Edit
Report

4 Answers

4

String is immutable. Appending a string can only generate a new string.

StringBuilder is mutable. Appending to a StringBuilder is an in-place operation, like adding to an ArrayList.

answered 2011-11-04T15:08:01.457
4

This doesn't compile.

String S= "orange";
S.append("apple");

if you do

final String S= "orange";
final S2 = S + "apple";

This doesn't create any objects as it is optimised at compile time to two String literals.

StringBuilder s = new StringBuilder("Orange");
s.append("apple");

This creates two objects StringBuilder and the char[] it wraps. If you use

String s2 = s.toString();

This creates two more objects.

If you do

String S= "orange";
S2 = S + "apple";

This is the same as

String S2 = new StringBuilder("orange").append("apple").toString();

which creates 2 + 2 = 4 objects.

answered 2011-11-04T15:13:27.237
1

StringBuilder is holding a buffer of chars in a char[] and converting them to a String when toString is called.

answered 2011-11-04T15:11:32.820
-1
****String s1="Azad"; ----One object will create in String cons. pool

System.out.println(s1);--output--Azad

s1=s1.concat("Raja");  Two object will create 1-Raja,2-AzadRaja and address of AzadRaja Store in reference s1 and cancel ref.of Azad object 

System.out.println(s1);  --output AzadRaja****
answered 2012-02-28T20:38:35.847

Your Answer