Old School Variable Argument Method

  • 0
     Before introduction of Varargs(which is going to be our next topic of discussion in Java Journal), two appraoches were used to create methods with variable number of arguments. They are
First approach invloved the use of overloaded method. The method simply involved creating all poosible set of input arguments and define a separate method with same name. This approach gaurantees to push you onto edge.
Second approach was to use a single method with on;y one argument array of the required type. We will discuss this method in here. However, the problems associated with this approach was that each time, preparing for a call to a method, an array was supposed to be created. This method can be extremely complex and errorprone if number of calls are large.
package ClassIllustration;

class OldSchoolVariableLengthArguments
{
 static void VarArgMethod(String args[])
 {
  System.out.print("Number of Arguments received this time " + args.length + " Contents ");
  
  for(String x:args)
  {
   System.out.print(" " + x);
  }
  System.out.println();
 }
 
 public static void main(String args[])
 {
  String arg1[]={"The", "Java", "Journal"};
  String arg2[]={"Your", "Confusion", "Buster"};
  String arg3[]={"A", "Place", "to", "clear", "all", "your", "doubts"};
  String arg4[]={};
  
  VarArgMethod(arg1);
  VarArgMethod(arg2);
  VarArgMethod(arg3);
  VarArgMethod(arg4);
 }
}
As you can see, I had to create four different arrays for four method calls. The typing load would increase with the number of calls to the method. To compile the program,
javac - d . OldSchoolVariableLengthArguments.java

And to run the program
ClassIllustration.OldSchoolVariableLengthArguments

Output for the program on my machine is

Number of Arguments received this time 3 Contents  The Java Journal

Number of Arguments received this time 3 Contents  Your Confusion Buster

Number of Arguments received this time 7 Contents  A Place to clear all your doubts

Number of Arguments received this time 0 Contents


No comments:

Post a Comment