String Concatenation in Java

Price: INR 1,299.00
Was: INR 1,799.00

In Java String Class we can perform the concatenation of Strings, In concatenation process we form a new String which is the combination of multiple Strings. There are many ways to concatenate the Strings.

  • Concatenation operator (+)
  • StringBuffer class
  • StringBuilder class
  • String.concat() function

Let’s discuss the each way to concatenate the String in Java.

Using Concatenation Operator (+)

Java string concatenation operator (+) is used to concatenate strings. An important thing to remember about doing String concatenation is that it doesn’t modify any String object and always create a new String object. If you use literal or if the object already exists in a pool, then it may return object from String pool but otherwise, it will result in a new String object.

Never use this method while concatenating String in the loop, it will result in lots of small String garbage. Also, don’t forget to store the reference of the object returned by + operator.  You can also use this method to convert int to String in Java, provided they are always the second operand.

Output:

MerrillaKnightly
Merrilla Knightly

Concatenation using StringBuffer and StringBuilder

This is the right way to join multiple String in Java because it represents a mutable String and when you concatenate multiple small String, it won’t generate temporary intermediate String object.

This result in a lot of memory saving and reduce garbage collection time. By the way, you should always use StringBuilder instead of  StringBuffer because it provides the same functionality but without any synchronization overhead, which means faster operation. Use of StringBuffer or StringBuilder also results in fluent and readable code.

Output:

Merrilla Knightly
Merrilla Knightly

Using concat() method

Concat() is the inbuilt method in the String class. This method concatenates the specified string to the end of the current string.

Output:

MerrillaKnightly

0 Comment

Leave a Reply