Java Reference
In-Depth Information
" 134 12 1 0 21 "
We want to write a program segment that removes the first integer from
p
and
stores it in
int
variable
d
. We begin by breaking it down into a sequence of steps.
This is an example of
top-down design
, or
stepwise refinement
(see Sec. 2.5).
1. Remove the blanks from the beginning of
p
;
2. Add a blank to the end of
p
(so we know
p
ends in a blank);
3. Find the index
i
of the first blank in
p
;
4. Store
p[0..i-1]
, as an integer and not as a string, in
d
;
5. Remove
p[0..i-1]
from
p
.
These steps are written in English and our non-Java notation. This allows us
to concentrate on the steps involved without worrying about how they are imple-
mented in Java. The curious step is step 2. It was inserted so that, during step 3,
we could assume that there was at least one blank after the first integer.
If you execute the sequence yourself, using
p
as given above, you will see
that it stores
134
in
d
and changes
p
to
" 12 1 0 21 "
.
How do we javanize each of the steps? Looking carefully through the meth-
ods of class
String
, we see that we can use functions
trim
,
indexOf
, and
sub-
string
, and to convert a string of digits to an integer, we use wrapper function
Integer.valueOf
. Here is the sequence of steps, in Java:
p= p.trim()
;
p= p + " ";
int
i= p.indexOf(" ");
d= Integer.parseInt(p.substring(0,i));
p= p.substring(i);
5.2.5
Class StringBuffer
An instance of class
String
is
immutable
: it cannot be changed. For example, in
the program segment at the end of the previous subsection, we could not append
a blank to
p
but had to create an entirely new string and assign it to
p
:
Lesson
page 5-4
p= p + " ";
Package
java.lang
contains class
StringBuffer
, whose instances are
sequences of characters that are
mutable
: they can be changed. For example, to
append a blank to a
StringBuffer
variable
q
, use the procedure call:
q.append(" ");
When a string has to be changed a lot, it may be advantageous to convert it
to class
StringBuffer
, perform the changes on the
StringBuffer
, and then
convert the result back to a
String
. This can improve performance by eliminat-
ing the creation of many strings during the manipulation. We illustrate this later,
but first we summarize the methods available in instances of
StringBuffer
.
Search WWH ::
Custom Search