0

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?

2

4 Answers 4

5

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)
Sign up to request clarification or add additional context in comments.

Comments

1

Varargs are just syntactic sugar that lets you write

num(1,2,3);

instead of

num(new int[] {1,2,3});

Comments

0
System.out.println("%s %s %s.", "this", "is", "why");

System.out.println("%s %s %s %s?", new String[] {"or", "you", "prefer", "this"});

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.