Java String Handling

Java StringBuilder Add to Front Example (StringBuffer)

Java StringBuilder add to front Example (StringBuffer) example shows how to add or prepend text to front of the StringBuilder object. Example also shows how to insert text at beginning of the StringBuilder/StringBuffer object.

How to insert text at beginning of the StringBuilder in Java (add to front)?

Java StringBuilder class provides various append methods to add text to the StringBuilder at the end. However, in some situations you might want to add text to front or beginning of the StringBuilder object.

In such cases, you can use insert method of the StringBuilder class. The insert method inserts specified text at the specified index of the StringBuilder object.

This insert method inserts the specified character sequence at the specified location in the StringBuilder. To add to front or beginning of the StringBuilder object, we will specify index as 0 as given in below example.

Output

As you can see from the output, string “Zero” is added to the front or the beginning of the StringBuilder object.

The insert method of the StringBuilder class is overloaded to insert various data types like int, char, long, float, double, boolean, character array etc.

Depending upon the particular use case, there is also another method to prepend text to StringBuilder as given in below example.

Output

Above given approach first reverses the StringBuilder object. It then reverses all the strings which are to be added to front and appends them to the StringBuilder object. At the end it reverses the entire StringBuilder object.

Above example also works for StringBuffer as they have similar API.

Please also see how to add element at front of the ArrayList example. Visit Java StringBuilder and StringBuffer examples to learn more.

References:
StringBuilder JavaDoc
StringBuffer JavaDoc

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.