How to Concatenate Strings in Java: Simple Guide
In Java, you can concatenate strings using the
+ operator or the concat() method. For better performance when joining many strings, use StringBuilder with its append() method.Syntax
There are three common ways to join strings in Java:
String result = str1 + str2;uses the plus operator to join two strings.String result = str1.concat(str2);calls theconcat()method on a string.StringBuilder sb = new StringBuilder(); sb.append(str1).append(str2); String result = sb.toString();usesStringBuilderfor efficient concatenation.
java
String result1 = "Hello" + " World"; String result2 = "Hello".concat(" World"); StringBuilder sb = new StringBuilder(); sb.append("Hello").append(" World"); String result3 = sb.toString();
Example
This example shows how to concatenate strings using the plus operator, concat() method, and StringBuilder. It prints the results to the console.
java
public class StringConcatExample { public static void main(String[] args) { String str1 = "Hello"; String str2 = "World"; // Using + operator String result1 = str1 + " " + str2; // Using concat() method String result2 = str1.concat(" ").concat(str2); // Using StringBuilder StringBuilder sb = new StringBuilder(); sb.append(str1).append(" ").append(str2); String result3 = sb.toString(); System.out.println(result1); System.out.println(result2); System.out.println(result3); } }
Output
Hello World
Hello World
Hello World
Common Pitfalls
One common mistake is using the + operator repeatedly in loops, which creates many temporary strings and slows down the program. Instead, use StringBuilder for better performance.
Also, concat() only accepts one string argument, so chaining multiple concatenations requires multiple calls.
java
public class WrongConcat { public static void main(String[] args) { String result = ""; for (int i = 0; i < 3; i++) { // Inefficient: creates new string each loop result = result + i; } System.out.println(result); // Better way: StringBuilder sb = new StringBuilder(); for (int i = 0; i < 3; i++) { sb.append(i); } System.out.println(sb.toString()); } }
Output
012
012
Quick Reference
Use this quick guide to choose the right concatenation method:
| Method | Usage | Best for |
|---|---|---|
| + operator | Simple joining of few strings | Quick and readable code |
| concat() | Joining two strings | When chaining few strings explicitly |
| StringBuilder | Joining many strings or in loops | Efficient and fast concatenation |
Key Takeaways
Use the + operator or concat() method for simple string joining.
Prefer StringBuilder when concatenating strings inside loops for better performance.
concat() only accepts one string argument at a time.
Repeated + operations in loops create many temporary strings and slow down your program.
StringBuilder's append() method is efficient and recommended for multiple concatenations.