String concatenation in java

Let’s learn string concatenation in java.

String concatenation in java

String concatenation concatenates two or more strings to form a new string. Let’s see few methods to concatenate two strings in java,

  • String concatenation by concat() method
  • String concatenation by string concatenation operator (+)
  • String concatenation by StringBuilder

String concatenation by concat() method: String concat method concatenates specified string to end of given string. Let’s see an example of concat() method,

Also read – sparse matrix and its representations in java

public class StringConcatMethodDemo 
{
   public static void main(String[] args) 
   {
      String str1 = "Flower "; 
      String str2 = "Brackets"; 
      String str3 = str1.concat(str2); 
      System.out.println(str3); 
   }
}



Output:

string concatenation in java

String concatenation by string concatenation operator (+):  string concatenation operator (+) is used to add strings and it considered as best way to concatenate strings. Here’s an example,

public class StringConcatenationDemo 
{
   public static void main(String[] args) 
   { 
      String str = "Flower" + " Brackets"; 
      System.out.println(str);
   }
}



Output:

Flower Brackets

But java compiler transforms above code to,

String str = (new StringBuilder()).append("Flower").append(" Brackets").toString();



Because concatenation is executed through StringBuilder or StringBuffer class and its append method. We can use concat() method on primitive values. For example,

public class StringConcatenationDemo 
{
   public static void main(String[] args) 
   { 
      String str = 40 + 10 + "Arjun" + 60 + 80; 
      System.out.println(str);
   }
}



Output:

50Arjun6080


String concatenation by StringBuilder

Unlike String, StringBuilder class can be muted. The principal operation of a StringBuilder are append and insert which are overloaded to accept data of any type.

public static String concat(String str1, String str2)
{
   return new StringBuilder(str1).append(str2).toString();
}



How to concatenate two strings using scanner

Now let’s learn how to concatenate two strings in java using scanner. To concatenate two strings we are using string concatenation operator (+).

Here’s the java program to concatenate two strings,

import java.util.Scanner;

public class StringConcatenationDemo 
{
   public static void main(String[] args) 
   {
      String str1, str2;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter first string: ");
      str1 = sc.nextLine();
      System.out.println("Please enter second string: ");
      str2 = sc.nextLine();
      System.out.println("Concatenate two strings in java using scanner: ");
      System.out.println(str1 + " " + str2);
      sc.close();
   }
}



Output:

Please enter first string:
hello
Please enter second string:
world
Concatenate two strings in java using scanner:
hello world