Java Reference
In-Depth Information
A
void
method does not return a value.
Key
Point
The preceding section gives an example of a value-returning method. This section shows how
to define and invoke a
void
method. Listing 6.2 gives a program that defines a method named
printGrade
and invokes it to print the grade for a given score.
VideoNote
L
ISTING
6.2
TestVoidMethod.java
1
public class
TestVoidMethod {
2
public static void
main(String[] args) {
3 System.out.print(
"The grade is "
);
4
Use
void
method
main
method
printGrade(
78.5
);
invoke
printGrade
5
6 System.out.print(
"The grade is "
);
7
printGrade(
59.5
);
printGrade
method
8 }
9
10
public static void
printGrade(
double
score) {
11
if
(score >=
90.0
) {
12 System.out.println(
'A'
);
13 }
14
else if
(score >=
80.0
) {
15 System.out.println(
'B'
);
16 }
17
else if
(score >=
70.0
) {
18 System.out.println(
'C'
);
19 }
20
else if
(score >=
60.0
) {
21 System.out.println(
'D'
);
22 }
23
else
{
24 System.out.println(
'F'
);
25 }
26 }
27 }
The grade is C
The grade is F
The
printGrade
method is a
void
method because it does not return any value. A call to a
void
method must be a statement. Therefore, it is invoked as a statement in line 4 in the
main
method. Like any Java statement, it is terminated with a semicolon.
To see the differences between a void and value-returning method, let's redesign the
printGrade
method to return a value. The new method, which we call
getGrade
, returns
the grade as shown in Listing 6.3.
invoke
void
method
void vs. value-returned
L
ISTING
6.3
TestReturnGradeMethod.java
1
public class
TestReturnGradeMethod {
2
public static void
main(String[] args) {
3 System.out.print(
"The grade is "
+ getGrade(
78.5
));
4 System.out.print(
"\nThe grade is "
+ getGrade(
59.5
));
5 }
6
main
method
invoke
getGrade
Search WWH ::
Custom Search