How to concatenate strings in Java

Key takeaways:

  • String concatenation combines multiple strings into a single new string.

  • It’s useful in creating file paths, personalizing content, constructing URLs, bioinformatics (DNA/protein sequences), etc.

  • Here are some Java string concatenation methods:

    • Using the + or += operator: Simplest method, modifies the original string

    • Using concat() method: Returns a new string with the appended string

    • Using StringBuilder class: Efficient for frequent modifications, appends strings without creating new objects

    • Using format() method: Formats strings with placeholders and values

    • Using String.join() method (Java 8+): Joins multiple strings with a delimiter

What do generative AI, website generators, and error alerts share? They merge strings to form meaningful text. String concatenation is a fundamental operation in many programming languages that combines two or more strings to form a new string by subsequently appending the next string to the end of the previous strings.

Java strings concatenation
Java strings concatenation

It is difficult to think of a domain that doesn’t require string concatenation in one of its steps, e.g., web developmentdata science, and user interface development, to name just a few, wouldn’t be possible without it. Several applications rely on concatenating strings:

  • Creating file paths: Merging the name of the file path with its file name

  • Personalized content: Creating customized messages or alerts based on the user input

  • URL construction: Creating URLs based on the dynamic parameters and user input

  • Natural language processing (NLP): Constructing sentences or phrases from individual words

  • Bioinformatics: Joining DNA or protein sequences for comparison and analysis

Java string concatenation

James Gosling highlights the importance of versatility and simplicity in Java’s design. The following five string concatenation methods exemplify his perspective by providing an intuitive and straightforward way to concatenate strings:

Method 1: Concatenate strings using the + or += operator

The program below demonstrates how to concatenate two strings using the + or += operator in Java. The += operator modifies the original string variable by adding another string to it.

class HelloWorld {
public static void main( String args[] ) {
String first = "Hello";
String second = "World";
String third = first + second;
System.out.println(third);
// yet another way to concatenate strings
first += second;
System.out.println(first);
}
}

Note: As per the official Java documentation, when you use + or += to concatenate a string with a reference to an object in Java, the reference will automatically be converted into a string using the object's toString() method. If the object or its toString() method returns null, the string "null" will be used instead.

Method 2: Concatenate strings using the concat() method

The concat() method is a member of the String class and is used to concatenate the specified string to the end of the current string.

Syntax

The signature of the concat() method is shown below:


String concat(String stringToConcat)

Parameter

stringToConcat is the string to be concatenated. It will be appended at the end of the string object calling this method.

Return type

The concat() method returns the concatenated string.

The program below demonstrates the concatenation using the String.concat() method with two strings in Java:

class HelloWorld {
public static void main( String args[] ) {
String first = "Hello";
String second = "World";
String third = first.concat(second);
System.out.println(third);
}
}

Note: You can also directly concatenate the strings within the println() method itself as System.out.println(first + second); or System.out.println(first.concat(second));.

Method 3: Concatenate strings using the StringBuilder class

StringBuilder class is an efficient way to concatenate strings in Java. It allows us to modify strings without creating intermediate string objects. We can use the StringBuilder class to create the first string and then append it to another string using the append() method. After creating the desired string this way, we can use the toString() method to convert it back to a string if needed.

class HelloWorld {
public static void main( String args[] ) {
StringBuilder sb = new StringBuilder("Educative");
sb.append(" Platform.");
String concatenateStr = sb.toString();
System.out.println(concatenateStr);
}
}

Method 4: Concatenate strings using the format() method

The format() method in Java allows us to concatenate strings using the format specifier. The following example demonstrates how to concatenate strings using the format() method:

class HelloWorld {
public static void main( String args[] ) {
String second = "Platform";
String concatenateStr = String.format("Educative %s", second);
System.out.println(concatenateStr);
//concatenate three strings
String firstvar = "Hello";
String secondvar = "Java";
String thirdvar = "World";
// Using String.format() to concatenate and format the strings
String concatenateStr2 = String.format("%s %s %s", firstvar, secondvar, thirdvar);
// Output the result
System.out.println(concatenateStr2);
}
}

Method 5: Concatenate strings using the String.join() method

The String.join() method (introduced in Java 8) is used to join multiple strings with a specified delimiter. The following example demonstrates how to concatenate strings using the String.join() method:

class HelloWorld {
public static void main( String args[] ) {
String concatenateStr = String.join(" ", "Educative", "Platform.");
System.out.println(concatenateStr);
}
}

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How do we concatenate two strings in Java?

We can concatenate two strings in Java using the various methods as listed below:


How can we append three strings in Java?

We can append three strings in Java simply by using the + operator. Here’s a code example:

String first = "Hello";
String second = "Java";
String third = "World";
String result = first + " " + second + " " + third;


How do we concatenate strings with numbers in Java?

We can concatenate strings with numbers using the + operator:

String strnew = "The number is ";
int number = 20;
String concatenateStr = strnew + number; // result will be "The number is 20"
System.out.println(concatenateStr);


How do we check if two strings are equal in Java?

The equals() method in Java is invoked every time a string is compared with another string to see if they’re equivalent to each other or not.

String first = "educative";
String second = "educative";
boolean isEqual = first.equals(second);
System.out.println(isEqual);


How do we concatenate two strings in C#?

We can concatenate two strings in C# using the + operator. You can visit our Answer for its implementation: How to concatenate two strings in C#.


How do we concatenate two strings in Python?

We can concatenate two strings in Python using various methods as listed below:

  • Using the + operator
  • Using the % operator
  • Using the join() method
  • Using the format() method
  • Using the , comma
  • Using the f-string
  • Using the * operator
  • Using the loops and the += operator

You can visit our Answer for the details of each method: How to concatenate strings in Python.


What’s the difference between StringBuilder and StringBuffer?

There are multiple differences between StringBuilder and StringBuffer. Some of them are listed below:

  • StringBuffer is synchronized while StringBuilder is non-synchronized.

  • StringBuffer is thread-safe, meaning that two threads can’t call the string buffer at the same time, while StringBuilder is not thread-safe, meaning that two threads can call the string buffer at the same time.

  • StringBuffer is less efficient than String Builder.

You can visit our detailed answer on What are the differences between StringBuilder and StringBuffer?.


Free Resources