Java: String Builder

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.


What is it and when should I use it?

Take a look at the following code for instance:

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:

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:

Hope you learned something new !



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store