Java String Handling

Java String Concatenate Example

Java String Concatenate example shows how to concatenate strings in Java. Example also shows difference between concatenation operator (+) vs concat method vs concatenation using StringBuilder/StringBuffer.

How to concatenate strings in Java?

There are several ways using which you can concatenate String in Java as given below.

1) Concatenate String using concatenation operator (+)

You can use string concatenation operator “+” to concatenate two or more Strings as given below.

Output

Concatenation using + operator also works with Objects and primitive values. If the object is concatenated with the String, it is automatically converted to String using toString method of it. Primitive values are also converted to String representation using respective wrapper class’s toString method. It even concatenates null without throwing NullPointerException.

Output

2) Concatenate String using concat method of String class

You can use concat method of String class to concatenate two strings as given below.

Output

3) Concatenate String using StringBuffer/StringBuilder

StringBuffer or StringBuilder can be used to concatenate multiple strings using append method as given below.

Output

What is the best way to concatenate strings?

Difference between String concatenation using + operator, concat method and StringBuffer

1) Concatenating strings using + operator looks clean and clearly shows the purpose of the expression than concatenation using concat method. Moreover, concatenation using + might use the String objects from the pool, while String concatenation using concat method always create a new String object.

2) String concatenation using + operator is converted to more efficient code which uses append method of StringBuffer/StringBuilder class by most modern JVMs as given below.

Will be converted to

3) concat method only works with strings. You can not append other data types, such as primitive values, using concat method. While + operator works with all of them.

4) If first String is null, invoking concat method on it will throw NullPointerException while concatenating them with + will not, for example

Will print

If number of concatenation operations are small, concatenation using + operator is recommended. On the other hand, if you need to do concatenate operation in loop, using append method of StringBuffer class gives more performance.

Please let us know your views in the comments section below.

 

Tags
Join 1000+ fellow learners! Enter your email address below: