Methods -- Style 3 
(does not receive arguments, does return values)

style3pic

Style 3: Our third style of method takes no arguments, but will return a value.  Up until now, we have been communicating information TO an invoked method.  Now we will be returning information FROM the method by using the method return value.  The return value can be a constant, a variable, or an expression.  The only requirement is that the return value be of the type specified in the method definition.   

A method can return only ONE value! 

A method that returns data must be called (in main) from an assignment statement or from inside an expression.

A method call (that returns a value) from main is replaced by the method's return value when the method is finished ... so be sure to do something with that return value.  Store the return value somewhere; print the return value to the screen; use the return value in a calculation; just use it!! 

//Demo Program for Methods
//this program will use two methods

import java.util.Scanner;

public class method3test {
     public static void main(String[ ] args)  {

          greeting(5);  //first method call
          int response;
          response = getNumber();   //second method call (from assignment statement)
          greeting (response);          //first method call again
    }
 

     //First Method for greeting
     public static void greeting(int x)
    {
         int i;
         for(i = 0; i < x; i++)
         {
               System.out.print("Hi ");
         }
         System.out.println( );
    }


    //Second method which returns an integer
    public static int getNumber( )
    {
         int number;
        Scanner reply = new Scanner(System.in);
        do
        {
           System.out.println("\nPlease enter value(1-10): ");
          number = reply.nextInt();
         }
        while ((number < 1) || (number > 10));  //error trap
        reply.close();
        return number;  //return the number to main (to be stored in "response")
    }
}

Output:

Hi Hi Hi Hi Hi

Please enter value(1-10): 5

Hi Hi Hi Hi Hi

divider
Return to Unit Menu |  JavaBitsNotebook.com | MathBits.com | Terms of Use  | JavaMathBits.com