How to implement a method taking variable arguments or Varargs in Java

As known it is possible to implement a method which takes variable number of arguments in Java.

System.out.printf(“%d %f”,i,k); is the best example of such a method, allowing variable number of arguments.

And am sure, such method would be required some where, while developing Java applications.

Below is sample declaration of such method,

public void myFunc(String ... strs)
{
    for (String s : strs)
    {
         System.out.println(strs);
    }
}


represents there can be any number of arguments of that specific type.

Below is an example for a method which need to be invoked with int, String parameters followed by any number of String parameters.

public void myFunc(int i, String tst,String ... strs)
{
    for (String s : strs)
    {
         System.out.println(s);
    }
}


Also, please note that, these variable arguments can be of any type, but all of them need to be of specific type.
If you are not sure of the type of variable arguments, then you can use Object as parameters, this is because Object class is Base class of all classes in Java.

Below is an example of method taking objects of any class as parameter

public void myObjFunc(Object... objs)
{
    for (Object obj : objs)
    {
         System.out.println(obj);
    }
}

You may also like to read:
How to override toString()
What is Generic Class
List of Java Keywords

Leave a Reply