Variable argument list

While analyzing a code I found a function with argument ‘Object… args’. This was very new for me, so I tried to find the meaning of the statement. Later I found that it is used for variable argument list but only from Java SE5.

Variable argument was exist in the previous version too. As all the class is ultimately inherited from the common root class Object and call it this way:

class Test{}
public class VarArg1 {
    static void printArray(Object[] args)
    {
        for(Object obj:args)
        {
            System.out.print(obj + ” ~ “);
        }        
        System.out.println(“”);
    }
    public static void main(String[] args) {
        printArray(new Object[]{new Integer(35),new Float(23.4),new Double(33.222)});
        printArray(new Object[]{“One”,”Two”,”Three”,”Four”,”Five”});
        printArray(new Object[]{new Test(),new Test(),new Test(), new Test()});
    }
}

Output:
35 ~ 23.4 ~ 33.222 ~
One ~ Two ~ Three ~ Four ~ Five ~
Test@19821f ~ Test@addbf1 ~ Test@42e816 ~ Test@9304b1 ~

  Now from Java SE5 we may change the similar code to below one. In which we do have no any change but the way of making variable object is changes.

class Test{}

public class VarArg2 {
    static void printArray(Object.. args)
    {
        for(Object obj:args)
        {
            System.out.print(obj + ” ~ “);
        }        
        System.out.println(“”);
    }
    public static void main(String[] args) {
        printArray(new Object[]{new Integer(35),new Float(23.4),new Double(33.222)});
        printArray(new Object[]{“One”,”Two”,”Three”,”Four”,”Five”});
        printArray(new Object[]{new Test(),new Test(),new Test(), new Test()});
    }
}

Output:
35 ~ 23.4 ~ 33.222 ~
One ~ Two ~ Three ~ Four ~ Five ~
Test@19821f ~ Test@addbf1 ~ Test@42e816 ~ Test@9304b1 ~

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: