Java Reference
In-Depth Information
public static int
m(String s) {
int
count =
0
;
for
(
int
i =
0
; i < s.length(); i++)
if
(Character.isUpperCase(s.charAt(i)))
count++;
return
count;
}
}
The
StringBuilder
and
StringBuffer
classes are similar to the
String
class
except that the
String
class is immutable.
Key
Point
In general, the
StringBuilder
and
StringBuffer
classes can be used wherever a string is
used.
StringBuilder
and
StringBuffer
are more flexible than
String
. You can add,
insert, or append new contents into
StringBuilder
and
StringBuffer
objects, whereas
the value of a
String
object is fixed once the string is created.
The
StringBuilder
class is similar to
StringBuffer
except that the methods for modify-
ing the buffer in
StringBuffer
are
synchronized
, which means that only one task is allowed to
execute the methods. Use
StringBuffer
if the class might be accessed by multiple tasks con-
currently. Concurrent programming will be introduced in Chapter 32. Using
StringBuilder
is
more efficient if it is accessed by just a single task. The constructors and methods in
StringBuffer
and
StringBuilder
are almost the same. This section covers
StringBuilder
. You can replace
StringBuilder
in all occurrences in this section by
StringBuffer
. The program can compile and run without any other changes.
The
StringBuilder
class has three constructors and more than 30 methods for manag-
ing the builder and modifying strings in the builder. You can create an empty string builder or
a string builder from a string using the constructors, as shown in Figure 9.11.
StringBuilder
StringBuilder
constructors
java.lang.StringBuilder
+StringBuilder()
+StringBuilder(capacity: int)
+StringBuilder(s: String)
Constructs an empty string builder with capacity
16
.
Constructs a string builder with the specified capacity.
Constructs a string builder with the specified string.
F
IGURE
9.11
The
StringBuilder
class contains the constructors for creating instances of
StringBuilder
.
9.6.1 Modifying Strings in the
StringBuilder
You can append new contents at the end of a string builder, insert new contents at a specified
position in a string builder, and delete or replace characters in a string builder, using the meth-
ods listed in Figure 9.12.
The
StringBuilder
class provides several overloaded methods to append
boolean
,
char
,
char[]
,
double
,
float
,
int
,
long
, and
String
into a string builder. For example,
the following code appends strings and characters into
stringBuilder
to form a new string,
Welcome to Java
.
StringBuilder stringBuilder =
new
StringBuilder();
stringBuilder.append(
"Welcome"
);
stringBuilder.append(
' '
);
stringBuilder.append(
"to"
);
stringBuilder.append(
' '
);
stringBuilder.append(
"Java"
);
append