Java Reference
In-Depth Information
String saying = proverb.toString();
The object
saying
will contain "
Many
hands
make
light
work
".
The
toString()
method is used extensively by the compiler together with the
append()
method to
implement the concatenation of
String
objects. When you write a statement such as:
String saying = "Many" + " hands" + " make" + " light" + " work";
the compiler will implement this as:
String saying = new StringBuffer().append("Many").append(" hands").
append(" make").append(" light").
append(" work").toString();
The expression to the right of the
=
sign is executed from left to right, so the segments of the string are
appended to the
StringBuffer
object that is created until finally the
toString()
method is
invoked to convert it to a
String
object.
String
objects can't be modified, so any alteration or
extension of a
String
object will involve the use of a
StringBuffer
object, which can be changed.
Summary
You should now be thoroughly familiar with how to create and use arrays. Most people have little trouble
dealing with one-dimensional arrays, but arrays of arrays are a bit more tricky so try to practice using these.
You have also acquired a good knowledge of what you can do with
String
and
StringBuffer
objects. Most operations with these objects are very straightforward and easy to understand. Being able
to decide which methods you should apply to the solution of specific problems is a skill that will come
with a bit of practice.
The essential points that we have discussed in this chapter are:
You use an array to hold multiple values of the same type, identified through a single
variable name.
❑
You reference an individual element of an array by using an index value of type
int
. The index
value for an array element is the offset of that element from the first element in the array.
❑
An array element can be used in the same way as a single variable of the same type.
❑
You can obtain the number of elements in an array by using the
length
member of the
array object.
❑
An array element can also contain an array, so you can define arrays of arrays, or arrays of
arrays of arrays…
❑
A
String
object stores a fixed character string that cannot be changed. However, you can
assign a given
String
variable to a different
String
object.
❑
You can obtain the number of characters stored in a
String
object by using the
length()
method for the object.
❑