From Java 5 onwards, we may create methods having variable number of arguments. Such methods having three dots (…) as the argument known as ellipsis.
class CodingDots
{
static void method(String ... str)
{
System.out.println("Data is : ");
for (String s : str)
{
System.out.println(s);
}
}
public static void main(String args[])
{
method("C","C++","Java"); // call with 3 args
method("C,","C++","Java","Python","C#","JS"); // with 6 args
}
}
OUTPUT:-
Data is :
C
C++
Java
Data is :
C,
C++
Java
Python
C#
JS
Another Example:- Find sum of all given numbers.
class CodingDots
{
static void sum(int ... input)
{
int total=0;
for (int n : input)
{
total = total + n;
}
System.out.println("Sum of given numbers is "+total);
}
public static void main(String args[])
{
sum(10,20,30);
sum(5,10,15,20,25);
}
}
OUTPUT:-
Sum of given numbers is 60
Sum of given numbers is 75