Java Reference
In-Depth Information
values that were displayed; for example, the
charAt()
method returned a character at a
specified position in the string.
The value returned by a method also can be stored in a variable:
String label = “From”;
String upper = label.toUpperCase();
In the preceding example, the
String
object
upper
contains the value returned by calling
label.toUpperCase()
—the text “FROM”, an uppercase version of “From”.
If the method returns an object, you can call the methods of that object in the same state-
ment. This makes it possible for you to nest methods as you would variables.
Earlier today, you saw an example of a method called with no arguments:
myCustomer.cancelAllOrders();
3
If the
cancelAllOrders()
method returns an object, you can call methods of that object
in the same statement:
myCustomer.cancelAllOrders().talkToManager();
This statement calls the
talkToManager()
method, which is defined in the object
returned by the
cancelAllOrders()
method of the
myCustomer
object.
You can combine nested method calls and instance variable references, as well. In the
next example, the
putOnLayaway()
method is defined in the object stored by the
orderTotal
instance variable, which itself is part of the
myCustomer
object:
myCustomer.orderTotal.putOnLayaway(itemNumber, price, quantity);
This manner of nesting variables and methods is demonstrated in
System.out.
println()
, the method you've been using in all program examples to display
information.
The
System
class, part of the
java.lang
package, describes behavior specific to the com-
puter system on which Java is running.
System.out
is a class variable that contains an
instance of the class
PrintStream
representing the standard output of the system, which
is normally the screen but can be redirected to a printer or file.
PrintStream
objects have
a
println()
method that sends a string to that output stream.
Class Methods
Class methods, like class variables, apply to the class as a whole and not to its instances.
Class methods are commonly used for general utility methods that might not operate
directly on an instance of that class but do fit with that class conceptually.