5. Methods

 
[Page 134]

5.4. void Method Example

The preceding section gives an example of a nonvoid method. This section shows how to declare and invoke a void method. Listing 5.2 gives a program that declares a method named printGrade and invokes it to print the grade for a given score.

Listing 5.2. TestVoidMethod.java
 1   public class   TestVoidMethod { 2   public static void   main(String[] args) { 3  printGrade(   78.5   );  4 } 5 6   public static void   printGrade(   double   score) { 7   if   (score >=   90.0   ) { 8 System.out.println(   'A'   ); 9 } 10   else if   (score >=   80.0   ) { 11 System.out.println(   'B'   ); 12 } 13   else if   (score >=   70.0   ) { 14 System.out.println(   'C'   ); 15 } 16   else if   (score >=   60.0   ) { 17 System.out.println(   'D'   ); 18 } 19   else   { 20 System.out.println(   'F'   ); 21 } 22 } 23 } 

The printGrade method is a void method. It does not return any value. A call to a void method must be a statement. So, it is invoked as a statement in line 3 in the main method. This statement is like any Java statement terminated with a semicolon.

Note

A return statement is not needed for a void method, but it can be used for terminating the method and returning to the method's caller. The syntax is simply

   return   ; 

This is rare, but sometimes useful for circumventing the normal flow of control in a void function. For example, the following code has a return statement to terminate the function when the score is invalid.


   public static void   printGrade(   double   score) {    if   (score <     score >   100   )  System.out.println(   "Invalid score"   );    return   ;  }   if   (score >=   90.0   ) { System.out.println(   'A'   ); }   else if   (score >=   80.0   ) { System.out.println(   'B'   ); }   else if   (score >=   70.0   ) { 

[Page 135]
 System.out.println(   'C'   ); }   else if   (score >=   60.0   ) { System.out.println(   'D'   ); }   else   { System.out.println(   'F'   ); } } 

 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net