String concatenation java

Hey guys!! Welcome to flower brackets blog. In this post we are going to learn string concatenation java.

string concatenation java

String concatenation is one of the paramount method in java. Let’s see how to concatenate strings in java,

  • String.concat method
  • + operator
  • StringBuilder

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

Also read – sort string array

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

Output:

Flower Brackets

concat() method internally uses Arrays.copyOf() and System.arraycopy() method.


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 methods, which are overloaded as to accept data of any type.

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

Related Posts