File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes What is the best way to do string concatenation? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "What is the best way to do string concatenation?" Watch "What is the best way to do string concatenation?" New topic
Author

What is the best way to do string concatenation?

Franco Finstad
Greenhorn

Joined: May 02, 2003
Posts: 22
What is the best way to do string concatenation? I read that using "+" on a string object uses StringBuffer behind the scenes so it seems that using StringBuffer explicitly is unecessary.
So, should I do:
myString + "foo" + "bar";
or
myStringBuffer.append("foo").append("bar");
Any help is appreciated.
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
If you do the first you will end up with a String object that is immutable.
If you do the second you will end up with a StringBuffer object that is mutable.
Which do you WANT?


"JavaRanch, where the deer and the Certified play" - David O'Meara
Arvind Dua
Greenhorn

Joined: Mar 28, 2003
Posts: 5
Besides what Cindy said another criteria for deciding whether to use a StringBuffer or String concatenation is the number of String Objects you need to concatenate. If it is only 2 both are equal in terms of performance . But if the number of Strings you want to concatenate is more, I will certainly prefer StringBuffer because everytime I concatenate two Strings a new Object is created( because String objects are immutable and cannot be modified) but if its a StringBuffer, the same Object is modified to hold the concatenated String and no new Objects are created.
Hope this helps !!
[ May 22, 2003: Message edited by: Arvind Dua ]
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 5288
    
  10

You might want to consider readability before trying to second guess the compiler's optimization capabilities. A succession of append()s to a StringBuffer would probably throw another programmer off at first glance. Try to write clear code first; use a profiler to find bottlenecks.
[ May 22, 2003: Message edited by: Junilu Lacar ]

Junilu - [How to Ask Questions] [How to Answer Questions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What is the best way to do string concatenation?