How to Join Strings in Java: Simple Methods and Examples
In Java, you can join strings using the
+ operator, the String.concat() method, or the String.join() method for multiple strings. The String.join() method is useful to join many strings with a delimiter easily.Syntax
Here are 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 the concat method on a string.String result = String.join(delimiter, str1, str2, ...);- joins multiple strings with a delimiter.
java
String result1 = "Hello" + " World"; String result2 = "Hello".concat(" World"); String result3 = String.join(", ", "Apple", "Banana", "Cherry");
Example
This example shows how to join strings using the plus operator, concat method, and String.join method.
java
public class JoinStringsExample { public static void main(String[] args) { String a = "Hello"; String b = "World"; // Using + operator String joined1 = a + " " + b; // Using concat method String joined2 = a.concat(" ").concat(b); // Using String.join method String joined3 = String.join(", ", "Apple", "Banana", "Cherry"); System.out.println(joined1); System.out.println(joined2); System.out.println(joined3); } }
Output
Hello World
Hello World
Apple, Banana, Cherry
Common Pitfalls
Common mistakes when joining strings include:
- Using
+operator in loops, which creates many temporary strings and slows performance. - Forgetting to add spaces or delimiters between strings, causing words to run together.
- Using
concat()withnullvalues, which throwsNullPointerException.
Use StringBuilder for joining strings in loops for better performance.
java
public class PitfallExample { public static void main(String[] args) { String[] words = {"Java", "is", "fun"}; // Inefficient way (creates many strings) String sentence = ""; for (String word : words) { sentence += word + " "; } System.out.println(sentence.trim()); // Better way using StringBuilder StringBuilder sb = new StringBuilder(); for (String word : words) { sb.append(word).append(" "); } System.out.println(sb.toString().trim()); } }
Output
Java is fun
Java is fun
Quick Reference
Summary of string joining methods in Java:
| Method | Usage | Notes |
|---|---|---|
| + operator | str1 + str2 | Simple for few strings, not efficient in loops |
| String.concat() | str1.concat(str2) | Joins two strings, throws NullPointerException if argument is null |
| String.join() | String.join(", ", str1, str2, ...) | Joins multiple strings with delimiter, introduced in Java 8 |
| StringBuilder | Use append() in loops | Efficient for joining many strings or in loops |
Key Takeaways
Use + operator or concat() for simple string joining.
Use String.join() to join multiple strings with a delimiter easily.
Avoid using + operator inside loops; prefer StringBuilder for better performance.
Remember to handle null values to avoid exceptions.
String.join() requires Java 8 or newer.