Java Reference
In-Depth Information
Note
We say “
define
a method” and “
declare
a variable.” We are making a subtle distinction
here. A definition defines what the defined item is, but a declaration usually involves
allocating memory to store data for the declared item.
define vs. declare
Calling a method executes the code in the method.
Key
Point
In a method definition, you define what the method is to do. To execute the method, you have
to
call
or
invoke
it. There are two ways to call a method, depending on whether the method
returns a value or not.
If a method returns a value, a call to the method is usually treated as a value. For example,
int
larger = max(
3
,
4
);
calls
max(3, 4)
and assigns the result of the method to the variable
larger
. Another exam-
ple of a call that is treated as a value is
System.out.println(max(
3
,
4
));
which prints the return value of the method call
max(3
,
4)
.
If a method returns
void
, a call to the method must be a statement. For example, the
method
println
returns
void
. The following call is a statement:
System.out.println(
"Welcome to Java!"
);
Note
A value-returning method can also be invoked as a statement in Java. In this case, the
caller simply ignores the return value. This is not often done, but it is permissible if the
caller is not interested in the return value.
When a program calls a method, program control is transferred to the called method. A called
method returns control to the caller when its return statement is executed or when its method-
ending closing brace is reached.
Listing 6.1 shows a complete program that is used to test the
max
method.
L
ISTING
6.1
TestMax.java
1
public class
TestMax {
2
/** Main method */
3
public static void
main(String[] args) {
4
int
i =
5
;
5
int
j =
2
;
6
int
k = max(i, j);
7 System.out.println(
"The maximum of "
+ i +
8
VideoNote
Define/invoke
max
method
main
method
invoke
max
" and "
+ j +
" is "
+ k);
9 }
10
11
/** Return the max of two numbers */
12
public static int
max(
int
num1,
int
num2) {
define method
13
int
result;
14
15
if
(num1 > num2)
16 result = num1;
17
else
18 result = num2;
19
20
return
result;
21 }
22 }
Search WWH ::
Custom Search