Skip to content

AvinandanBose/Java_VarArgs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Java_VarArgs

Introduction

Beginning with JDK 5 , Java has included a feature that simplifies the creation of methods that need to take variable number of arguments. This feature is called varargs and it is short for variable-length arguments. A method that takes a variable number of arguments is called a variable-arity method , or simply a varargs methods .

Prior to JDK5 , variable -length arguments could be handled in two ways:

    • 1. First, if the maximum number of arguments was small and known , they we could create overloaded versions of the method, one for each way the method could be called.

    //Method Overloading  public class varargs1 { //Increasing the number of arguments in the method signature public void add(int a , int b){} public void add(int a , int b , int c){}  //Interchanging the method signature  public void sub(int a , float b){} public void sub(float b , int a ){} //Changing the type of the arguments public void div(int a, float b) {} public void div(String a, String b) {} public static void main(String[] args){ varargs1 a = new varargs1(); varargs1 b = new varargs1(); varargs1 c = new varargs1(); // .....etc. a.add(1, 2); b.add(1, 2, 3); c.sub(1, 2.9f); a.sub(2.9f, 1); b.div(1, 2); c.div("1", "2"); } } 

    • 2. Second Aproach is used in which the arguments were put into an array and then the array was passed to the method.

    public class varargs1 { static void vaTest(int v[]){  System.out.println("Number of args: " + v.length);  System.out.println("Contents: "); for(int i = 0; i < v.length; i++) System.out.println(" arg " + i + ": " + v[i]);  System.out.println();  }   public static void main(String args[]){  int n1[] = {10};  int n2[] = {1, 2, 3};  int n3[] = {};  vaTest(n1); // 1 arg  vaTest(n2); // 3 args  vaTest(n3); // no args  }     }  

    In the program, the method vaTest() is passed its agruments through the array v . This old-style approach to variable-length arguments does enable vaTest() to take an arbitrary number of arguments .However, it requires that these arguments be manually packaged into an array prior to calling vaTest(), as shown below :

    //Arbitratry Number of Arguments Say In Above Example: int n[] = {10}; No. of Arguments = 1. Elements of Array n[] = 10. Similarly , int n2[] = {1, 2, 3}; No. of Arguments = 3 Elements of Array n2[] = 1,2,3 . int n3[] = {}; No. of Arguments = 0 And They are manually packaged into Arrays: n[] , n2[] and n3[] and passed into Method: vaTest(). 

    Note There are two problems :

    • 1. It is tedious to construct an array each time vaTest() is called.
    • 2. It is potentially error prone.

VarArgs

Java introduced a Three Peroid Operator (...) to specify variable length argument .

Note now the way that vaTest is written is :

    static void vaTest(int ...v){} 

    static void vaTest(int... v) { System.out.print("Number of args: " + v.length + " Contents: "); for (int x : v){ System.out.print(x + " "); } //OR // for (int i = 0; i < v.length; i++) { // System.out.print(v[i] + " "); // } System.out.println(); } public static void main(String args[]){ vaTest(10); //1 args vaTest(1,12,3); // 3 args  vaTest(); // no args } 

    Explanation: Here vaTest() is the function , where v is an array. The ... syntax simply tells the compiler that a variable number of argument will be used , and that these arguments will be stored in the array by v . Secondly, in main() function, vaTest() is called with different numbers of arguments, including no arguments at all. The arguments are automatically put in an array and passed to v. In case of no arguments, the length of the array is zero.

  • 1 . A method can have "normal" parameters along wiht a variable-length parameter. However the variable-length parameter must be declared by the method.
  • int doIt(int a, int b, double c, int ... vals){} Here first three arguments are matched according to their types. Then any remaining arguments are assumed to belongs to vals. 

  • 2 . The varargs parameter must be last.
  • int doIt(int a, int b, double c, int ... vals, boolean stopFlag){  //Error  } 

  • 3 . There must be only one varargs parameter.
  • int doIt(int a, int b, double c, int ... vals, double ...morevals){  //Error  }  Attempt to declare the second varargs parameter is illegal. 

Overloading Vararg Methods

    We can overload a method that takes a variable-length argument.

     static void vaTest(int ... v) {} static void vaTest(boolean ... v) {} static void vaTest(String msg, int ... v) {} static void vaTest(Float i, int... v) {} 

    The above program illustrates both ways that a varargs method can be overloaded .There are two types :

    • 1. First the types of its vararg parameter can differ . This is the case for vaTest(int..) and vaTest(boolean...). ` ...` "The Triple Period Operator" causes the parameter to be treated as an array of the specified type. As we can overload methods by using different of array parameters , here also we can overload vararg methods by using different types of varargs . In this case , Java uses the type difference to determine which overloaded method to call.
    • 2. The second way to overload a varargs method is to add one or more normal parameters. This is what was done with vaTest(String, int...), vaTest(Float , int... ). In this case, Java uses both the number of arguments and the type of the arguments to determine which method to call.

Vararg and Ambiguity

    Unexpected errors can result when overloading a method that takes a variable length argument. These errors involve ambiguity(Compiler unable to understand the "overloaded method" at which the method call will be put. ).

    1. First Type

    class VarArgs4{ static void vaTest(int ...v){} static void vaTest(boolean ...v) {} public static void main(String args[]) { vaTest{1,2,3}; //OK vaTest{true,false,false}; //OK vaTest(); // Error : Ambiguous } } 

    For, vaTest() → compiler unable to identify to put the method call " vaTest() " to the "overloaded methods" : " vaTest(int ...v) " and " vaTest(boolean ...v) ". As it is valid for both . Hence causes "Ambiguity" .

    2 . Second Type

    class varargs4 { static void vaTest(int... v) { } static void vaTest(int i, int ...v) {} public static void main(String args[]) { vaTest(1); } } 

    Although the parameter list of vaTest() differ, there is no way for the compiler to resolve the following call: vaTest(1). Hence compiler again fails to translate the method call and make a choice between void vaTest(int... v) and vaTest(int i, int ...v), to put the call according to method signature for operation. Thus the situation is ambiguous .

About

This is a repository which explains about VarArgs feature of Java.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages