Varargs (short name for variable arguments) is used to pass an arbitrary number of values to a method. You use varargs when you don’t know how many of a particular type of argument will be passed to the method.
To use varargs, follow the type of the last parameter by an ellipsis (three dots, …), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.
class VarargExample { public int sumNumber(int ... args){ System.out.println("argument length: " + args.length); int sum = 0; for(int x: args){ sum += x; } return sum; } public static void main( String[] args ) { VarargExample ex = new VarargExample(); int sum2 = ex.sumNumber(2, 4); System.out.println("sum2 = " + sum2); int sum4 = ex.sumNumber(1, 3, 5, 7); System.out.println("sum4 = " + sum4); } }
The code in the method body will treat the parameter as an array in either case.