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()?

4
  • 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. Commented May 22, 2015 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. Commented May 22, 2015 at 10:50
  • The + operation is applied in compile-time if possible. Commented May 22, 2015 at 11:05
  • Hope [this][1] answers your question [1]: stackoverflow.com/questions/47605/… Commented May 22, 2015 at 11:18

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.