Java Reference
In-Depth Information
concatenates
"hello"
,
"BC"
and
22
. The concatenation can be performed as follows:
String s =
new
StringBuilder().append(
"hello"
).append(
"BC"
).
append(
22
).toString();
First, the preceding statement creates an
empty
StringBuilder
, then appends to it the
strings
"hello"
and
"BC"
and the integer
22
. Next,
StringBuilder
's
toString
method
converts the
StringBuilder
to a
String
object to be assigned to
String
s
. The statement
s +=
"!"
;
can be performed as follows (this may differ by compiler):
s =
new
StringBuilder().append(s).append(
"!"
).toString();
This creates an empty
StringBuilder
, then appends to it the current contents of
s
fol-
lowed by
"!"
. Next,
StringBuilder
's method
toString
(which must be called
explicitly
here) returns the
StringBuilder
's contents as a
String
, and the result is assigned to
s
.
StringBuilder
provides overloaded
insert
methods to insert values of various types at
any position in a
StringBuilder
. Versions are provided for the primitive types and for
character arrays,
String
s,
Object
s and
CharSequence
s. Each method takes its second ar-
gument and inserts it at the index specified by the first argument. If the first argument is
less than
0
or greater than the
StringBuilder
's length, a
StringIndexOutOfBounds-
Exception
occurs. Class
StringBuilder
also provides methods
delete
and
deleteCharAt
to delete characters at any position in a
StringBuilder
. Method
delete
takes two argu-
ments—the starting index and the index one past the end of the characters to delete. All
characters beginning at the starting index up to but
not
including the ending index are de-
leted. Method
deleteCharAt
takes one argument—the index of the character to delete.
Invalid indices cause both methods to throw a
StringIndexOutOfBoundsException
.
Figure 14.14 demonstrates methods
insert
,
delete
and
deleteCharAt
.
1
// Fig. 14.14: StringBuilderInsertDelete.java
2
// StringBuilder methods insert, delete and deleteCharAt.
3
4
public class
StringBuilderInsertDelete
5
{
6
public static void
main(String[] args)
7
{
8
Object objectRef =
"hello"
;
9
String string =
"goodbye"
;
10
char
[] charArray = {
'a'
,
'b'
,
'c'
,
'd'
,
'e'
,
'f'
};
11
boolean
booleanValue =
true
;
12
char
characterValue =
'K'
;
13
int
integerValue =
7
;
14
long
longValue =
10000000
;
15
float
floatValue =
2.5f
;
// f suffix indicates that 2.5 is a float
16
double
doubleValue =
33.333
;
17
Fig. 14.14
|
StringBuilder
methods
insert
,
delete
and
deleteCharAt
. (Part 1 of 2.)