String Concatenation in Java with Example

Java String Concatenation | 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.

A string in Java can be concatenated with two or more strings or a string with a number or symbol to display information as per requirements.

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, then you see your complete name as a single string. This is a realtime use of string concatenation in Java.

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:

  1. By concat() method.
  2. 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”.

1. Let’s take a simple example program in which we will concatenate two strings using concat() method. Look at the source code.

Program code:

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:

String concatenation in Java using concat() method

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.


2. 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:

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:
String Concatenation by concat() method in Java
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.


Consider the following example code given below:

Program code:

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.

Allotting memory for string objects

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:

package stringPrograms; 
public class StringConcatenationTest4 
{ 
public static void main(String[] args) 
{ 
 String s1 = "Shubh" + " Deep"; 
 System.out.println(s1); // Shubh Deep 
 } 
}
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.

For example, 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:

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.


Hope that this tutorial has covered almost all the important points related to string concatenation in java with example programs and memory concept. I hope you will have understood and enjoyed it.
Thanks for reading!!!

Next ⇒ Substring in Java⇐ PrevNext ⇒

Leave a Comment