wood burning stoves 2.0
The moose likes Beginning Java and the fly likes regarding String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "regarding String" Watch "regarding String" New topic

regarding String

MoonChinn Goh

Joined: Jul 25, 2002
Posts: 12
method A
String str = "[";
//one string obj has been created in String pool
String str2 = str + "hallo";
//internally translate to
//new StringBuffer(str).append("hallo").toString()

method B
String str2 = "[" + "hallo";
//internally translate to
//new StringBuffer("[").append("hallo").toString();

So, does it means that method A will be creating more objects than method B?
Someone please help to explain......

[ March 26, 2003: Message edited by: MoonChinn Goh ]
Rajeshwari Natarajan
Ranch Hand

Joined: Mar 05, 2003
Posts: 67
Yes..method A will create more objects that method B..
If u do multiple concatenation in a single line, the append() method of the StringBuffer class is called multiple times.
But only two objects are created- StringBuffer and String objects.
When u do the concatenation over multiple lines, a new String object is created everytime and for each of that a StringBuffer object is created.
Performance-wise additional method calls are far better than additinal object creation and their subsequent garbage collection.

regards<br />Rajeshwari. N
I agree. Here's the link: http://aspose.com/file-tools
subject: regarding String
It's not a secret anymore!