Methods with Variable Number of Arguments

  • 0
     In my last article, I discussed how before the introduction of VarArgs, programmers had to deal with the requirement of methods. Here, I am going to discuss the VarArgs Methods, that allow you to deal with the requirement of variable number of arguments in a method. A variable length argument is specified by three periods. For example
static void VarMethod(int...v)
     The best way to access all the arguments in VarArgs methods, is to use a for-each loop. However, there are two restrictions with associated with VarArgs Methods.
  1.  If the method is supposed to take different arguments, then, VarArgs argument must be at the end of the argument list. For example
    int VarArgMethod(boolean flag, String name, int...args)
  2.  Second restrictions restricts the number of VarArgs argument in argument list to one only.
     Just like normal methods, VarArgs Methods can also be overloaded. However, overloading of VarArgs Method usually leads to ambiguity problems, so, it considered a safe practice to not to overload VarArgs Method. You can fallow either of two methods to overload the methods.
  1. change the type of VarArgs argument.
  2. add a normal variable to the argument list.
     I have written a Java program which is just enhanced version of my last program.
package ClassIllustration;

class VarArgs
{
 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[])
 {
  VarArgMethod("The", "Java","Journal");
  VarArgMethod("Your", "Confusion", "Buster");
  VarArgMethod("A", "place", "to", "clear", "all", "your", "doubts");
  VarArgMethod();
 }
}
To compile the program
javac -d . VarArgs.java
To run the program
java ClassIllustration.VarArgs
The output for the program 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
Stay tuned.

No comments:

Post a Comment