Java: String Builder

Anton Suprun
2 min readJun 15, 2021
Photo by Blake Connally on Unsplash

In Java, as is the case with most programming languages, strings are immutable; once a string is initialized with a value, it cannot be changed.

StringBuilder

What is it and when should I use it?

Take a look at the following code for instance:

Figure 1: Inefficient example

At first glance, it looks as though we are just extending our string with a three concatanations at each iteration of our loop. However, that is not the case!

Since strings are immutable, each time we add on to myVeryLongString, we allocate memory for a new String object.

This takes up a lot of unnecessary memory and the process of allocating memory at each iteration of the loop slows down your program. So, don’t do this!

A more efficient approach is to use the StringBuilder object:

Figure 2: Using a StringBuilder object

Internally, StringBuilder object is treated like a variable-length array which contains a sequence of characters. The biggest advantage is that the length and content of the StringBuilder object can be modified at any point in the program without allocating unnecessary memory.

Oracle has great documentation on all the built-in methods that the StringBuilder class offers; it’s short and concise, I suggest you check it out if you’re interested in learning a bit more about the StringBuilder details.

One of the great things about the StringBuilder class is that the append and insert methods are overloaded; they accept any type of data in the arguement and converts that data type to a String and appends/inserts that characters of. that String object to the StringBuilder. See in Figure 3 below just some of the data types a StringBuilder object can accept:

Figure 3: StringBuilder can accent arguments of type String, int, bool and more

Hope you learned something new !

--

--