String concatenation in java

In this post we are going to 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.concat() method
  • + operator
  • StringBuilder

Java String 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 operator (+):  (+) operator is used to add string. 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 in java, 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


Using 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();
}