Varargs: passing a variable number of arguments to a method

From version 5 of Java you can call a method passing a variable number of arguments.
A variable of this type is called varargs, you can only use in a method signature and its syntax is the primitive type or object type followed by 3 dots (ellipsis).
An example is the following:

where the variable x is an array containing all the values ​​passed (in this example x[0] is equal to 1).
This way has some limitations:

  1. you can use the variable varargs only one time in a method
  2. the variable varargs must be at the last place in the method signature

As variable varargs you can pass null or no value; in the above example the call varargs() is like varargs(new int[0]) where new int[0] is an empty array but not null.

In situations of ambiguity for overloaded methods the call to method with varargs is always loser as you see from the following examples:

  • example 1:
  • example 2 (boxing):
  • example 3 (widening):

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.