Tuesday, 11 December 2012

Variable arguments - Java

This is one of the new feature in JDK5. varargs allows you to pass variable number of arguments to function. You can no argument, one arguments or any number of arguments to function using this feature. Remember one thing that vararg must be that last argument to function and we can use only one vararg for  one function. We can use varargs anywhere except last argument. You can even pass array to varargs.
Here I am giving one simple example,

class Test
{
    private void printThis(int... a)
    {
        for(int i = 0; i < a.length; i++)
            System.out.print("\nArgs : " + a[i]);
        System.out.print("\n\n=======================");
    }
   
    public static void main(String args[])
    {
        int[] ary = new int[10];
        for(int i = 0; i < 10; i++)
            ary[i] = i;
       
       
        Test t = new Test();
        t.printThis();
        t.printThis(1, 2, 3);
        t.printThis(1, 2, 3, 4, 5, 6, 7, 8);
        t.printThis(ary);
    }
}


We can use this when we don't know exact number of arguments.

No comments:

Post a Comment