String concatenation in Java is the process of joining or combining two or more strings together to create a new string. It is one of the most common operation or task in any programming languages.
For example, when you fill an online registration form, you fill your first name, middle name, and last name in three separate columns. But when you finish the form, you see your complete name as a single string. This is a real-time use of string concatenation.
In Java, a string can be concatenated with two or more strings or a string with a number or symbol to display information as per requirements.
In general, Java does not allow operators to be applied to string objects except the plus (+) operator, which concatenates multiple strings and forms a new string.
In this tutorial, we will understand different ways to concatenate multiple strings in Java programming. We will also understand concepts of allotting string objects in the memory.
Best Ways to Concatenate Strings in Java
Since string concatenation is heavily used in Java programming, there are two convenient and best ways to concatenate strings in Java. They are as follows:
- By concat() method.
- By + (String concatenation) operator
Let’s understand all two methods one by one with the help of example programs and suitable figures.
String Concatenation by concat() Method in Java
This string concat() method concatenates or joins the specified string to the end of current string and creates a new string object. The general syntax for concat() method is as follows:
public String concat(String str)
Here, ‘concat’ is a method name and return type of this method is string object.
‘String str’ in the parenthesis represents that we are passing another string object or string values to concat() method while it is called. For example:
String s2 = s1.concat("Hi");
The concat() method will concatenate or join String “Hi” at the end of string class object s1 and return the second string s2 as a result. Here, s1 is a string class object.
Similarly, if
String s1 = "Dhan"; String s2 = "bad"; String s3 = s1.concat(s2);
In this example, concat() method joins two strings (s1 and s2) and stores it in the string variable s3 as a result. So, if s1 = “Dhan” and s2 = “bad” then we can expect s3 will be “Dhanbad”.
Let’s take a simple example program in which we will concatenate two strings using concat() method. Look at the source code.
Program code 1:
package stringPrograms; public class StringConcatenationTest1 { public static void main(String[] args) { String s1 = "Hello"; s1.concat("Java"); System.out.println(s1); // Hello } }
Output: Hello
Explanation of memory concept:
1. When the statement String s1 = “Hello”; is executed by JVM, a string object will create in the string constant pool and store “Hello” in it. The reference variable s1 is pointing to that object.
2. As you know that once we create a string object, we are not allowed to perform any changes in that object. If we will try to change, a new object will be created with these changes in the heap area.
When the statement s1.concat(“Java”); will be executed, JVM will be added at the end of “Hello” and it will become “Hello Java”.
Since we performed changes in the existing object. That’s why a new object will be created in the heap area and stores “Hello Java” in it.
But we did not assign any reference variable to this new object. Therefore, it will be removed from the memory by the garbage collector.
3. When the statement String s1 = “Hello”; will be executed. For every string literal, one copy of the object will also be created in the string constant pool for further usability and stores “Java” in it.
As you can observe in the above figure, still ‘s’ is pointing to “Hello” only. Therefore, the output is Hello.
Let’s take another example program in which we will concatenate two strings and store the result into another variable of string type.
Program code 2:
package stringPrograms; public class StringConcatenationTest2 { public static void main(String[] args) { String s1 = "Indian "; String s2 = "Team"; String s3 = s1.concat(s2); System.out.println(s3); // Indian Team } }
Output: Indian Team
Explanation of memory concept:
As you can see in the above figure, a total of three objects are created, one in the heap area and two in the SCP area.
Now consider the following example code given below:
Program code 3:
package stringPrograms; public class StringConcatenationTest1 { public static void main(String[] args) { String s1 = new String("Java"); s1.concat(" Core"); s1 = s1.concat(" Programming"); System.out.println(s1); } }
a) How many string objects will be created in the heap area and string constant pool area?
b) What will be the output of the following program?
Ans a: To find out string objects and output of the above program, let’s understand the memory concept with the help of the figure below.
1. When the statement String s1 = new String(“Java”); will be executed by JVM, one object will be created in the heap area and one copy of object will be created in the SCP area for future purposes. The reference variable s1 is pointing to object “Java” in the heap area.
2. When the line s1.concat(” Core”); will be executed by JVM, for every string literal, one copy of object ” Core” will be created in the SCP area for future purposes. The content ” Core” will be added at the end of “Java” and it will be stored in the heap as “Java Core”.
Since we are not pointing any reference variable to this new object. Therefore, the garbage collector will remove this newly created object from the memory.
3. When JVM will execute line s1 = s1.concat(” Programming”);, for string literal, one copy of the object will create in the SCP area and store ” Programming” in it. JVM will concatenate content ” Programming” to the end of “Java” and it becomes “Java Programming”.
After concatenation, JVM will create a new object and store string “Java Programming” in that object. But the content of string s1 is not modified. That’s why strings are called immutable.
Now, JVM will point reference s1 towards that new object because we are assigning the same reference variable s1 to the newly created object.
The old object that contains “Java”, has lost its reference as shown in the figure and the garbage collector will remove it from the memory.
Thus, as you can observe from the figure that a total of 6 objects are created in the memory, three objects in the heap, and three objects in the string constant pool.
Ans b. The output of the program is “Java Programming” because s1 is pointing to a newly created object in the heap.
String Concatenation in Java using + operator
The plus operator (+) is used to add two or more strings in Java. For example, two strings “Hello” and ” Java” can be concatenated to form a single new string “HelloJava”.
String str = "Hello" + "Java"; // Result is "HelloJava".
What if we would like to add two strings separated by a space? No problem:
String name = "Hello" + " " + "Java";
This statement concatenates three strings into one string: Hello, the string literal ” “, and Java. The result is “Hello Java”.
Let’s take an example program where we will concatenate two strings by using a plus (+) operator. Take a look at the following source code.
Program code 4:
package stringPrograms; public class StringConcatenationTest4 { public static void main(String[] args) { String s1 = "Shubh" + " Deep"; System.out.println(s1); } }
Output: Shubh Deep
Java String Concatenation with Other Data Types
In Java, we can also concatenate strings with other types of data by using (+) operator. That is, string values can also be easily concatenated with primitive values.
In this case, the primitive value is first automatically converted into its string representation within a string object and then this string is concatenated as before.
Consider the following example.
int age = 16; String s = "She is " + age + " years old."; System.out.println(s); // Output: She is 16 years old.
Here, age is an int rather than another string, but the output produced is the same as before. This is because the int value 16 is automatically converted into its string within a String object. This string is then concatenated with other strings.
Note:
At least, one of the operands must be a string for concatenation. If none of the operands is a string, the plus sign (+) will work as an addition operator that adds two numbers.
Here are some examples:
// String tutorial is concatenated with number 2 String s = "Tutorial" + 2; // s become Tutorial2. // String ABC is concatenated with character D. String s1 = "ABC" + 'B'; // s1 becomes ABCD.
Let’s take an example program where we will concatenate string values with other primitive values.
Program code 5:
package stringPrograms; public class StringConcatenationTest5 { public static void main(String[] args) { int date = 15; String month = " August "; int year = 1947; String s1 = date + month + year; System.out.println(s1); // 15 August 1947 } }
Output: 15 August 1947
In the above example program, two variables, date and year of data type int are concatenated along with a String object “month”.
The variable date is initialized with a value 15 while the variable year is initialized with a value 1947. The string object month is initialized with the value of August. After concatenation, the result is 15 August 1947.
Other Ways to Concatenate Strings in Java
There are some other techniques to concatenate or combine multiple strings in Java. Let’s understand them one by one with the help of examples.
1. String Concatenation by using StringBuilder Class
StringBuilder is a class that offers an append() method to perform string concatenation operation. It is the most straightforward and fastest way to combine multiple strings in Java. The append() method can take arguments of different types, such as int, char, CharSequence, boolean, float, double, Objects, and StringBuilder.
StringBuilder is mutable class, which means values stored in StringBuilder objects can be updated or changed once they are created. Let’s take an example program based on this concept.
Program code 6:
package stringPrograms; public class StringBuilderExample { public static void main(String[] args) { // Create a new StringBuilder object. StringBuilder sb = new StringBuilder(); // Call append() method to concatenate strings and other data types. sb.append("Hello, "); // Appending a string sb.append("Java!"); // Appending another string sb.append(2023); // Appending an integer // Convert the StringBuilder object to a String. String result = sb.toString(); // Display the concatenated string System.out.println(result); } }
Output: Hello, Java!2023
In this example, we have created a StringBuilder object and use the append() method to add strings and an integer to it. After appending all the desired values, we have converted the value stored into StringBuilder object to a String using the toString() method.
Then, we have printed the concatenated result on the console. This example exhibits how we can dynamically concatenate different types of data using StringBuilder.
2. String Concatenation using format() Method
The String.format() method allows us to concatenate multiple strings using format specifier like %s, %d followed by the string values or objects. It’s a powerful way to concatenate strings with specific formatting. Let’s take examples based on it.
Program code 7:
package stringPrograms; public class StringFormatExample { public static void main(String[] args) { String s1 = "Scientech"; String s2 = " Easy"; String s = String.format("%s%s",s1,s2); System.out.println(s.toString()); } }
Output: Scientech Easy
Program code 8:
package stringPrograms; public class StringFormatExample { public static void main(String[] args) { String name = "Tripti"; int age = 23; // Use String.format() to create a formatted string. String formatted = String.format("My name is %s, and I am %d years old.", name, age); // Printing the formatted string. System.out.println(formatted); } }
Output: My name is Tripti, and I am 23 years old.
3. String concatenation using String.join() method in Java 8 and Beyond
In Java 8 and later versions, we can use join() method of String class, which offers a more concise and readable way to concatenate strings. It takes two arguments: a delimiter (i.e. separator) and an array of string objects. Let’s take an example based on it.
Program code 9:
package stringPrograms; public class StringJoinExample { public static void main(String[] args) { String s1 = new String("Scientech"); String s2 = new String("Easy"); String s = String.join(" ", s1,s2); System.out.println(s.toString()); } }
Output: Scientech Easy
In the above example, we have stored the result of String.join(“”, s1, s2) method into a variable s of type string. We have used white space as a separator which is specified inside the quotation marks, followed by the string objects or array of string objects.
4. String concatenation using StringJoiner class in Java 8
Java 8 introduced a StringJoiner class to concatenate string objects efficiently. This class has all the functionalities of String.join() method. Here’s an example:
Program code 10:
package stringPrograms; import java.util.StringJoiner; public class StringJoinerExample { public static void main(String[] args) { // Create a StringJoiner object with a delimiter. StringJoiner joiner = new StringJoiner(", "); // Adding string elements to the StringJoiner. joiner.add("Apple"); joiner.add("Banana"); joiner.add("Cherry"); // Get the concatenated string String result = joiner.toString(); // Display the concatenated string System.out.println("Concatenated String: " + result); } }
Output: Concatenated String: Apple, Banana, Cherry
In this example, we have created a StringJoiner object, specifying a delimiter (in this case, “, “). We then used the add() method to add individual strings to the StringJoiner. After that, we have used toString() method to obtain the concatenated string with the specified delimiter. This technique is especially useful when we want to join elements with a separator, such as creating comma-separated lists or other formatted strings.
5. String concatenation using Collectors.joining() method in Java 8
In Java 8 and later version, we can also use the Collectors.joining() method to concatenate string objects efficiently. This method joins the input element in a similar order as they occur. We often use this method in concatenation with Java streams or a list of strings. Here’s an example:
Program code 11:
package stringPrograms; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class CollectorsJoiningExample { public static void main(String[] args) { // Create a list of string array. List liststr = Arrays.asList("Apple", "Banana", "Orange"); // Perform joining operation. String result = liststr.stream().collect(Collectors.joining(", ")); // Display the result. System.out.println(result.toString()); } }
Output: Apple, Banana, Orange
Program code 12:
package stringPrograms; import java.util.stream.Collectors; import java.util.stream.Stream; public class CollectorsJoiningExample { public static void main(String[] args) { // Create a stream of strings. Stream stringStream = Stream.of("Apple", "Banana", "Orange"); // Use Collectors.joining() to concatenate the string elements with a delimiter. String result = stringStream.collect(Collectors.joining(", ")); // Display the concatenated string. System.out.println("Concatenated String: " + result); } }
Output: Concatenated String: Apple, Banana, Orange
In this example, we have created a stream of strings and then use the Collectors.joining(“, “) method to concatenate the string elements in the stream with a specified delimiter (“, “). After that, we have stored the obtained result into a variable result of string type and displayed it on the console.