File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes string concatenation Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "string concatenation" Watch "string concatenation" New topic
Author

string concatenation

Naresh Chaurasia
Ranch Hand

Joined: May 18, 2005
Posts: 299
Why is string concatenation considered to be expensive operation.


SCJP 1.4, SCWCD1.4, OCA(1Z0-007)
Krishna Srinivasan
Ranch Hand

Joined: Jul 28, 2003
Posts: 1778
String is immutable. When you concat another string, it is created new object instead of manipulating the same string object. That's why is expensive when appending more string objects using +=.


KrishnaSrinivasan (SCJP 1.5, SCWCD 1.3, SCBCD 5.0)
400 Mock Questions for SCJP 1.5, SCJP 1.6, SCWCD 5.0, SCBCD 5.0
Naresh Chaurasia
Ranch Hand

Joined: May 18, 2005
Posts: 299
If i try str = str1 + str2, then how many objects get created.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 13395

Naresh Chaurasia wrote:If i try str = str1 + str2, then how many objects get created.


I believe ....

str = str1 + str2;

is converted to something like this ....

str = new StringBuilder().append(str1).append(str2).toString();


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Srikanth Nakka
Greenhorn

Joined: Apr 15, 2007
Posts: 26

If i try str = str1 + str2, then how many objects get created.


there are three objects ...... two already exists str1,str2 and new str

my doubt is that str =str + str2 ............ how many objects created

i think 3 objects are old : str , str2 and new : str
two object has reference and one object without reference
correct me if not


Thanking You,
Srikanth Nakka
Asmita Khamkar
Greenhorn

Joined: Mar 28, 2009
Posts: 23
yes you are right.
Bob Wheeler
Ranch Hand

Joined: Apr 24, 2009
Posts: 317
Henry Wong wrote:
Naresh Chaurasia wrote:If i try str = str1 + str2, then how many objects get created.


I believe ....

str = str1 + str2;

is converted to something like this ....

str = new StringBuilder().append(str1).append(str2).toString();

Looks like you are right. Quote from the API:

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.

So, if you use the '+' sign in any case a new StirngBuilder or StringBuffer object will be created.

cheers
Bob


SCJP 6 - SCJD - SCWCD 5 - SCBCD 5
JavaEnterpriseEditionFaq - TomcatFaq
 
 
subject: string concatenation
 
developer file tools