Reputation: 4180
I was reading a book about java and the author did some variable arguments. It is something just like this:
public int num(int ... nums){}
and I did some research it looks like nums
is simply an array. So I am thinking the above code can be then replaced as:
public int num(int[] nums){}
My question: What is the point of the variable arguments? Can you change the type to other types such as String
?
Upvotes: 0
Views: 110
Reputation: 676
Varargs (variable arguments) do indeed get packaged into an array when your program is run. There is no functional difference between making a call like this
public int add(int... addends);
and this
public int add(int[] addends);
Java will create an int[]
for you and store it in the variable addends in the former. In the latter, you make it so the caller of the add
function has to create the array themselves. This can be a bit ugly, so Java made it easy. You call the varargs method like so:
int sum = add(1,2,3,4,5,6);
And you call the array method like so:
int sum = add( new int[] {1,2,3,4,5,6} );
Varargs can be used for more than just primitives, as you suspected; you can use them for Objects (of any flavor) as well:
public Roster addStudents(Student... students) {}
A quote from the article linked:
So when should you use varargs? As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called.
Edit: Added example for using Objects
Upvotes: 0
Reputation: 162781
The difference would be in how you can call the method.
If your method looked like this:
public int num(int[] nums){}
you could call it like this:
num(new int[] { 1, 2, 3 });
On the other hand, if you used varargs like this:
public int num(int ... nums){}
you could call it more concisely, like this:
num(1, 2, 3)
Upvotes: 5
Reputation:
Varargs are just syntactic sugar that lets you write
num(1,2,3);
instead of
num(new int[] {1,2,3});
Upvotes: 1
Reputation: 6333
System.out.println("%s %s %s.", "this", "is", "why");
System.out.println("%s %s %s %s?", new String[] {"or", "you", "prefer", "this"});
Upvotes: 0