Java Reference
In-Depth Information
return type
parameters
signature
public static void callBob( ... ){
method name
body
}
FIGURE 4.1:
The different parts of a method.
import
java . util .
∗
;
public class
Remodel
{
public static void
main(String [] args)
{
callBob() ;
callPeter() ;
}
public static void
callBob()
{
System. out . println (
"Paint room"
);
}
public static void
callPeter()
{
System. out . println (
"Install hardwood floor"
);
}
}
Note that method names should always start with a lowercase letter. The program will
print
Paint room
followed by
Install hardwood floor
. Note that one needs to use the
syntax:
methodName
(
...
) to call a method. In other words, we always need to use parentheses
when calling a method. The reason is that if we do not use the parentheses, then the compiler
will think that we are referring to the variable
callBob
and not the
callBob
method. For
now, all methods will be
public
and
static
.A
public
method means that the method can
be access from everywhere (i.e., a friend that can be called by anyone). A
static
method
means that the method does not have any hidden parameters. More information on both
keywords will be presented in Chapter 6.
The different parts of a method are shown in Figure 4.1. The parameters of the method
go between the parentheses. This is the information that is sent to the method. In our
example, nothing is sent to both methods. A return type of void means that the method
does not return anything. The first line of the method definition includes the name of the
method, the parameters of the method, and the return type. This line is sometimes referred
to as the
signature
of the method.
Next, we will show how data can be passed between methods. We will keep the same
example, but now the width and length of the room will be passed to Bob and Peter. Our
friends will paint and put hardwood floor in the room and will send us the bill (they are
our friends, but they will not work for nothing). Here is the modified version of the code.
import
java . util .
∗
;
public class
Remodel
{
public static void
main(String [] args)
{
double
bobPrice = callBob(8 , 12) ;
double
peterPrice = callPeter (8, 12);