5.3 Passing Arguments to a Method

Values that are sent into a method are called arguments. In Example of previous section, we defined a method displayLine that display a Line of 40 characters. To call this method we write the statement displayLine();. Now we will modify our displayLine method so that it can can accept arguments. Look at the following example :

/**
 * This program demonstrate passing
 * argument to a method.
 */
public class PassingArgument
{
   public static void main(String[] args)
   {
      int x = 30;

      System.out.println("Display line of 50 characters");
      displayLine(50);
      System.out.println("Display line of 30 characters");
      displayLine(x);
   }

   /**
    *  The displayLine method accept an argument.
    */
   public static void displayLine(int n)
   {
      for (int i = 1; i <= n; i++)
      {
         System.out.print("_");
      }

      System.out.println(" ");
   }
}          

Output :

Display line of 50 characters
__________________________________________________
Display line of 30 characters
______________________________