Concatenating Strings in Java: Choosing the Right Method
Written on
What is String Concatenation
String concatenation is a common operation in Java programming, allowing us to join multiple strings together for use. For instance, if you have "Hello" from one variable and "World" from another, the result would be "Hello World".
However, it's important to note that the String class in Java is immutable. Once a String object is created, it cannot be changed. This immutability is enforced by the final keyword, indicating that the internal character array cannot be modified.
Once an immutable instance is created, its member variables remain unchanged. This design provides several benefits, including hashcode caching, improved security, and ease of use.
Since strings cannot be altered, how do we perform concatenation? The answer is that concatenation results in the creation of a new string. Here's an example code snippet demonstrating string concatenation:
public class StringJointDemo {
public static void main(String[] args) {
// Example of +
String s1 = "Hello ";
String s2 = "World";
s2 = s1 + s2;
System.out.println(s2);
}
}
Ultimately, s2 now holds a reference to a newly created String object, as depicted below.
Thus, how should one concatenate strings in Java? There are several approaches, and we will explore some common methods.
Several Ways of String Concatenation
1. Using the + Operator
In Java, the most straightforward way to concatenate strings is by using the + operator directly. It's crucial to clarify that some may misinterpret this as operator overloading; however, Java does not support operator overloading. Instead, this is an example of syntactic sugar.
Principle
Referring back to the previous code:
String s1 = "Hello ";
String s2 = "World";
s1 = s1 + s2;
System.out.println(s);
Decompiling this code reveals the underlying mechanics:
new StringBuffer().append(s1).append(s2).toString();
When using the + operator for concatenation, a StringBuilder object is instantiated, and its append(String str) method is called to concatenate the strings.
2. Using the concat Method
You can also concatenate strings using the concat(String str) method found in the String class:
public class StringJointDemo {
public static void main(String[] args) {
// Example of concat
String s1 = "Hello ";
String s2 = "World";
String s3 = s1.concat(s2);
System.out.println(s3);
}
}
Principle
Examining the concat method's source code shows that it first allocates a character array large enough to accommodate both strings, copies the values, and then creates a new String object from this array.
Consequently, using the concat method also results in the creation of a new String, reinforcing the concept of string immutability.
3. Using the StringBuffer or StringBuilder Class
Given that the + operator effectively utilizes the capabilities of the StringBuilder class, you can directly use StringBuilder for string concatenation:
public class StringJointDemo {
public static void main(String[] args) {
// Example of StringBuilder
String s1 = "Hello ";
String s2 = "World";
String s3 = new StringBuilder().append(s1).append(s2).toString();
System.out.println(s3);
}
}
When using an IDE like IntelliJ IDEA, it may suggest using the + operator for such simple concatenation tasks.
s3 = new StringBuffer().append(s1).append(s2).toString();
Difference Between StringBuffer and StringBuilder
Before delving into differences, it's essential to understand how StringBuffer and StringBuilder work. Both encapsulate a character array, as defined in their superclass AbstractStringBuilder. However, StringBuilder is mutable and allows for modification.
Moreover, not every position in the character array is necessarily utilized, as it supports the delete method to remove characters in specific ranges.
Examining the append method reveals that it primarily copies characters to the internal array and expands it if necessary. The key distinction is that StringBuffer is thread-safe, while StringBuilder is not.
4. Using the StringJoiner Class
The StringJoiner class in the java.util package can also be employed for string concatenation. It allows for an optional delimiter, along with a prefix and suffix.
Here's an example:
public class StringJointDemo {
public static void main(String[] args) {
StringJoiner sj = new StringJoiner(" ");
sj.add("Hello ").add("World");
System.out.println(sj);
sj = new StringJoiner(" ", "", "!");
sj.add("Hello ").add("World");
System.out.println(sj);
}
}
Output:
Hello World
Hello World!
It's noteworthy that when initializing a StringJoiner with StringJoiner(CharSequence delimiter), the delimiter must be specified. If you don't need a delimiter, an empty string can be used.
The StringJoiner class also provides a constructor for defining prefix and suffix.
Principle
After introducing the basic usage, let’s examine the underlying implementation of StringJoiner, particularly the add method:
As observed, StringJoiner relies on StringBuilder for its functionality.
If we have a list of students:
List<String> students = Arrays.asList("Tom", "Bob", "Victor");
To concatenate them into a string, the code would be:
String studentJoint = students.stream().collect(Collectors.joining(","));
System.out.println(studentJoint);
If you want to add prefixes and suffixes, simply pass them as parameters:
String studentJoint = students.stream().collect(Collectors.joining(",", "[", "]"));
System.out.println(studentJoint);
Additionally, the String class features a join method that accepts an array or list as the second parameter, simplifying string concatenation from a List<String>.
How to Choose the Appropriate Concatenation Method?
With multiple methods available for string concatenation, how do you decide which to use? The choice should be based on specific scenarios.
For straightforward concatenation, the + operator is suitable.
This applies to simple cases like "Hello World," where strings are concatenated without additional complexity.
If concatenating strings within a loop, opt for StringBuilder or StringBuffer.
Using the + operator in a loop can lead to performance issues due to frequent object creation, as shown in the earlier example.
For concatenating strings from a List, consider using StringJoiner or related methods for simplicity.
That concludes this discussion. Until next time!
Finally, if you found this article helpful, please clap and follow. Thank you!
I’m Dylan, and I look forward to progressing with you.
Recommended Reading
Java Interview and Usage Skills
- This column introduces common Java interview topics and related skills.
Mastering Redis
- A guide to fully understanding Redis.