• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

regarding String

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic