append() StringBuffer Example

append() StringBuffer Example


StringBuffer, with its nature of mutability, comes with many methods that do not exist in String. One useful method is append() StringBuffer method which appends anything to the existing contents.

Following is the method signature of append() StringBuffer as defined in Java API.

  • public StringBuffer append(String str): String str is appended at the end of the contents existed in StringBuffer.

StringBuffer append() method is overloaded 13 times that takes all data types, char array and Object etc.

In the following append() StringBuffer example, different data types, strings and dates etc. are appended.


append() StringBuffer
Output screen of append() StringBuffer Example

How append() method works internally?

For example:

StringBuffer sb = new StringBuffer(“Hello”);
int x = 10;
double d1 = 10.5;

It does like this:
sb.append(Sting.valueOf(x)).append(String.valueOf(d1)).toString();

For every append, an object of StringBuffer is returned. On that returned StringBuffer object again append() is called. Each data appended calls String.valueOf() method to get its string representation. This helps to chain together the data of all append calls.

Leave a Reply

Your email address will not be published. Required fields are marked *