ptg7068951
Creating Behavior with Methods 141
You have been using methods throughout your programs up to this point
without knowing it, including one in particular: println(). This method
displays text onscreen. Like variables, methods are used in connection with
an object or a class. The name of the object or class is followed by a period
and the name of the method, as in screen2D.drawString()or
Integer.parseInt().
Declaring a Method
You create methods with a statement that looks similar to the statement
that begins a class. Both can take arguments between parentheses after
their names, and both use {and }marks at the beginning and end. The
difference is that methods can send back a value after they are handled.
The value can be one of the simple types such as integers or Boolean val-
ues, or it can be a class of objects.
The following is an example of a method the Virusclass can use to infect
files:
public booleaninfectFile(String filename) {
booleansuccess = false;
// file-infecting statements go here
return success;
}
This method takes a single argument: a string variable called filename,
which is a variable that represents the file that should be attacked. If the
infection is a success, the successvariable is set to true.
In the statement that begins the method, booleanprecedes the name of the
method, infectFile. This statement signifies that a booleanvalue is sent
back after the method is handled. The returnstatement is what actually
sends a value back. In this method, the value of successis returned.
If a method should not return a value, use the keywordvoid.
When a method returns a value, you can use the method as part of an
expression. For example, if you created a Virusobject called malaria, you
could use statements such as these:
if (malaria.infectFile(currentFile)) {
System.out.println(currentFile + “ has been infected!”);
} else{
System.out.println(“Curses! Foiled again!”);
}
NOTE
TheSystem.out.println()
method might seem confusing
because it has two periods
instead of one. This is because
two classes are involved in the
statement—theSystemclass
and the PrintStreamclass.
TheSystemclass has a variable
calledoutthat is a
PrintStreamobject.println()
is a method of the PrintStream
class. The System.out.print-
ln()statement means,in
effect,“Use the println()
method of the outvariable of
theSystemclass.” You can
chain together references in
this way.