Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
Method Description
String[ ] split(StringregExp) Decomposes the invoking string into par ts and returns an array
that contains the result. Each par t is delimited by the regular
expression passed inregExp.
String[ ] split(StringregExp, intmax) Decomposes the invoking string into par ts and returns an array
that contains the result. Each par t is delimited by the regular
expression passed inregExp.The number of pieces is specified
bymax.Ifmaxis negative, then the invoking string is fully
decomposed. Other wise, ifmaxcontains a nonzero value,
the last entr y in the returned array contains the remainder
of the invoking string. Ifmaxis zero, the invoking string is
fully decomposed.
CharSequence
subSequence(intstar tIndex,
intstopIndex)

Returns a substring of the invoking string, beginning atstar tIndex
and stopping atstopIndex. This method is required by the
CharSequenceinter face, which is now implemented byString.

Notice that several of these methods work with regular expressions. Regular expressions
are described in Chapter 27.

StringBuffer


StringBufferis a peer class ofStringthat provides much of the functionality of strings.
As you know,Stringrepresents fixed-length, immutable character sequences. In contrast,
StringBufferrepresents growable and writeable character sequences.StringBuffermay have
characters and substrings inserted in the middle or appended to the end.StringBufferwill
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 withStringand let Java manipulateStringBuffers behind the scenes
by using the overloaded+operator.

StringBuffer Constructors


StringBufferdefines these four constructors:

StringBuffer( )
StringBuffer(intsize)
StringBuffer(Stringstr)
StringBuffer(CharSequencechars)

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 aStringargument that sets the initial contents
of theStringBufferobject and reserves room for 16 more characters without reallocation.
StringBufferallocates 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,StringBufferreduces the
number of reallocations that take place. The fourth constructor creates an object that contains
the character sequence contained inchars.

Chapter 15: String Handling 375

Free download pdf