Java String concatenate example


String concatenate is a way to join multiple Strings to create large String. There are many places where we use to do String concatenate.
For example: When you override toString() method of object, you concatenate multiple attributes to create a big String that represent that object.

3 ways to concatenate String

  1. UsingĀ + operator
  2. Using String’s concat method
  3. Using StringBuffer or StringBuilder

+ Operator:

Although java does not support operator overloading but you can concatenate two String usingĀ + operator.

Here result will be “HelloJava2blog” .

String’s concat method:

You can use String ‘s concat method to concatenate two String.

Here result will be “HelloJava2blog” .

StringBuilder or StringBuffer:

You can use StringBuilder or StringBuffer’s append method to concatenate two String.

It is fastest way to concatenate two String.

Performance Comparison:

  1. + Operator is not recommended for large String concatenation as it creates lots of temporary object and also some what slow.
  2. If you have lot of concatenation, StringBuffer or StringBuilder is recommended as it is fastest of all.

Java program for String concatenation:

When you run above program, you will get below output


Add Comment