void Method

5.2 void Method

Look at the following program that demonstrate how a method is defined and called. In this program, we have defined a method displayLine that displays a line. Execution of program start from main and when it encounters statment displayLine() control passes to method and after execution of the code of method control comes back to next statement of main method.
/**
 *   This program defines and calls a method.
 */
public class MethodDemo
{
   public static void main(String[] args)
   {
      System.out.println("Advantage of methods.");
      displayLine();
      System.out.println("Write once use many times");
      displayLine();
   }

   /**
    *      The displayLine method displays a line.
    */
   public static void displayLine()
   {
      for (int i = 1; i <= 40; i++)
      {
         System.out.print("_");
      }

      System.out.println(" ");
   }
}
Output :
Advantage of methods.
________________________________________
Write once use many times
________________________________________


Method definition

Method definition has two parts, header and body. Following figure explain each of these parts.
method-parts

Calling a Method

To call a method, simply type the name of the method followed by a set of parentheses. As we used in above example.
displayLine();

No comments:

Post a Comment

Pages