Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

regarding String

 
MoonChinn Goh
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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()

vs
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
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic