String concatenation in java

Let’s learn string concatenation in java.

String concatenation in java

String concatenation is nothing but combining two or more strings to form a new string.

Let’s learn few ways to concatenate strings in java.

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

String concatenation using concat() method: String concat() method concatenates specified string to end of given string.

Let’s see an example on concat method 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 using + (string concatenation) operator:  string concatenation operator (+) is used to add or concatenate strings and it considered as best way to concatenate strings in java.

Here’s an example.

// concatenation operator in java
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 using StringBuilder or StringBuffer class through its append() method.


We can use concat() method on primitive values as well. 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 using StringBuilder

Unlike String, we can mute StringBuilder class. The primary 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();
}


Also read – Bubble sort in java