Understanding Variable Arguments (VarArgs)

Understanding Variable Arguments (VarArgs)

The Method To Take Multiple Arguments.

·

2 min read

Varargs (variable arguments) is a Java method that takes a variable number of arguments. Variable Arguments in Java makes it easier to write methods that require a variable number of arguments.

For example, you want to create a method/function that outputs the sum of two integers but if you want to output the sum of three integers you'll have to create another function. VarArgs can take multiple arguments at once saving you a lot of time.

Let's look at the syntax first:

static void fun(int ...v){
     //body
}

You put three dots before the variable name to specify that it is a VarArg.

  • Internally, VarArgs store the values in one-dimensional arrays. You can use the various array functions on the variable "v" such as .length or ToString. Example:
main(){
    fun(1,2,3,4);
}
static void fun(int ...a){
    System.out.print(Arrays.ToString(a));
}

// output : [1,2,3,4]
  • It supports other data types such as string, int , char etc.
  • VarArgs can also be used with other parameters but one has to make sure that there can be only one VarArg parameter and that should be written at the end. Example:
static void fun(int a, int b, String ...c){
    //body
}
  • You can even provide no argument at all and it will be interpreted as an empty array.
  • In the case of more than one function with variable arguments, you cannot provide a null input, as determining in which function to store the null value would be impossible.

Example:

main(){
    fun();
}

static void fun(int ...a){
    //body
}
static void fun(String ...b){
    //body
}

// this will give an error.

I hope this was helpful. (ɔ◔‿◔)ɔ ♥

Let's connect on Twitter.