Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String class: + vs concat

 
Sam Drake
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is it recommended to use concat method instead of + operator? Please explain the difference. I'm a beginner.
regards,
sam.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Curious. I'd never loooked at concat before. About the only thing that looks different is when the string you are adding has zero length it just gives you back the original instead of creating a new String. The + operator can be a bit expensive ... if you are doing hundreds or thousands of string building operations look into StringBuffer.append(). It is common to see a method build up a StringBuffer and then return or use theBuffer.toString() at the end.
 
Pradeep bhatt
Ranch Hand
Posts: 8927
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where did you get the statement ? StringBuffers are recomended over String for concatination operations.

Originally posted by Sam Drake:
Why is it recommended to use concat method instead of + operator? Please explain the difference. I'm a beginner.
regards,
sam.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Pradeep Bhat:
Where did you get the statement ? StringBuffers are recomended over String for concatination operations.

And even that's an oversimplification. StringBuffers are actually rather rarely needed to be used explicitely.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic