concat() method
Concat() method appends the specified string at the end of the given string and then returns and then returns a new string formed. Sure we can use the concat() method to join three or more strings.The concat() method signature
public String concat(String str)
The method concatenates the string str at the end of the current string.
For example:
String s1 = “Hello ”;
s1.concat("World")
returns a new string “Hello World”.
Concat() method example
Let’s concat two strings after their initialisation, then concat more strings. And one more interesting example: we are going to create a method that would return different messages according to argument.
public class ConcatTest {
public static void main(String[] args) {
//String concat with concat() method
String string1 = "I learn ";
String string2 = "concatenation in Java";
//here we use concat() method to join the two strings above
String result = string1.concat(string2);
System.out.println(result);
//concat() method to join 4 strings
String myWebSite = "Code".concat("Gym").concat(".cc").concat("/quest");
System.out.println(myWebSite); // here we've got "CodeGym.cc/quest"
System.out.println(myMessage(true));
System.out.println(myMessage(false));
}
private static String myMessage(boolean b) { //concat() method with selection statement
return "I have".concat(b ? " " : "n't ").concat("got it");
}
}
The output is:
Concatenation using overloaded operators "+" and "+="
You can use these two operators in the same way as with numbers. They work just like concat(). Let’s concatenate the string “Code” and string “Gym”.
public class StringConcat {
public static void main(String[] args) {
String myString = "Code" + "Gym";
myString+= ".cc";
System.out.println(myString);
}
}
Usually Java doesn’t allow overloading operations for user classes, but these two operators work as overloaded. You might think that inside the + operator is hiding concat(), but in fact, another mechanism is used here. If we look at the Java program bytecode, we’ll see that StringBuilder was created and its append() method is used.
The Java Compiler sees the “+” operator and realizes that operands are strings, not primitive types. So it works like concat.
public class StringTest2 {
public static void main(String[] args) {
String hello = "hello";
String world = " world!";
String helloworld = (new StringBuilder().append(hello).append(world).toString());
System.out.println(helloworld);
//this is the same as:
String result = hello + world;
}
}
Concat(0) or + ?
If you need to merge strings only once, use the concat() method. For all other cases, it is better to use either the + or Stringbuffer/StringBuilder operator. Also, the + operator is used to convert types. If one of the operands is equal, for example, the number and the second is a string, then at the exit we will get a string. Example:
public class StringConcat {
public static void main(String[] args) {
int myInt = 5;
String myString = " days";
System.out.println(myInt + myString);
boolean b = (myInt + myString) instanceof String;
System.out.println(b);
}
}
We used instanceof to check if (myInt + myString) a String. Here is the output of this program:
public class StringConcat {
public static void main(String[] args) {
String myString = "book ";
System.out.println(myString + null);
System.out.println((myString + null) instanceof String);
}
}
The output is:
public class StringConcat {
public static void main(String[] args) {
String myString = "book ";
System.out.println(myString.concat(null));
}
}
The output is:
The concat()
method and the "+"
operator are two popular ways to concatenate strings in Java. Choosing the right approach depends on factors such as performance and readability.
Performance Considerations
- The
"+"
operator is internally converted into aStringBuilder
orStringBuffer
operation by the compiler for multiple concatenations. This makes it efficient in most scenarios. concat()
is slightly faster when concatenating exactly two strings since it skips the overhead of creating intermediate objects.
Readability Considerations
- The
"+"
operator is more intuitive and readable for simple concatenation. concat()
is less readable, especially when chaining multiple concatenations, and it requires all operands to be non-null, leading to potentialNullPointerException
.
Conclusion
Use the "+"
operator for most scenarios, especially for readability, unless performance testing indicates that concat()
provides a measurable benefit in specific cases.
Impact of Algorithm Choice on String Concatenation Performance
The choice of algorithm used for string concatenation can significantly impact application performance, especially when dealing with large-scale or repetitive operations.
Using StringBuilder for Efficiency
For scenarios involving multiple concatenations in loops, using StringBuilder
is more efficient than using the "+"
operator directly, as it avoids creating multiple intermediate String
objects.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 1000; i++) {
builder.append("example");
}
String result = builder.toString();
This approach minimizes memory usage and improves performance.
Avoiding Naive Approaches
Avoid concatenating strings in a loop using the "+"
operator, as it creates a new String
object in every iteration, leading to increased memory consumption and slower performance.
Using StringJoiner for String Concatenation
Introduced in Java 8, StringJoiner
provides a modern and flexible way to concatenate strings with optional delimiters, prefixes, and suffixes.
import java.util.StringJoiner;
public class StringJoinerExample {
public static void main(String[] args) {
StringJoiner joiner = new StringJoiner(", ", "[", "]");
joiner.add("Java");
joiner.add("Python");
joiner.add("C++");
System.out.println(joiner.toString()); // Output: [Java, Python, C++]
}
}
StringJoiner
is particularly useful when formatting strings with consistent delimiters or surrounding text.
Concatenating Strings with Collectors.joining in the Stream API
The Collectors.joining
method, part of the Stream API, offers an elegant and efficient way to concatenate strings from collections.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectorsJoiningExample {
public static void main(String[] args) {
List<String> languages = Arrays.asList("Java", "Python", "C++");
String result = languages.stream()
.collect(Collectors.joining(", ", "[", "]"));
System.out.println(result); // Output: [Java, Python, C++]
}
}
This method is ideal for scenarios involving dynamic collections, such as lists or arrays, and supports adding custom delimiters, prefixes, and suffixes.
GO TO FULL VERSION