Varargs In Java

As we have to make different functions for multiple parameters so it increases our code length. So varargsĀ is used so that you don’t have to make different functions. It allows the method to take multiple parameters.

  • There should be only one variable argument in one method.
  • The variable argument must be the last argument.
class Varargs1
{
static void fun(int...a)
{
for(int p:a)
{
System.out.println(p);
}
}

public static void main(String args[])
{
fun(100);
fun(100,200);
fun(100,200,300);
fun();
}
}

Output:
100
100
200
100
200
300

 

Leave a Reply