Skip to content

Java StringBuilder Add to Front Example (StringBuffer)

Java StringBuilder add to front Example (StringBuffer) example shows how to add or prepend text to the front of the StringBuilder object. The 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 the 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 the front or beginning of the StringBuilder object, we will specify the index as 0 as given in the below example.

Output

As you can see from the output, the string “Zero” is added to the front or at 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 the below example.

Output

The above-given approach first reverses the StringBuilder object. It then reverses all the strings which are to be added to the front and appends them to the StringBuilder object. In the end, it reverses the entire StringBuilder object (reverse StringBuilder).

The above example also works for StringBuffer as they have a similar API.

Please also see how to add elements at front of the ArrayList example.

This example is a part of the Java StringBuffer tutorial and Java StringBuilder tutorial.

References:
StringBuilder JavaDoc
StringBuffer JavaDoc

About the author

Leave a Reply

Your email address will not be published.