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?
First there is a problem with your question:
Correct, two Objects are created, the String “orange” and the String “apple”, inside the StringBuffer/StringBuilder no Objects will be created if we don’t overflow the buffer. So those lines of code create 2 or 3 objects.
I don’t know where you get that, here you create one StringBuilder Object, one “Orange” String, one “apple” String, for a total of 3 Objects, or 4 if we overflow the StringBuilder buffer. (I count the array creation as object creation).
I read your question as, how can StringBuilder do the append without creating a new Object (when the buffer is not overflown)?
You should look at
StringBuilder, since it’s the non thread safe implementation. The code is interesting and easy to read. I’ve added the inline comments.As internal structure there is a char array, not a String. It is initially built with length 16 and will be increased every time the capacity is exceeded. If the Strings to append fit within the char array, there is no need to create new Objects.
StringBuilderextendsAbstractStringBuilder, where you’ll find the following code:Since not all the array will be used at a given time, another important variable is the length:
There are many overloading of append, but the most interesting one is the following:
So, the append method is quite simple, the only magic left to discover is the
expandCapacity, here it is:In our case, padding, since we’re expanding the length.