3 Best Ways In Java String Concatenation

String concatenation is one of the paramount method in java. Here you will learn 3 best ways in java string concatenation.

There are three methods in java to concatenate strings and they are,

  • StringBuffer.append method
  • String.concat method
  • Using + operator

Let us understand each method with an example below,

3 Best Ways In Java String Concatenation

Method 1: String concatenation is performed through StringBuffer class which has method called append().

Here string concatenation operator produce new string by appending the second operand onto the end of first operand.

Example: 3 Best Ways In Java String Concatenation

Also Read – Two Best Ways In Java To Sort String Array

public class Java_String_Concatenation {

public static void main(String[] args) {
 
String str_First = "Flower";
String str_Second = "Brackets";
 
// Using StringBuffer.append method
 
String str_Concat = new StringBuffer().append(str_First).append(str_Second).toString();
 
System.out.println("String concatenation using StringBuffer.append method - " + str_Concat);

}

}

Output: String concatenation using StringBuffer.append method – FlowerBrackets


Method 2: String.concat method is one of the method to concatenate two strings.

In this method specified string concatenates to the end of given string.

Let’s see its example below,

Example: 3 Best Ways In Java String Concatenation

public class Java_String_Concatenation {

public static void main(String[] args) {
 
String str_First = "Flower";
String str_Second = "Brackets";
 
// Using String.concat method
 
String str_Concat = str_First.concat(str_Second);
 
System.out.println("String concatenation using String.concat method - " + str_Concat);

}

}

Output: String concatenation using String.concat method – FlowerBrackets


Method 3: In this method of java string concatenation, (+) operator is used which adds string.

Example:

public class Java_String_Concatenation {

public static void main(String[] args) {
 
// Using (+) operator to concatenate strings
 
String str_Concat = "Flower" + "Brackets";
 
System.out.println("String concatenation using (+) operator - " + str_Concat);

}

}

Output: String concatenation using (+) operator – FlowerBrackets


NOTE:

In string concatenation, concatenate operator (+) can concat primitive values also. Let’s take a look at an example,

Example:

public class Java_String_Concatenation {

public static void main(String[] args) {
 
// (+) operator can concat primitive values also
 
String str_Concat = 10 + 4 + "Flower" + "Brackets" + 64 + 37;
 
System.out.println("(+) operator can concat primitive values also - " + str_Concat);

}

}

Output: 

(+) operator can concat primitive values also – 14FlowerBrackets6437

About the author

admin

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *