StringBuffer is a peer class of String that provides much of the functionality of strings.
As you know, String represents fixed-length, immutable character sequences. In contrast,
StringBuffer represents growable and writeable character sequences. StringBuffer
may have characters and substrings inserted in the middle or appended to the end.
StringBuffer will automatically grow to make room for such additions and often has
more characters preallocated than are actually needed, to allow room for growth. Java
uses both classes heavily, but many programmers deal only with String and let Java
manipulate StringBuffers behind the scenes by using the overloaded + operator.
StringBuffer Constructors
StringBuffer defines these three constructors:
The default constructor (the one with no parameters) reserves room for 16
characters without reallocation. The second version accepts an integer argument that
explicitly sets the size of the buffer. The third version accepts a String argument that
sets the initial contents of the StringBuffer object and reserves room for 16 more
characters without reallocation. StringBuffer allocates room for 16 additional
characters when no specific buffer length is requested, because reallocation is a costly
process in terms of time. Also, frequent reallocations can fragment memory. By
allocating room for a few extra characters, StringBuffer reduces the number of
reallocations that take place.
As you know, String represents fixed-length, immutable character sequences. In contrast,
StringBuffer represents growable and writeable character sequences. StringBuffer
may have characters and substrings inserted in the middle or appended to the end.
StringBuffer will automatically grow to make room for such additions and often has
more characters preallocated than are actually needed, to allow room for growth. Java
uses both classes heavily, but many programmers deal only with String and let Java
manipulate StringBuffers behind the scenes by using the overloaded + operator.
StringBuffer Constructors
StringBuffer defines these three constructors:
- StringBuffer( )
- StringBuffer(int size)
- StringBuffer(String str)
The default constructor (the one with no parameters) reserves room for 16
characters without reallocation. The second version accepts an integer argument that
explicitly sets the size of the buffer. The third version accepts a String argument that
sets the initial contents of the StringBuffer object and reserves room for 16 more
characters without reallocation. StringBuffer allocates room for 16 additional
characters when no specific buffer length is requested, because reallocation is a costly
process in terms of time. Also, frequent reallocations can fragment memory. By
allocating room for a few extra characters, StringBuffer reduces the number of
reallocations that take place.
No comments:
Post a Comment