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

style2pic

Style 2:  Our second style of method will take arguments (parameters) but will not return a value.  The parameter list in the parentheses specifies the types and number of arguments that are passed to the method.
    

//Demo Program for Methods
import java.util.Scanner;
public class DisplayClass2 {
      public static void main (String[ ] args)  {

          
greeting(5);  // Method call passing argument 5 to method 
   

           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));
          

           greeting(number);
//Method call again with a variable argument
          //The value stored in "number" will be passed to the method.
          reply.close();
      }


    
// Method for greeting
    
public static void greeting(int x)   //parameter shows need for int
     {
          int i;  
// declaring LOCAL variable*
          for(i = 0; i < x; i++)
          {
               System.out.print("Hi ");
          }
          System.out.println( );
    }
}  

Output:

Hi Hi Hi Hi Hi

Please enter value(1-10): 4

Hi Hi Hi Hi

*  A local variable is a variable that is used only within the method. Such a variable is NOT recognized by main.  When execution returns to main, the local variable will no longer be available for use.

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