Java Reference
In-Depth Information
The interface terminology is also used for individual methods. For example, the
String
docu-
mentation shows us the interface of the
length
method:
public int length()
Returns the length of this string. The length is equal to the number of Unicode code
units in the string.
Specified by:
length in interface CharSequence
Returns:
the length of the sequence of characters represented by this object.
The interface of a method consists of the
signature
of the method and a comment (shown here
in italics). The signature of a method includes (in this order):
■
an access modifier (here
public
), which we shall discuss below;
■
the return type of the method (here
int
);
■
the method name;
■
a list of parameters (which is empty in this example).
The interface provides everything we need to know to make use of this method.
5.3.2
Using library-class methods
Back to our
TechSupport
system. We now want to improve the processing of input a little. We
have seen in the discussion above that our system is not very tolerant: if we type “Bye” or
“ bye” instead of “bye”, for instance, the word is not recognized. We want to change that by
adjusting the text read in from a user so that these variations are all recognized as “bye”.
The documentation of the
String
class tells us that it has a method called
trim
to remove
spaces at the beginning and the end of the string. We can use that method to handle the second
problem case.
Concept:
Exercise 5.7
Find the
trim
method in the
String
class's documentation. Write down the
signature of that method. Write down an example call to that method on a
String
variable
called
text
.
Immutable
objects.
An object
is said to be immu-
table if its contents
or state cannot be
changed once it
has been created.
Strings are an ex-
ample of immutable
objects.
One important detail about String objects is that they are
immutable
—that is, they cannot be
modified once they have been created. Note carefully that the
trim
method, for example, re-
turns a new string; it does not modify the original string. Pay close attention to the following
“Pitfall” comment.
Search WWH ::
Custom Search