The concat() method joins one string to the end of another and returns a new combined string. It is a readable, method-based alternative to the + operator for simple two-string joins.
01
Append Text
Add to the end.
02
Returns String
New combined value.
03
Immutable
Originals unchanged.
04
One Argument
Another String only.
05
vs + Operator
Two ways to join.
06
StringBuilder
For many joins.
Fundamentals
Definition and Usage
In Java, concat(String str) belongs to java.lang.String. When you call greeting.concat("World!"), Java creates a new string containing the characters of greeting followed by "World!". The greeting variable still points to the old text unless you assign the result back to it.
Because strings are immutable, every concatenation produces a fresh object. That design keeps strings thread-safe and predictable, but it also means you should not call concat() thousands of times in a tight loop without a StringBuilder.
💡
Beginner Tip
Always capture the return value: result = a.concat(b). Calling a.concat(b) alone and ignoring the return value leaves a unchanged—unlike some mutable list types, strings never update in place.
Foundation
📝 Syntax
The concat() method is declared in the String class:
java
public String concat(String str)
Parameters
str — the string appended to the end of the caller. Must not be null.
Return Value
Returns a new String whose content is the caller followed by str.
Exceptions
Throws NullPointerException if str is null.
Cheat Sheet
⚡ Quick Reference
Code
Result
"Hello, ".concat("World!")
"Hello, World!"
"Java".concat("")
"Java" (unchanged content)
"".concat("Hi")
"Hi"
"a".concat("b").concat("c")
"abc" (chained)
"Hi".concat(null)
NullPointerException
Basic
a.concat(b)
Join two strings
Operator
a + b
Common alternative
Assign
s = s.concat("!")
Update variable
Many joins
new StringBuilder()
Use in loops
Hands-On
Examples Gallery
These programs run in Java 8+. They cover basic joining, immutability, chaining, comparison with +, and when to reach for StringBuilder.
Concatenated: Hello, World!
Original still: Hello,
How It Works
concat() copies both strings into a new object and returns it. originalString still holds only "Hello, " because strings never change after creation.
Example 2 — Original String Is Not Modified
A quick proof that you must assign the result if you want to keep the combined text.
java
public class ImmutableDemo {
public static void main(String[] args) {
String word = "Code";
word.concat("ToFun"); // return value ignored!
System.out.println("word is still: " + word);
word = word.concat("ToFun"); // assign the result
System.out.println("word now: " + word);
}
}
📤 Output:
word is still: Code
word now: CodeToFun
How It Works
The first concat() call creates "CodeToFun" but throws it away because nothing stores it. Reassigning word with the second call fixes the issue.
📈 Practical Patterns
Chaining, alternatives, and performance-aware building.
Example 3 — Chaining concat() Calls
Each concat() returns a new string, so you can chain calls to join several pieces.
java
public class ChainConcat {
public static void main(String[] args) {
String result = "Java"
.concat(" is ")
.concat("fun")
.concat("!");
System.out.println(result);
}
}
📤 Output:
Java is fun!
How It Works
Each step builds a temporary string. For a few parts this is fine; for many segments in a loop, prefer StringBuilder to avoid creating lots of intermediate objects.
Example 4 — concat() vs the + Operator
Both approaches produce the same result for simple string joins.
java
public class ConcatVsPlus {
public static void main(String[] args) {
String first = "Hello";
String second = "Java";
String withConcat = first.concat(", ").concat(second);
String withPlus = first + ", " + second;
System.out.println("concat(): " + withConcat);
System.out.println("+ operator: " + withPlus);
System.out.println("Same content? " + withConcat.equals(withPlus));
}
}
📤 Output:
concat(): Hello, Java
+ operator: Hello, Java
Same content? true
How It Works
The compiler often optimizes + on strings similarly to concat(). Use whichever reads better; + is idiomatic for short literals, while concat() makes method-style chaining explicit.
Example 5 — Building Text in a Loop with StringBuilder
When concatenating inside a loop, StringBuilder avoids creating a new string on every iteration.
java
public class BuilderLoop {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append("Item ").append(i).append("; ");
}
String report = sb.toString().trim();
System.out.println(report);
}
}
📤 Output:
Item 1; Item 2; Item 3; Item 4; Item 5;
How It Works
StringBuilder mutates an internal buffer, then toString() creates one final String. This pattern scales better than result = result.concat(...) inside the loop.
Applications
🚀 Common Use Cases
Building messages — combine a label and a value: "Score: ".concat(scoreText).
File paths and URLs — append path segments when you already hold base strings.
Method-style chaining — readable pipelines that append fixed suffixes.
Teaching immutability — show that string operations return new objects.
Legacy APIs — some libraries expect explicit concat() instead of operators.
🧠 How concat() Works
1
You call concat(str)
Java receives the caller string and the string to append.
Input
2
Null check on argument
If str is null, Java throws NullPointerException.
Validate
3
New array allocated
The JVM copies characters from both strings into a new backing array for a fresh String object.
Copy
=
📝
Combined String
Caller + argument, without changing either original.
Important
📝 Notes
Strings are immutable—concat() never edits the caller in place.
The + operator is the most common concatenation style in modern Java code.
concat() accepts only String; use + or String.valueOf() to append numbers.
Concatenating with empty string "" returns a string equal in content to the caller.
For repeated joins, use StringBuilder or String.join() / String.format() when appropriate.
Performance
⚡ Optimization
A single concat() call is efficient and fine for joining two strings. Inside loops, avoid s = s.concat(part) because each iteration allocates a new string copying everything so far. Use StringBuilder.append() instead, then call toString() once at the end. The Java compiler also optimizes some compile-time + chains automatically.
Wrap Up
Conclusion
The concat() method is a clear, explicit way to join two strings in Java. It reinforces the immutability model: you always get a new result and must assign it if you want to keep the combined text.
For everyday one-line joins, + is perfectly acceptable. Reach for concat() when method chaining reads better, and switch to StringBuilder when you assemble text repeatedly or in loops.
Prefer String.join() for delimiter-separated lists
❌ Don’t
Ignore the return value of concat()
Call concat() repeatedly in tight loops
Pass null as the argument
Expect the original string to change in place
Use string concat inside hot paths without measuring performance
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about concat()
Use these points whenever you join strings in Java.
5
Core concepts
🔗01
Appends Text
Argument to the end.
Purpose
🔄02
New String
Immutable result.
Return
➕03
vs + Operator
Both join strings.
Alternative
⚡04
StringBuilder
For many joins.
Performance
⚠05
null Throws
NullPointerException.
Safety
❓ Frequently Asked Questions
concat(String str) appends the argument string to the end of the calling string and returns a new combined String. The original strings are not modified because strings in Java are immutable.
Call it on any String: firstString.concat(secondString). It takes one String parameter and returns a new String containing both parts in order.
Both create a new string when joining text. The + operator is more common and can mix strings with numbers (automatic conversion). concat() only accepts another String and reads clearly as "append this string."
No. Strings are immutable. concat() always returns a new String object. The caller and argument remain unchanged unless you reassign a variable with the result.
concat(null) throws NullPointerException. If the argument might be null, check first or use Objects.toString(other, "") or similar safe patterns.
Use StringBuilder (or StringBuffer) when concatenating many times inside a loop or building large text piece by piece. Repeated concat() or + in a loop creates many temporary strings and is slower.