0

I am aware of String concatenation: concat() vs "+" operator

But i have question on usage of both concat() and + operator effectively

concat() is more efficient than + operator but still we are using + operator in few cases below

Case 1

System.out.println("Hi! Welcome: "+nameString);

Case 2:

splitting huge length line in to multiple lines(eclipse formatting)

System.out.println("Hi! Welcome: "+nameString1
                                  +nameString2
                                  +nameString3);

why still we are using + operator instead of concat()?

Community
  • 1
  • 1
Sasikumar Murugesan
  • 4,412
  • 10
  • 51
  • 74
  • Q: Why should we be using `"Hello".concat("World").concat("!")` instead of `"Hello" + "World" + "!"`? A: There's no reason to do so, because it's much more concise and readable using `+`, and the possible performance penalty is absolutely no issue 99.99999% of the time. – JimmyB May 22 '15 at 10:44
  • In fact, as @JordiCastilla pointed out, in real life, if you're worried about performance, you'll use StringBuilder anyway, which probably scales better when concat'ing more than two strings. – JimmyB May 22 '15 at 10:50
  • The `+` operation is applied in compile-time if possible. – Bubletan May 22 '15 at 11:05
  • Hope [this][1] answers your question [1]: http://stackoverflow.com/questions/47605/string-concatenation-concat-vs-operator – mrinal May 22 '15 at 11:18

2 Answers2

3

There's are difference.

If aStr is null, then aStr.concat(bStr) >> NPEs
but if aStr += bStr will treat the original value of aStr as if it were null.

Also, the concat() method accepts just String instead the + operator which converts the argument to String (with Object.toString()).

So the concat() method is more strict in what it accepts.

Also, if you have lot of String concatenations with concat() or +, I highly recommend to work with mutable StringBuilder object that will increase speed of your code.

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
1

I agree with you about concat() efficiency, but look into few issue with it,

For concat(String str)

concat() is more strict about its argument means it only accept String not any other primitive or wrapper data type (Signature concat(String str)). String a = null, String b = "ABC"; b.concat(a) Throw null pointer exception.

for + accept all data type(wrapper or primitive) where as if you work with a+=b there wont any NPE operator will silently convert the argument to a String (using the toString() method for objects)

Afgan
  • 1,022
  • 10
  • 32