Java: String Builder

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.


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 !




Computer Science Student, Programming Enthusiast

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Visual Studio Code AutoComplete

MCUXPresso Usage

Weekly R&D update #8 Dec.20–26

Docker, .NET Core 5.0, Angular 11, Nginx and Postgres on the Google Cloud Platform — Pt 1

.Net 6 WebAPI — Intro to ElasticSearch — Step by Step #aspnetcore

Send Emails from Salesforce using Email Service Address.

Swift iOS Development: How to Pass Data from One Screen to Another

Connect Excel with Python

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
Anton Suprun

Anton Suprun

Computer Science Student, Programming Enthusiast

More from Medium

Java coding for kids.

Java Maps- My toolbox

Things to know about Java Collection

Object Oriented Programming with Java