Difference between concat() and + operator in Java

In this post, we will discuss the difference between concat() and + operator (String concatenation operator) in Java.


 

1. NullPointerException

We can concatenate a string to another string using concat() method as shown below:

Now if string a is null, this results in a NullPointerException. On the other hand, string concatenation operator won’t result in any exception if either of the string is null.

 

2. Type of arguments

The concat() method only accepts a String object as an argument, while the + operator will accept anything. If an object is passed to the + operator, it gets converted to a string by toString() method of that object. If a null reference variable is passed to the + operator, it gets converted to string "null".

 
Otherwise, all primitive types (int, char, double or float) gets converted to a String by calling the corresponding conversion method of associated Wrapper class (Integer, Character, Double, Float). Note that compiler may optimize away the creation of a wrapper object by converting directly from a primitive type to a string.

 

3. Java Compiler Optimizations

To increase the performance of repeated string concatenation, a Java compiler uses the StringBuffer class to reduce the number of intermediate String objects. Therefore,

is the equivalent of

The concat() method uses superfast arraycopy() method of Java’s System class for concatenation as evident from Java 8 source code below:

 

 

4. Performance

As discussed, while performing String concatenations using + operator, Java compiler silently creates an intermediate StringBuilder object, appends the strings, and finally calls toString() method. This results in major performance issues if length of the string increases.

It is recommended to use the + operator if number of operations is less and concat() method when the number of operations are more. Here’s performance benchmark test that proves it:

 

Download   Run Code

Output (will vary):

i = 1     : 2758
i = 10    : -14961
i = 100   : -415410
i = 1000  : -4423247
i = 10000 : -149126730

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of