ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Sample Java Program for Beginners: Ways to Concatenate String in Java

Updated on April 9, 2013

Concatenate String in Java with StringBuffer() and StringBuilder()

What is Concatenation?

‘Concatenate the Strings’ means that you would join the 2 strings together. String concatenation is sometimes needed inside the program to achieve the program’s goal. There are 3 ways to concatenate the strings.

1. Using the + operator

2. Using the StringBuffer()

3. Using the StringBuilder()

The + Operator

The + operator is the easiest way to concatenate a String. You just joined the 2 strings and add a + operator in between. For example:

String string1 = “This is ”;

String string2 = “a String.”;

System.out.print(string1 + string2);

Using the StringBuffer()

StringBuffer is use for append() and insert() operation. To use String Buffer on concatenating a String, just declare an object and use the append() method. For example:

StringBuffer object = new StringBuffer();



Using the StringBuilder()

StringBuilder() was made to make StringBuffer() work faster. StringBuffer() works slow because it is synchronized, opposite to the StringBuilder(). StringBuilder() is mainly use also for append() and insert() methods. If you want your program executes faster, use StringBuilder() instead. The way to use it do not have much difference on the way of using StringBuffer(), instead of calling StringBuffer() just call the StringBuilder(). For example:

StringBuilderr object = new StringBuilder();


Sample Java Code for Concatenating Strings

package concatenate_a_string;

public class Main {

    public static void main(String[] args) {

        String variableString1 = "+ Operator ";
        String variableString2 = "String Concatenation";

        String variableString3 = "String Buffer ";
        String variableString4 = "String Concatenation";

        String variableString5 = "String Builder ";
        String variableString6 = "String Concatenation";

        System.out.println(variableString1 + variableString2);

        StringBuilder access = new StringBuilder();

        StringBuffer access2 = new StringBuffer();



Sample Output:


    0 of 8192 characters used
    Post Comment

    No comments yet.