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.
public class StringBufferMethodDemo
{
 public static void main(String args[])
 {
   StringBuffer sb = new StringBuffer("Hello");

   String str = "World";
   int x = 10;
   double d1 = 10.5;
   boolean b1 = true;
   java.util.Date today = new java.util.Date();

   sb.append(str);         // appends strng
   sb.append(x);           // appends int value
   sb.append(" ");         // appends an empty space
   sb.append(d1);          // appends double
   sb.append(b1);          // appends boolean
   sb.append("\n");        // appends new line or line break
   sb.append(today);       // appends Date object

   System.out.println(sb); // now print sb object
 }
}


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 Comment

Your email address will not be published.