What is the StringBuffer.append() method in Java?

Introduction

In Java, StringBuffer.append() is a method in the StringBuffer class. It is used to append a string to the end of an existing string buffer. This allows us to easily add new text to a current string without creating a new object.

The append() method returns a reference to the same object so that we can can chain multiple append() calls together. This can be useful for creating long strings from various smaller strings.

Syntax

The syntax for the append() method is as follows:

public StringBuffer append(String str)
Syntax of the append() method

Parameters

str: This is the string that has to be appended to the end of the buffer.

Return value

The return value will be a reference to this object.

Overloaded versions

The append() method is overloaded, which means that there are multiple versions of it that you can use. Below, we have various overloaded versions of this method in the StringBuffer class:

class StringBuffer{
public StringBuffer append(boolean b)
public StringBuffer append(char c)
public StringBuffer append(char[] str)
public StringBuffer append(char[] str, int offset, int len)
public StringBuffer append(double d)
public StringBuffer append(float f)
public StringBuffer append(int num)
public StringBuffer append(long lng)
public StringBuffer append(Object obj)
public StringBuffer append(String str)
public StringBuffer append(StringBuffer sb)
}

These versions of the append() method take different types of arguments, such as boolean, char, double, float, long, int, Object, String, and StringBuffer. This can be useful for creating strings that contain dynamic data.

You can read more about the StringBuffer class in the Java API documentation.

Code example

The following example shows us how to use the append() method:

class HelloWorld {
public static void main( String args[] ) {
StringBuffer sb = new StringBuffer("Educative ");
sb.append("Answers");
System.out.println(sb); // prints "Educative Answers"
}
}

Code explanation

In the code above, we create a new StringBuffer object with the initial value of "Educative ". We then call the append() method to add "Answers" to the end of the string. Finally, we print out the resulting string.

As we can see from the output, the two strings are concatenated together into a single string.

Conclusion

In this Answer, we looked at the append() method in the StringBuffer class. This is useful for adding new text to an existing string buffer. We also looked at a simple example of how to use this method.

Free Resources