String concatenation is one of the most basic things you can do in programming. Concatenation is when you put two or more things together, such making a whole name from “First” and “Last” names or a complicated SQL query. At PW Skills, we stress that there are various ways to join text, but the best way depends on your performance demands and the version of Java you are using.
Methods to Concatenate String in Java
Java provides several distinct ways to join strings, each with its own “under-the-hood” behavior.
A. The + Operator (Simple and Common)
The easiest way to concatenate string in java is using the plus (+) operator.
- Example: String full = “Hello” + ” ” + “World”;
- Note: You can also use + to join a String with a number (e.g., “Score: ” + 10).
B. The concat() Method
The String class provides a built-in concat() method.
- Example: String s3 = s1.concat(s2);
- Difference: Unlike the + operator, concat() only accepts String arguments. If you try to pass an integer, the code will not compile.
C. StringBuilder and StringBuffer (High Performance)
Since Strings in Java are immutable (cannot be changed), every time you use +, Java creates a brand-new String object. For a few strings, this is fine. But if you are joining strings inside a loop 1,000 times, it becomes very slow.
- Solution: Use StringBuilder (not thread-safe, faster) or StringBuffer (thread-safe, slower).
- Example :
- Using StringBuilder for high-performance loops
StringBuilder sb = new StringBuilder();
String[] words = {“Java”, “is”, “awesome”, “in”, “2026”};
for (String word : words)
{
sb.append(word).append(” “); // Appends to existing buffer
}
String result = sb.toString().trim();
System.out.println(result);
// Output: Java is awesome in 2026
Advanced: Concatenate String in Java 8
With the release of java 8, developers received two powerful new tools for concatenation that made code much cleaner.
A. String.join()
This is perfect when you have a list of strings and want to put a comma or space between them.
- Syntax: String.join(delimiter, elements)
- Example: “`java
String result = String.join(“-“, “2026”, “03”, “06”);
// Result: 2026-03-06
B. StringJoiner Class
The StringJoiner class (found in java.util) allows you to define a prefix, a suffix, and a delimiter.
- Example :import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
Example A: Using StringJoiner for Prefix/Suffix
StringJoiner sj = new StringJoiner(“, “, “[“, “]”);
sj.add(“Red”).add(“Green”).add(“Blue”);
System.out.println(sj.toString());
// Output: [Red, Green, Blue]
Example B: Using Stream API (Collectors.joining)
List<String> list = Arrays.asList(“Apple”, “Banana”, “Cherry”);
String streamedResult = list.stream()
.map(String::toUpperCase)
.collect(Collectors.joining(” | “));
System.out.println(streamedResult);
// Output: APPLE | BANANA | CHERRY
Java vs. JavaScript Concatenation
Many developers work in both Java and JavaScript. While the basics are similar, the execution differs.
How to Concatenate String in JavaScript
In JS, you can use the + operator or Template Literals (the modern way).
- Template Literals: `Hello ${name}`
- Method: concat() also exists in JS: str1.concat(str2).
Concatenate String in JavaScript For Loop
A common task is to concatenate string in javascript for loop.
- Performance Tip: In modern JavaScript, it is often better to use .join() on an array instead of a loop: fruits.join(” “);
Also read :
- Java Non Primitive Data Types
- How to print variable in java
- Java Comments: Tutorial for Beginners
- Java Native Interface Explained: 14 Outstanding Components to Know
- Java Type Casting
- Top 30 Java Interview Question and Answers
- Top 60 Java Interview Questions and Answers For Freshers
- OOPs Concepts in Java with Examples & Interview Questions
- Java Comparison Operators
- Java Data Types Real-Life Example
- Java Boolean Data Types
- Java Arithmetic Operators
- Top 100 DSA Interview Questions
The StringJoiner and Stream API (Java 8 and Beyond)
As Java got better, it became clear that there needed to be more declarative ways to combine strings. This is why the StringJoiner class and the Collectors.joining() function were added to the Stream API. These tools are made to fix the “comma-separated list” problem, which used to need convoluted if-else logic to prevent a trailing comma.
You can set a delimiter, a prefix, and a suffix ahead of time with the StringJoiner. This is a lot cleaner than adding brackets or separators by hand. Also, if you’re working with collections, the Stream API gives you a really easy-to-read way to do it:
This new method is not only thread-safe when used with parallel streams, but it also cuts down on a lot of boilerplate code, which makes it easier to keep your Java 8 projects up to date and check them.
Why Methodology Matters
When we talk about how well different ways of concatenating strings in Java work, we’re really talking about how much memory they use and how long they take. Because the String class in Java is immutable, the JVM has to make a new String object in the heap memory and copy the previous contents over every time you use the + operator or the concat() method.
The Problem with the + Operator in Loops
The JVM does about $O(n^2)$ work if you use + in a loop to combine 10,000 strings. This is because it transfers the existing string into a new, bigger memory region every time it runs. For very large datasets, this might cause a lot of “Garbage Collection” overhead because thousands of temporary string objects that aren’t needed anymore fill up memory.
The Efficiency of StringBuilder
StringBuilder, on the other hand, keeps the characters in a buffer, which is an array that can change size. The .append() function just adds the new text to the buffer that is already there. It doesn’t create a new object. This makes the time complexity $O(n)$, which means that for activities that need a lot of processing power, this is the best technique to concatenate strings in Java.
Common Pitfalls and Tips for Concatenate String in Java
- The “Null” Trap: The “Null” Trap: If you use + with a null variable, like “Hello ” + null, you get “Hello null.”
- If you use concat() with a null variable: str.concat(null) throws a NullPointerException.
- Order of Operations:
- System.out.println(10 + 20 + “Score”); results in “30Score”.
- System.out.println(“Score” + 10 + 20); results in “Score1020”.
- Tip: Use parentheses to control the math!
- Immutability: Every time you “change” a string using +, the old string stays in memory (the String Pool) until garbage collection, which can lead to memory bloat in huge apps.
Conclusion
Whether you choose the simplicity of the + operator, the control of StringBuilder, or the elegance of java 8 joins, mastering how to concatenate string in java is a vital skill. By understanding the memory implications of each method, you can write code that is not only functional but also optimized for high-performance environments.
At PW Skills, we believe that “clean code” is just as important as “working code.” Next time you join text, think about the scale of your operation and pick the tool that fits best!
FAQs
Is StringBuilder better than the + operator?
Inside a loop, yes—always. For a single line like String s = "a" + "b";, the compiler actually converts the + into a StringBuilder automatically, so there is no difference.
How do I join strings in a for loop in Java?
Always initialize a StringBuilder before the loop and use .append() inside the loop. Avoid using += inside a loop.
What is the difference between concat string in javascript and Java?
In JavaScript, strings are also immutable, but the engine is very aggressive at optimizing the + operator. In Java, the programmer has more explicit control through StringBuilder.
Can I concatenate a character with a string?
Yes, String s = "A" + 'B'; works perfectly in Java.
How do I join a list of strings in Java 8?
Use String.join(", ", myList) or use the Collectors.joining() method if you are using the Stream API.
