Explaining varargs
Consider the following situation: you want to call a method, m1
, but the number of arguments may vary. Do you overload the method with each version of the method taking in one extra parameter? For example, assuming the argument types are of the String
type, do you overload m1
when each new version takes in an extra String
parameter? In this case, you would have to code m1(String)
, m1(String, String)
, m1(String, String, String)
, and so forth. This is not scalable.
This is where varargs
comes in. varargs
is a very flexible language feature in Java, specifically provided for this use case. The syntax is that the type name is followed by an ellipsis (three dots). Figure 7.10 shows varargs
in action:
Figure 7.10 – varargs example
In this figure, on line 10, m1(int… )
defines a method signature for the m1
method, defining 0 or more int
parameters. This is quite different from String[]
defined on line 4 for main
. In effect...