Java Reference
In-Depth Information
5.4 void Method Example
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 5.2 gives a program that defines a method named
printGrade and invokes it to print the grade for a given score.
VideoNote
L ISTING 5.2 TestVoidMethod.java
1 public class TestVoidMethod {
2 public static void main(String[] args) {
3 System.out.print( "The grade is " );
4
5
6 System.out.print( "The grade is " );
7
8 }
9
10
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 }
Use void method
main method
printGrade( 78.5 );
invoke printGrade
printGrade( 59.5 );
printGrade method
public static void printGrade( double score) {
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 5.3.
invoke void method
void vs. value-returned
L ISTING 5.3 TestReturnGradeMethod.java
1 public class TestReturnGradeMethod {
2 public static void main(String[] args) {
3 System.out.print( "The grade is " +
main method
getGrade( 78.5 )
);
4 System.out.print( "\nThe grade is " +
getGrade( 59.5 )
);
invoke getGrade
5 }
6
 
 
Search WWH ::




Custom Search