Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Difference between '+' and concat() method in String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Difference between Watch "Difference between New topic
Author

Difference between '+' and concat() method in String

Vijaylaxmi Agarwal
Greenhorn

Joined: Sep 23, 2008
Posts: 3
Hi,

Can anybody tell me what is the difference between '+' and concat() method in String.

Thanks in advance

Vijaylaxmi
arulk pillai
Author
Ranch Hand

Joined: May 31, 2007
Posts: 3219
I think there is no difference. I think both use a StringBuffer under the covers and do a toString() method at the end.


Java Interview Questions and Answers Blog | Amazon.com profile | Java Interview Books
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

Not quite. + does use a StringBuffer or StringBuilder, but concat() creates a new char[] with the contents of the current String and the String to append, and returns a new String based on that array:

I can actually see one more improvement on that which Sun have overlooked:


Now, if you concatenate only 2 strings the difference in performance will be minimal, but otherwise using + will result in fewer objects created, if there is a difference. However, its internal capacity can increase exponentially (it tries to use (value.length + 1) * 2 if the contents would not fit), so in the end it could be worse.

Still, using + is the usual way to go. Don't start using concat unless you find you really need to improve on performance.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Difference between '+' and concat() method in String
 
Similar Threads
.append() method
Difference between concat() method and '+'operator
String Concatination
append AND concat
what is the diff? (Strings again)