Introduction
String concatenation is fundamental in Java, but the + operator isn't the only way to combine strings. Understanding alternative methods is important for:
- Technical interviews
- Performance optimization
- Code readability
- Different programming scenarios
This guide explores six different methods to concatenate strings without using the + operator.
Method 1: Using concat() Method
The simplest alternative is the built-in concat() method provided by the String class.
public class StringConcatMethod {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = " World";
// Using concat()
String result = str1.concat(str2);
System.out.println(result);
// Multiple concatenations
String combined = "Java"
.concat(" is ")
.concat("awesome");
System.out.println(combined);
}
}
Output
Hello World
Java is awesome
Key Characteristics
- Returns a new
Stringobject. - Throws
NullPointerExceptionif the argument isnull. - Time Complexity: O(n + m), where n and m are the lengths of the two strings.
- Simple and easy to read.
Safe Implementation
public static String safeConcatenate(String str1,
String str2) {
if (str1 == null) {
str1 = "";
}
if (str2 == null) {
str2 = "";
}
return str1.concat(str2);
}
Method 2: Using StringBuilder
StringBuilder is the preferred choice when multiple concatenation operations are required.
public class StringBuilderConcatenation {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String result = sb.toString();
System.out.println(result);
}
}
Output
Hello World
Why StringBuilder Is Efficient
Less Efficient Approach
String result = "";
for (int i = 0; i < 1000; i++) {
result = result + i;
}
This creates many temporary String objects.
Recommended Approach
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i);
}
String result = sb.toString();
This modifies a single mutable object, making it significantly faster.
Common StringBuilder Methods
append()– Adds content to the end.insert()– Inserts content at a specified position.delete()– Removes characters.toString()– Converts the builder to aString.
Method 3: Using StringBuffer
StringBuffer works similarly to StringBuilder but is synchronized, making it thread-safe.
public class StringBufferConcatenation {
public static void main(String[] args) {
StringBuffer buffer = new StringBuffer();
buffer.append("Hello");
buffer.append(" ");
buffer.append("World");
System.out.println(buffer.toString());
}
}
Output
Hello World
StringBuilder vs StringBuffer
| StringBuilder | StringBuffer |
|---|---|
| Faster | Slightly slower |
| Not thread-safe | Thread-safe |
| Unsynchronized | Synchronized |
When to Use StringBuffer
Use StringBuffer when:
- Multiple threads modify the same object.
- Thread safety is required.
- Synchronization is important.
Otherwise, prefer StringBuilder.
Method 4: Using String.format()
String.format() combines formatting and concatenation.
public class StringFormatConcatenation {
public static void main(String[] args) {
String name = "Alice";
int age = 30;
String result =
String.format(
"Name: %s, Age: %d",
name,
age);
System.out.println(result);
String formatted =
String.format(
"%s is %d years old and from %s",
"Bob",
25,
"USA");
System.out.println(formatted);
}
}
Output
Name: Alice, Age: 30
Bob is 25 years old and from USA
Common Format Specifiers
| Specifier | Description |
|---|---|
%s |
String |
%d |
Integer |
%f |
Floating-point number |
%x |
Hexadecimal |
%b |
Boolean |
Method 5: Using String.join()
String.join() joins multiple strings using a delimiter.
import java.util.Arrays;
import java.util.List;
public class StringJoinConcatenation {
public static void main(String[] args) {
String[] words = {
"Hello",
"World",
"Java"
};
String result =
String.join(" ", words);
System.out.println(result);
List<String> list =
Arrays.asList(
"One",
"Two",
"Three");
String joined =
String.join(", ", list);
System.out.println(joined);
}
}
Output
Hello World Java
One, Two, Three
Key Features
- Accepts a delimiter.
- Works with arrays, lists, and other iterables.
- Produces a single concatenated string.
- Very clean and readable.
Method 6: Using Apache Commons Lang
Apache Commons Lang provides additional string utility methods.
import org.apache.commons.lang3.StringUtils;
public class ApacheCommonsConcat {
public static void main(String[] args) {
String result =
StringUtils.join(
new String[]{"A", "B", "C"},
"-");
System.out.println(result);
String repeated =
StringUtils.repeat("ab", 3);
System.out.println(repeated);
}
}
Output
A-B-C
ababab
Performance Comparison
| Method | Approximate Time (1000 Concatenations) |
|---|---|
concat() |
~50 ms |
StringBuilder |
~2 ms |
StringBuffer |
~3 ms |
String.format() |
~80 ms |
String.join() |
~5 ms |
| Apache Commons | ~6 ms |
+ operator |
Compiler optimizes to StringBuilder |
Common Methods Comparison
String s1 =
"Hello".concat(" ").concat("World");
String s2 =
new StringBuilder("Hello")
.append(" ")
.append("World")
.toString();
String s3 =
String.format(
"%s %s",
"Hello",
"World");
String s4 =
String.join(
" ",
"Hello",
"World");
All produce:
Hello World
Best Practices
Practice 1: Choose the Appropriate Method
For a single concatenation:
String result =
"Hello".concat(" World");
For multiple concatenations:
StringBuilder sb =
new StringBuilder();
for (String item : list) {
sb.append(item)
.append(", ");
}
For formatted output:
String message =
String.format(
"User: %s, ID: %d",
name,
id);
For joining values:
String csv =
String.join(",", values);
Practice 2: Avoid + Inside Loops
❌ Less Efficient
String result = "";
for (int i = 0; i < n; i++) {
result = result + i;
}
✅ Recommended
StringBuilder sb =
new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(i);
}
String result = sb.toString();
Practice 3: Handle Null Values
public class SafeConcatenation {
public static String concatenate(String... strings) {
StringBuilder sb =
new StringBuilder();
for (String s : strings) {
if (s != null) {
sb.append(s);
}
}
return sb.toString();
}
public static void main(String[] args) {
String result =
concatenate(
"Hello",
null,
"World");
System.out.println(result);
}
}
Output
HelloWorld
Frequently Asked Questions
Q1: Which method is the fastest?
Answer: StringBuilder is the fastest for repeated concatenation. For a single concatenation, concat() is simple and sufficient.
Q2: Why avoid the + operator?
Answer: Inside loops, it creates many intermediate String objects, reducing performance.
Q3: Can I mix different concatenation methods?
Answer: Yes, but it's generally better to use one approach consistently within the same task.
Q4: Is the + operator bad for single statements?
Answer: No. The Java compiler optimizes simple + expressions into StringBuilder operations.
Q5: When should I use StringBuffer?
Answer: Use StringBuffer only when multiple threads access and modify the same object.
Q6: How do I concatenate null values?
Answer: Check for null before appending or replace null with an empty string.
Q7: What's the best method for joining arrays?
Answer: String.join() is the cleanest and most readable solution.
Q8: Can these methods be used with Streams?
Answer: Yes. You can also use Collectors.joining() with Java Streams.
Q9: Which method performs best for very large strings?
Answer: StringBuilder remains the best choice because it provides linear-time concatenation.
Q10: Should I reuse StringBuilder objects?
Answer: Generally, no. Creating a new StringBuilder when needed is simple, efficient, and recommended.