Select Page

How to Concatenate Strings in Java

James Payne
Published: January 5, 2023

Java Programming tutorials

String concatenation can be defined as the process of joining two or more strings together to form a new string. Most programming languages offer at least one way to concatenate strings. Java gives you several options to choose from, including:

  • the + operator
  • the String.concat() method
  • the StringBuilder class
  • the StringBuffer class

Today’s programming tutorial will cover how to use each of the above four ways to concatenate strings together as well as provide some tips on how to choose which is best in a given situation.

Want to learn Java in an online class environment? We have a list of the Top Java Courses to help you get started.

Using the Plus (+) Operator

This is the easiest and most often employed way to concatenate strings in Java. Placing the plus (+) operator between two or more strings will combine them into a brand new string. Hence, the String object produced by concatenation will be stored in a new memory location in the Java heap. However, if a matching string already exists in the string pool, a reference to the found String object is returned. You can think of that as a form of caching. Here is a quick code example of the + operator at work in Java:

String firstName = "Rob";
String lastName  = "Gravelle";
// Outputs "Rob Gravelle"
System.out.println(firstName + " " + lastName);

Advantages of the Plus (+) Operator: Automatic Type Conversion and Null Handling

The + operator automatically converts all native types into their string representations, so it can handle everything from ints, floats, and doubles to single (char) characters. Moreover, it does not throw any exceptions for Null values, converting Null into its String representation as well. Here is some example code showing how to use the + operator in Java for string concatenation:

String fruits = "apples";
int howMany = 4;
String other = null;
// Outputs "I have 4 apples as well as null."
System.out.println("I have " + howMany + " " + fruits + " as well as " + other + ".");

Behind the scenes, the + operator silently converts non-string data types into a String using implicit type conversion for native types and the toString() method for objects, which is how it avoids the NullPointerException. The only downside is that we wind up with the word “null” in the resulting string, which may not be what developers want.

String concatenation is implemented through the append() method of the StringBuilder class. The + operator produces a new String by appending the second operand onto the end of the first operand. In the case of our previous example, here is what Java is doing:

String s = (new StringBuilder())
             .append("I have ")
             .append(howMany)
             .append(" ")
             .append(fruits)
             .append(" as well as ")
             .append(other)
             .append(".")
               .toString();  

Java String Concatenation Tips

Always store the String returned after concatenation using the + operator in a variable if you plan on using it again. That will avoid programmers having to go through the concatenation process multiple times. Also, avoid the use of the + operator for concatenating strings in a loop, as that will result in a lot of overhead.

While convenient, the + operator is the slowest way to concatenate strings. The other three options are much more efficient, as we will see next.

Read: Java Tools to Increase Productivity

Using the String.concat() Method

The String concat method concatenates the specified string to the end of current string. Its syntax is:

@Test
void concatTest() {
String str1 = "Hello";
String str2 = " World";
assertEquals("Hello World", str1.concat(str2));
assertNotEquals("Hello World", str1); // still contains "Hello"
}

We can concatenate multiple String by chaining successive concat invocations, like so:

void concatMultiple() {
String str1 = "Hello";
String str2 = " World";
String str3 = " from Java";
str1 = str1.concat(" ").concat(str2).concat(str3);
System.out.println(str1); //"Hello World from Java";
}


Note that neither the current String nor the String to be appended can contain Null values. Otherwise, the concat method throws a NullPointerException.

StringBuilder and StringBuffer Classes

The StringBuilder and StringBuffer classes are the fastest way to concatenate Strings in Java. As such, they are the ideal choice for concatenating a large number of strings – especially in a loop. Both of these classes behave in much the same way, the main difference being that the StringBuffer is thread-safe whereas the StringBuilder is not. Both classes provide an append() method to perform concatenation operations. The append() method is overloaded to accept arguments of many different types like Objects, StringBuilder, int, char, CharSequence, boolean, float, double, and others.

I addition to performance benefits, the StringBuffer and StringBuilder offer a mutable alternative to the immutable String class. Unlike the String class, which contains a fixed-length, immutable sequence of characters, StringBuffer and StringBuilder have an expandable length and modifiable sequence of characters.

Here is an example that concatenates an array of ten integers using StringBuilder and StringBuffer:

import java.util.stream.IntStream;
import java.util.Arrays;

public class StringBufferAndStringBuilderExample {
  public static void main(String[] args) {
    // Create an array from 1 to 10
    int[] range = IntStream.rangeClosed(1, 10).toArray();
    
    // using StringBuilder
    StringBuilder sb = new StringBuilder();
    for (int num : range) {
      sb.append(String.valueOf(num));
    }
    System.out.println(sb.toString()); // 12345678910
    
    // using StringBuffer
    StringBuffer sbuf = new StringBuffer();
    for (int num : range) {
      sbuf.append(String.valueOf(num));
    }
    System.out.println(sbuf.toString()); // 12345678910
  }
}

Final Thoughts on Java String Concatenation

In this programming tutorial, we learned all about Java’s four main ways to concatenate Strings together, along with tips on how to choose which is best in a given situation. To summarize, when you need to choose between the + operator, concat method, and the StringBuilder/StringBuffer classes, consider whether you are dealing with Strings exclusively or a mix of data types. You should also think about the possibility of NullPointerExeptions on Null values. Finally, there is the question of performance and mutability. The + operator is the slowest of all the options seen here today, while the StringBuilder and StringBuffer classes are both fast and mutable.

If you really want to look at all concatenation options in Java, version 8 introduced even more ways to concatenate Strings, including the String.join() method and the StringJoiner class. Version 8 also saw the introduction of Collectors. The Collectors class has the joining() method that works very much like the join() method of the String class.

Read more Java programming tutorials and software development tips.

Source: www.developer.com