The secrets of Java String concatenation – J051

by Nov 7, 2016




DeegeU Java Course

“The secrets of Java String concatenation” video is part of a larger free online class called “Free Java Course Online”. You can find more information about this class on “Free Java Course Online” syllabus.

Transcript – The secrets of Java String concatenation

Hi there! In this tutorial we’re going to look at Java string concatenation. Concatenation is taking two strings, and making them one. There’s several ways to do this, each with their own advantages and disadvantages.

How to concatenate Java Strings

When building applications, we’ll need to join some static message with a dynamic message. For example, maybe we need to prepare a greeting in our application. This way we can say “Hello, George” instead of just a simple “Hello”.

String helloString = "Hello ";
String nameString = "George";
String joinedString = helloString + nameString;
System.out.println(joinedString);

To do that, we could create two strings. The first string is just “Hello”. The second string we might read from an application setting or database. For this example we’ll just set it to “George”.

To join two strings, we use the plus operator. It’s that simple. We can also use the plus assignment operator, like this. joinedString now equals “Hello George”.

String nameString = "George";
String joinedString = "Hello " + nameString;
System.out.println(joinedString);

We might not need to create a variable “Hello”. It depends on our application, but we could replace the variable with a string literal like this. The result is still “Hello George”.

Analysis of Java String concatenation (instances)

Let’s look at what happened in our example. We have a string instance of “Hello”. It doesn’t matter if we use a literal or a variable, in both cases the string is interned. And we have a string for the name “George”. That’s two string instances in memory.

When we create the new string, “Hello George”, that’s a third string instance. Remember, strings are immutable. We can’t change strings, we can only create new ones. Now if we never use the “Hello” string, Java will eventually clear the instance from memory. Yet we can run into problems with memory and performance if we create too many strings.

Java String interning in the String pool when you concatenate strings.

Java String interning in the String pool when you concatenate strings.


Imagine if we were creating a log file. In our loop, we want to add to our string a log entry. We’ll keep the message simple. We’ll just say “visit number ” and the number of the visit.

So in this code we have one string for “visit number “. Then we create a string for that particular number. So “visit number 1”, “visit number 2”, and so on are newly created strings in the string pool.

Then we add it to our log string, and here’s where we’ll see our string problem get out of control. We’re creating a new string every time we add a log entry. Every string is an individual immutable object instance. So we’re creating a ton of objects we use and then throw away. What we need is a String that we can change.

Java String concatenation with StringBuilder

And Java has just what we need. There’s another class for representing strings called StringBuilder. This class gives you a collection of string manipulation methods. It also gives us a string which is modifiable. Since Java manipulates the string on the heap, it doesn’t enter the string pool.

There’s another class called StringBuffer which is similar, but it’s thread safe and slower. We’ll want to use the StringBuilder for most programs, unless we need the thread safety.

So in our original example, we could build a string like this. Then when we’re ready, we call toString and our StringBuilder returns a single string. But for this example, we’re not saving much. The StringBuilder helps us more when we’re building longer strings.

What Java 6+ is really doing for string concatenation

When we look at older Java code, we’re likely to see StringBuffers everywhere. In not so old code, StringBuilders. The reason is everyone was taught to use these classes when building strings. In Java 6, this changed a bit.

The people who make Java decided to force everyone down the path of StringBuilders. This prevented people from doing stupid things, like creating millions of string instances.

Since Java 6, Java uses a StringBuilder behind the scenes when we compile simple string concatenation. So there isn’t any difference in performance using this code or the StringBuilder code. Concatenation is simpler to read, so everyone has gone back to just using the plus operator.

Not out of the woods

But of course, it’s not that simple. Let’s go back to our logging example to see what’s happening there. If we use simple string concatenation, this is what Java is changing it to. So we’re creating StringBuilders in every loop. That’s a thousands StringBuilders and strings. And it’s not helping us, since we still create the log string over and over again.

What we’d need to do is move the creation of the StringBuilder outside our loop. This means we’re only creating one StringBuilder. We’re adding our single “visit number ” string, directly to the builder. At the end, we convert the builder to one string. This is much more efficient!

The key point here is we need to be aware about how many instances we create when concatenating strings. For small programs it’s usually not a big deal, but once we start concatenating strings in loops we can run into problems.

Using Java String.format

The last way to concatenate strings is to use the String.format method on the String class. This method gives us much more control over how we assemble our strings.

For example if we wanted to print the page number at the bottom of every page, we can specify the format of our string. We could use concatenation, but imagine our requirements are to provide many different formats for the page message.

We might say page one of two. Or maybe the message is “of the 2 pages this one is number 1”, or any other message you think of. We can create a long case statement for formatting, but someone will always come up with more cases.

The simpler way is to pass a format string, and then the objects we want to add to the string in order. This gives us complete flexibility on how we combine our strings.

This power comes at a price. It’s slower. Much slower. We’ll see String.format used on strings needing localization for a particular language. Sometimes it’s because we want to control the formatting of the individual parts of our string. We’ll cover String formatting more in a future lesson.

Conclusion

So that’s is Java string concatenation. We looked at how we can combine strings, how StringBuilders help us build dynamic strings, how concatenation works in current versions of Java, and why we need to pay attention to how Java combines our strings. If you have any questions, add them to the comments below.

If you enjoyed the video, please share and like. And with that, I’ll see you in the next tutorial!

<p><script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- DeegeU - Right Side -->
<ins class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-5305511207032009" data-ad-slot="5596823779"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></p>

Tools Used

  • Java
  • NetBeans

Media Credits

All media created and owned by DJ Spiess unless listed below.

  • No infringement intended

Get the code

The source code for “The secrets of Java String concatenation” can be found on Github. If you have Git installed on your system, you can clone the repository by issuing the following command:

 git clone https://github.com/deege/deegeu-java-intro.git

Go to the Support > Getting the Code page for more help.

If you find any errors in the code, feel free to let me know or issue a pull request in Git.

<h2>Don't miss another video!</h2> <p>New videos come out every week. Make sure you subscribe!<br><script src="//apis.google.com/js/platform.js"></script></p> <div class="g-ytsubscribe" data-channel="deegeu" data-layout="full" data-count="default"></div> <p></p>

Comments

comments

DJ Spiess

DJ Spiess

Your personal instructor

My name is DJ Spiess and I'm a developer with a Masters degree in Computer Science working in Colorado, USA. I primarily work with Java server applications. I started programming as a kid in the 1980s, and I've programmed professionally since 1996. My main focus are REST APIs, large-scale data, and mobile development. The last six years I've worked on large National Science Foundation projects. You can read more about my development experience on my LinkedIn account.

Pin It on Pinterest

Share This