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

Docker Monitoring Stack with Grafana

【2019】Monthly Project Report in July 2019

Easy Web Scraping using Python and BeautifulSoup4 and saving files as well HTML pages as PDF

Lucky NFT Coming To Binance NFT Market

Making Your Own JavaScript Linter (part 1)

String Hashing (MondayAlgo #8)

The One Number You Need to Explain: Net Promoter Score

生產力爆棚神器新登場 亞果元素全新iPad 磁吸支架上市

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

Coding Standards in Java.

Object Oriented Programming with Java

Java Design Patterns: Observer

Conversion Between Array and ArrayList in Java