var-arg Methods in Java

From 1.5 version on words we are allowed to declare a method with variable no of arguments such type of methods are called var-arg methods. We can declare a var-arg methoda as follows m1(int… i); this methods is applicable for any no of int arguments including zero no of arguments.

Example:

class Test {

    public static void m1(int... i) 

    {
        System.out.println("var-arg methods");
    }
    public static void main(String arg[]) 
    {
        m1();     // var-arg methods
        m1(10); // var-arg methods
        m1(10, 20); // var-arg methods
        m1(10, 20, 30); // var-arg methods
    }
}


‘var-arg’ methods internally implemented by using single dimensional arrays. Hence we can differentiate arguments by using index.

Example:

class Test 
{
    public static void main(String arg[]) 
    {
        sum(10, 20);
        sum(10, 20, 30, 40);
        int a;
        System.out.println(a);
        System.out.println(a[0]); 
        //C.E: varialbe ‘a’ might not have been initialized
        sum(10);
        sum();
    }

    public static void sum(int... a) 

    {
        int total = 0;
        for (int i = 0; i < a.length; i++)
        {
            total = total + a[i];
        }
        System.out.println("The sum is:" + total);
    }
}

Output:
The sum is 30
The sum is 100
The sum is 10
The sum is 0

We can mix general parameter with var-arg parameter.
Ex:
m1(char ch, int…a)

If we are mixing general parameters with var-arg parameter then var-arg parameter must be the last
parameter otherwise compile time error.

Ex:

m1(int… a, float f) //Invalid
m1(float f, int… a) //Valid

we can’t take more than one var-arg parameter in var-arg method otherwise C.E.

m1(int… a double… d)  //Invalid

which of the following are valid var-arg declarations.

m1(int... a)   //Valid 
m1(int. ..a) C.E: malformed function  //Invalid
m1(char ch, int... a)   //Valid
m1(int... a, char ch)   //Invalid
m1(int...a, boolean... b)  //Valid

Example:

class Test 
{
    public static void m1(int i) 
    {
        System.out.println("General method");
    }

    public static void m1(int... i) 

    {
        System.out.println("var-arg method");
    }

    public static void m1(String arg[]) 

    {
        m1();
        m1(10, 20);
        m1(10);
    }
}


Var-arg method will always get least priority i.e if no other method matched then only var-arg method will be executed.