• 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

String and StringBuffer (internal structure)

 
Ranch Hand
Posts: 264
Eclipse IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Everybody,
I know that StringBuffer is not mutable and String is immutable. Internally both are using array of character but how StringBuffer is using it extendable for achieving mutable feature.


Pawan
SCJP 5.0, SCWCD 1.4
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
(I think you meant to say "StringBuffer is mutable" instead of "StringBuffer is not mutable".)

The easiest way might be to just look at the source code of both classes. It comes with the JDK in a file called src.zip. In short, Stringbuffer has methods that change the underlying array of characters, while String does not.
 
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My guess is that a typical StringBuffer implementation starts off with an array of a certain size (which I believe you can also set as a constructor parameter), and whenever it needs more space, it simply creates a new array with double the capacity, and copies the old array elements over to the new array. From a computer science perspective, this is a simple way to achieve good amortized performance, despite the occasional array copying cost.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic