Tutorials

Java String


Java String Concatenation


If we want to concatenate two String object in java then it can be done in following ways:

  • Using + operator
  • Using concat() method

Using + operator

 

If you have read our tutorial on loop control then you must have seen we have used + operator number of times for concatenation purpose. Let’s see an example again.

 

Example:

 

public class ConcatString {

 

      public static void main(String[] args) {

            String str = "Raju" + "Ryan";

            System.out.println("Concatenated string is: "+ str);

      }

 

}

OUTPUT:

Concatenated string is: RajuRyan

 

Note 1: In output you can see RajuRyan is printed without any space. If you want space between two words then remove:

String str = "Raju" + "Ryan";

With

String str = "Raju" + " " + "Ryan";

OUTPUT:

Concatenated string is: Raju Ryan

 

Note 2: In the System.out.println, if you notice we have used + operator there as well.

This is why result of str variable (RajuRyan) is again concatenated to Concatenated string is: and giving us output:

Concatenated string is: RajuRyan

 

Using concat() method

In java concat() is simple to use. Just use it as shown in below example to concatenate two String objects.

 

Example:

 

package string;

 

public class ConcatString1 {

 

      public static void main(String[] args) {

            String firstString = "Rajneesh";

            String secondString = "Shukla";    

            String fullName = firstString.concat(secondString);

 

            System.out.println(fullName);

      }

}

OUTPUT:

RajneeshShukla

 

Note 1: In output you can see RajuRyan is printed without any space. If you want space between two words then use the following statement,

String fullName = firstString.concat(" ").concat(secondString);

OUTPUT:

Rajneesh Shukla



Please Share this page
Views : 76
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!