Insights Technical Hub How to use var-args with methods in Java

How to use var-args with methods in Java

Introduction:

Var-args are a feature that is new in Java version 5. They allow arguments to passed to a method without restricting their quantity. Any amount of arguments can be passed to the method using var-args as a parameter, if its of the specified type.

Requirements:

A java development environment, this can be a text editor, compiler, and runtime environment (JRE).

Procedure:

In the method’s signature, include the type, followed by an ellipsis () and a name for the var-args. Var-args can be of primitive or object types. The following is an example of a method with an int var-args argument called “parameter4”:

public void method1(int parameter1, String parameter2,
int parameter3, int… parameter4){}

The var-args parameter must always be the last parameter. You can also only have one var-args parameter per method.

The var-agrs parameter, when used, will become an array, which can be accessed using the name provided in the method’s signature. Here is a way to use the var-args in the method declaration, or signature, written above:

public void method1(int parameter1, String parameter2, int parameter3, int... parameter4){ 
System.out.println(parameter4[3]); //This will print the 4th element of the var-args parameter4 array to standard output 
}

The previous code will print the 4th element (element 3) of the array “parameter4” to standard output. This array, “parameter4” is the var-args parameter for the method “method1.” If we were to call the method as follows:

method1(5, "abc", 4, 2, 3, 5, 7, 8, 1, 9);

then the following would be printed to standard output:

7