Reputation: 4520
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()
?
Upvotes: 0
Views: 100
Reputation: 1070
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)
Upvotes: 1
Reputation: 26961
There's are difference.
If aStr
is null, then aStr.concat(bStr)
>> NPE
s
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.
Upvotes: 3