[Logo] JavaRanch » JavaRanch Saloon
  Search | FAQ | Recent Topics | Hot Topics
Register / Login


Reply Bookmark it! Watch this topic JavaRanch » Forums » Professional Certification » Programmer Certification (SCJP)
 
RSS feed
 
New topic
Author

string concatenation

Naresh Chaurasia
Ranch Hand

Joined: May 18, 2005
Messages: 228

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
Messages: 1776

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
Messages: 228

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

SCJP 1.4, SCWCD1.4, OCA(1Z0-007)
Henry Wong
author
Bartender

Joined: Sep 28, 2004
Messages: 10022

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
Messages: 25

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
SCJP 6 |
Happy Diwali ....
Asmita Khamkar
Greenhorn

Joined: Mar 28, 2009
Messages: 20

yes you are right.
Bob Wheeler
Ranch Hand

Joined: Apr 24, 2009
Messages: 308

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
JavaEnterpriseEditionFaq - TomcatFaq
 
jQuery in Action
 
 
Reply Bookmark it! Watch this topic JavaRanch » Forums » Professional Certification » Programmer Certification (SCJP)
 
RSS feed
 
New topic
hibernate profiler