Lesson 9: String Concatenation and Using StringBuilder in Java

Introduction

Hello, everyone! Today, we’ll talk about working with strings in Java. Specifically, we’ll learn how to combine (concatenate) strings and use memory efficiently when dealing with a lot of text. This is a very useful topic that you will need in all kinds of programs, from simple tasks to more complex projects.


1. What is a String in Java?

In Java, strings are sequences of characters. Strings are created using the String class.

If you want to review this, check out the article: “Reference Types in Java – Strings.”

Example:

String hello = "Hello";
String world = "World";

2. String Concatenation

2.1 The Simplest Way: Using the + Operator

The + operator allows you to combine strings easily:

String firstName = "John";
String lastName = "Smith";
String fullName = firstName + " " + lastName;
System.out.println(fullName); // Output: John Smith

2.2 Using the += Operator

If you need to add something to an existing string, you can use the += operator:

String greeting = "Hello";
greeting += ", World!";
System.out.println(greeting); // Output: Hello, World!

3. Problems with the + Operator

At first, everything seems simple, but there’s a catch. Since strings in Java are immutable (unchangeable), every operation with + creates a new string. The old string stays in memory until the Garbage Collector removes it (if there are no references to it).

This leads to inefficient memory use, especially if you concatenate strings a lot, for example, inside loops.

Example in a loop:

String result = "";
for (int i = 0; i < 10; i++) {
    result += i; // A new string is created at every step
}
System.out.println(result); // Output: 0123456789

Here, the program creates a new string every time it loops, which wastes memory and slows the program.


4. String Concatenation with the append() Method from StringBuilder

4.1 Efficient String Concatenation: StringBuilder

Instead of using the + operator, you can use the append() method from the StringBuilder class.

StringBuilder is a class in the Java library (article: “Classes and Objects) that provides methods for working with text. If you forgot what a class or method is:

  • A class is like a blueprint that groups together data and actions.
  • A method is a command that performs a specific task.

Using StringBuilder is like using ready-made tools. This saves you time because most programming problems can be solved with these standard tools.


4.2 How to Use StringBuilder

  1. Create a StringBuilder object.
  2. Add strings or characters using the append() method.
  3. Convert the result into a regular string using the toString() method.

4.3 What Do append() and toString() Do?

The append() Method

append() – a method that adds strings or characters to the end of the current StringBuilder object. You can add numbers, letters, words, and even other strings.

Example:

StringBuilder builder = new StringBuilder();
builder.append("Hello");
builder.append(" "); // Adding a space
builder.append("World");
System.out.println(builder.toString()); // Output: Hello World

The toString() Method

toString() – a method that converts the StringBuilder object into a regular String. This is useful when you need the final result as a string to use elsewhere or print on the screen.

Example:

StringBuilder builder = new StringBuilder();

builder.append("Hello"); // Adding the first part of the string
builder.append(", ");
builder.append("world!");
builder.append(" How are you?");

String result = builder.toString(); // Convert to a string
System.out.println(result); // Output: Hello, world! How are you?

5. When to Use + and When to Use StringBuilder?

Using the + Operator

The + operator is convenient for small numbers of strings or simple operations.

Example:

String message = "Hello" + ", " + "world!";
System.out.println(message); // Output: Hello, world!

Using StringBuilder

Use StringBuilder when you need to combine many strings efficiently. For example, when preparing text that will be saved into a file or sent somewhere.


Example: Preparing Text for a File

When working with files, StringBuilder helps you efficiently combine text, just like when you display it in the console. The only difference is that instead of using System.out.println() to display the result, you would use code to save this text into a file.

Here’s an example of how you prepare text with StringBuilder:

StringBuilder builder = new StringBuilder();
builder.append("First line\n");
builder.append("Second line\n");
builder.append("Third line\n");

// Displaying the combined text in the console
System.out.println(builder.toString());

Later, when you learn file handling, you will replace the console output with code that saves builder.toString() to a file. The process of preparing the text stays the same – you just change where the text is sent.


6. What Did We Learn Today?

  • StringBuilder is a ready-to-use tool created to optimize working with strings.
  • The append() and toString() methods make it easy to add parts of text and convert it to a string.
  • Use the + operator for small tasks and StringBuilder for larger tasks or preparing text for files or data streams.

7. Practical Task

Try building your own string using StringBuilder with words and symbols. For example, create this string:

“Java is interesting and useful!”

Head over to an Online IDE and type in your code. If it feels a little difficult, you can read the article: Java Program Structure: A Beginner’s Guide for extra help.

Hint:

StringBuilder builder = new StringBuilder();
builder.append("Java");
builder.append(" is ");
builder.append("interesting");
builder.append(" and useful!");
System.out.println(builder.toString());

Leave a Reply