Java Reference
In-Depth Information
S
TRING
B
UFFERS
Java provides a
StringBuffer
class, which is a class similar to
String
, except that ob-
jects of this class type can be modified. Developers use objects of this type instead
of
String
s when the text contained in the object must be modified frequently.
StringBuffer
s have a size attribute and are automatically increased in size as neces-
sary. The only real downside to
StringBuffer
s is that they do not perform as well in
some cases as
String
s do, and you cannot use the + operator for concatenation.
StringBuffer
s can be converted into
String
s using the
toString()
method.
Conversely, any data type can be easily added to a
StringBuffer
using the
append()
method. In this case, the same operator overloading conventions defined by the
String
class are used.
Some particularly useful
StringBuffer
methods are listed in Table 8.3. Unless
otherwise noted, the return type is a
StringBuffer
, and this
StringBuffer
is modi-
fied by the method.
TABLE 8.3 STRING MANIPULATION IN JAVA AND COBOL
Method
Description
COBOL Equivalent
append (datatype arg)
Arg is converted into a String and
MOVE NUMBER TO NUMBER-
added to the end of StringBuffer.
AS-Z9 STRING NUMBER-AS-Z9
TO STRING1
char charAt (int index)
Returns the character at position
MOVE
STRING2
(POS:1) TO
index in the StringBuffer.
CHARACTER
setCharAt (int index,
The character at position index is
MOVE
CHARACTER
TO
char character)
replaced with character.
STRING2
(POS:1)
insert (int offset,
Arg is converted first to a String and
MOVE
NUMBER
TO
datatype arg)
then placed in StringBuffer starting
NUMBER-AS-Z9
MOVE
at position offset.
STRING1-REDEFINES-
NUMBER- AS-Z9
TO
STRING2
(POS:SIZE)
int length ()
Return the length of StringBuffer.
Items are always fixed length,
defined at compile time.
replace (int offset,
Replace the characters in
MOVE
STRING1
(POS:LEN) TO
int length, String str)
StringBuffer starting at offset for the
STRING2
number of chars in length with the
characters in string.
continued