In this article, we will discuss several ways of concatenating Strings in Java and also outline some common pitfalls and bad practices.
String concatenation is the process of joining two or more small String to create a big String. For example, you can create a full name by concatenating first and last name of a person.
Different Ways to concatenating Strings In Java
- Using StringBuilder
- Addition(+) Operator
- Using String.concat() Method
- Using String.join() Method (Java 8+)
- Using StringJoiner Class (Java 8+)
- Using Arrays.toString() Method
Let's discuss the above different ways to concatenating Strings in Java.
1. Using StringBuilder
StringBuilder class provides append() method which is used to append the specified string to this character sequence. Let’s build a quick example of String concatenation using the StringBuilder class:
package com.javaguides.corejava.string;
public class ConcatStringExample {
public static void main(String[] args) {
ConcatStringExample example = new ConcatStringExample();
example.usingStringBuilder();
}
public void usingStringBuilder() {
StringBuilder stringBuilder = new StringBuilder(150);
stringBuilder.append("Java");
stringBuilder.append(" is");
stringBuilder.append(" top");
stringBuilder.append(" programming");
stringBuilder.append(" laguange");
System.out.println(stringBuilder.toString());
}
}
Output:
Java is top programming laguange
Internally, StringBuilder maintains a mutable array of characters. In our code sample, we’ve declared this to have an initial size of 150 through the StringBuilder constructor. Because of this size declaration, the StringBuilder can be a very efficient way to concatenate Strings.
It’s also worth noting that the StringBuffer class is the synchronized version of StringBuilder. Although synchronization is often synonymous with thread safety, it’s not recommended for use in multithreaded applications due to StringBuffer’s builder pattern.
2. Addition(+) Operator
This is the same operator that results in the addition of numbers and is overloaded to concatenate when applied to Strings.
If you have more string concatenation operations, then prefer using StringBuilder object over the + operator.
Let’s take a quick look at how this works:
package com.javaguides.corejava.string;
public class ConcatStringExample {
public static void main(String[] args) {
ConcatStringExample example = new ConcatStringExample();
example.usingPlusOperator();
}
public void usingPlusOperator() {
String concatStr = "Java" + " is" + " top" + " programming" + " language";
System.out.println(concatStr);
}
}
Output:
Java is top programming language
Notice that String concatenation using the + operator within a loop should be avoided. Since the String object is immutable, each call for concatenation will result in a new String object being created.
3. Using String.concat() Method
Let's use Spring.concat() method -This method concatenates the specified string to the end of this string. This method returns a String object, so chaining together the method is a useful feature.
package com.javaguides.corejava.string;
public class ConcatStringExample {
public static void main(String[] args) {
ConcatStringExample example = new ConcatStringExample();
example.usingStringConcatMethod();
}
public void usingStringConcatMethod() {
String concatStr = "Java".concat(" is").concat(" top").concat(" programming").concat(" language");
System.out.println(concatStr);
}
}
Output:
Java is top programming language
4. Using String.join() Method (Java 8+)
If our application is running on Java 8 or above, we can take advantage of the String.join method. With this, we can join an array of Strings with a common delimiter, ensuring no spaces are missed.
package com.javaguides.corejava.string;
public class ConcatStringExample {
public static void main(String[] args) {
ConcatStringExample example = new ConcatStringExample();
example.usingStringJoinMethod();
}
public void usingStringJoinMethod() {
String[] strArray = {
"Java",
" is",
" top",
" programming",
" language"
};
String concatStr = String.join("", strArray);
System.out.println(concatStr);
}
}
Output:
Java is top programming language
A huge advantage of this method is not having to worry about the delimiter between our strings.
5. Using StringJoiner Class (Java 8+)
Java 8 added a new final class StringJoiner in java.util package. It is used to construct a sequence of characters separated by a delimiter. Now, you can create a string by passing delimiters like a comma(,), hyphen(-) etc.
package com.javaguides.corejava.string;
import java.util.StringJoiner;
public class ConcatStringExample {
public static void main(String[] args) {
ConcatStringExample example = new ConcatStringExample();
example.usingStringJoinerClass();
}
public void usingStringJoinerClass() {
StringJoiner joiner = new StringJoiner(" ");
joiner.add("Java");
joiner.add("is");
joiner.add("top");
joiner.add("programming");
joiner.add("language");
System.out.println(joiner.toString());
}
}
Output:
Java is top programming language
Read more about StringJoiner class at http://www.javaguides.net/2018/07/java-8-stringjoiner-class.html
6. Using Arrays.toString() Method
The Array class contains a handy toString method which nicely formats an array of objects. The Arrays.toString method also calls the toString method of any enclosed object – so we need to ensure we have one defined.
package com.javaguides.corejava.string;
import java.util.Arrays;
public class ConcatStringExample {
public static void main(String[] args) {
ConcatStringExample example = new ConcatStringExample();
example.usingArrayToString();
}
public void usingArrayToString() {
String[] myFavouriteLanguages = {
"Java",
"C",
"Java EE"
};
String str = Arrays.toString(myFavouriteLanguages);
System.out.println(str);
}
}
Output:
[Java, C, Java EE]
Read more about Arrays class at http://www.javaguides.net/2018/08/java-util-arrays-class-api-guide.html
Complete Example
package com.javaguides.corejava.string;
import java.util.Arrays;
import java.util.StringJoiner;
public class ConcatStringExample {
public static void main(String[] args) {
ConcatStringExample example = new ConcatStringExample();
example.usingArrayToString();
example.usingStringBuilder();
example.usingPlusOperator();
example.usingStringConcatMethod();
example.usingStringJoinerClass();
example.usingStringJoinMethod();
}
public void usingStringBuilder() {
StringBuilder stringBuilder = new StringBuilder(150);
stringBuilder.append("Java");
stringBuilder.append(" is");
stringBuilder.append(" top");
stringBuilder.append(" programming");
stringBuilder.append(" laguange");
System.out.println(stringBuilder.toString());
}
public void usingPlusOperator() {
String concatStr = "Java" + " is" + " top" + " programming" + " language";
System.out.println(concatStr);
}
public void usingStringConcatMethod() {
String concatStr = "Java".concat(" is").concat(" top").concat(" programming").concat(" language");
System.out.println(concatStr);
}
public void usingStringJoinMethod() {
String[] strArray = {
"Java",
" is",
" top",
" programming",
" language"
};
String concatStr = String.join(" ", strArray);
System.out.println(concatStr);
}
public void usingStringJoinerClass() {
StringJoiner joiner = new StringJoiner("");
joiner.add("Java");
joiner.add("is");
joiner.add("top");
joiner.add("programming");
joiner.add("language");
System.out.println(joiner.toString());
}
public void usingArrayToString() {
String[] myFavouriteLanguages = {
"Java",
"C",
"Java EE"
};
String str = Arrays.toString(myFavouriteLanguages);
System.out.println(str);
}
}
Output:
[Java, C, Java EE]
Java is top programming laguange
Java is top programming language
Java is top programming language
Javaistopprogramminglanguage
Java is top programming language
Related Java String Programs and Examples
- String Programs in Java with Output
- Java program to Count Number of Duplicate Words in String
- Java Program to Count Number of Words in Given String
- Java Program to Count the Number of Occurrences of Substring in a String
- Java Program to Count the Occurrences of Each Character in String
- Java Program to Merge two String Arrays
- Java Program to Remove Duplicate Words from String
- Java Program to Reverse a String(5 ways)
- Java Program to Reverse Each Word of a String
- Java Program to Swap Two Strings
- How to Check if the String Contains only Digits
- How to Check if the String Contains only Letters
- How to Check If the String Contains Only Letters or Digits
- Java Program to Check if Input String is Palindrome
- Java Program to Find all Permutations of String
- How to Remove or Trim All White Spaces from a String in Java
- How to Remove Leading and Trailing White Space From a String in Java
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
Comments
Post a Comment