Java varargs (AKA variable-arguments) Tutorial

In this section we will learn what the varags is and how to use it in Java.

What is Java varArgs

Sometimes we need a method, but the number of arguments that the method will take cannot be determined at design time!

For example, let’s say we have a method named `sum()` and its job is to take any number of integer values that a user set as its input and calculate the total sum.

So how do we know beforehand that if a user set one value or two or three or more values!

For this reason, since Java 5 a new way of declaring the parameter of a method was introduced, which is called Variable Arguments (AKA VarArgs).

Java varArgs syntax

Here’s the structure of VarArgs inside the parentheses of a method:

(data-type … parameter_name){//body…}

`data-type`: the data-type of course is the data type of the arguments that the method is about to take.

Note: the arguments should all be of the same type.

Triple dots `…`: the triple dots `…` is used to signal the compiler that we’re declaring a VarArgs not a normal parameter.

Note: the triple dots `…` go between the data type and the parameter name.

`parameter_name`: this name actually represents an array and in the method, we can use it to go through the arguments that it took when it was being called.

VarArgs Notes: remember the variable of type VarArgs represents an array and so the `length` attribute can be accessed via this variable to get the number of elements a user set for the method.

Example: Java varArgs and for-each loop

public class Simple {

    public static void main(String[] args) {
        sum(100);
        sum(200,1,2,4,3345,3,2342,243,434,234,24,2654,6453,34);
        sum(23,2342,3423,43);
    }
    public static void sum(int...list){
        System.out.println("The list of arguments is: ");
        int sum = 0;
        for (int i: list){
            System.out.print(i+", ");
            sum += i;
        }
        System.out.println("\nThe total sum is: "+sum);
    }
}

Output:

The list of arguments is:

100,

The total sum is: 100

The list of arguments is:

200, 1, 2, 4, 3345, 3, 2342, 243, 434, 234, 24, 2654, 6453, 34,

The total sum is: 15973

The list of arguments is:

23, 2342, 3423, 43,

The total sum is: 5831

In this example, the `sum()` method has a VarAgrs set as its parameter. This means we can call the `sum()` method and each time with a different range of numbers (of type integer for this example).

Note: we used the `for each` statement to access the elements of the `list` parameter, but of course we could also use the `for` loop as well.

Example: Java varArgs and for loop

Considering the last example, this is how we could use the `for` loop:

for (int i = 0 ; i< list.length; i++){
//body...
}

Here the list is the varArgs parameter of the sum method. 

Java varArgs notes:

1- varArgs should always be put as the last parameter

We mentioned that when using VarArgs, the arguments of the target method should be all of the same type!

But other than the VarArgs, what if we want to set one or more parameters of other types in the method?

In such case, the VarArgs should be set as the last parameter of the method and the other parameters come before it.

Example: Java varargs as the last parameter

public class Simple {

    public static void main(String[] args) {
        process("sum",100);
        process("subtraction",200,1,2,4,3345,3,2342,243,434,234,24,2654,6453,34);
        process("subtraction", 23,2342,3423,43);
    }
    public static void process(String sumOrsubtract, int...list){
        if (sumOrsubtract =="sum"){
            System.out.println("The list of arguments is: ");
            int sum = 0;
            for (int i: list){
                System.out.print(i+", ");
                if (sum == 0){
                    sum = i;
                }else{
                sum += i;
                }
            }
            System.out.println("\nThe total sum is: "+sum);
        }else if (sumOrsubtract == "subtraction") {
            System.out.println("The list of arguments is: ");
            int sum = 0;
            for (int i: list){
                System.out.print(i+", ");
                if (sum == 0){
                    sum = i;
                }else{
                    sum -= i;
                }
            }
            System.out.println("\nThe result of the subtraction is: "+sum);
        }else{
            System.out.println("I don't know what to do!");
        }

    }
}

Output:

The list of arguments is:

100,

The total sum is: 100

The list of arguments is:

200, 1, 2, 4, 3345, 3, 2342, 243, 434, 234, 24, 2654, 6453, 34,

The result of the subtraction is: -15573

The list of arguments is:

23, 2342, 3423, 43,

The result of the subtraction is: -5785

As you can see the first parameter of the `process` method is of type `String` and so when we call this method, the compiler expect to see the first argument to be of type `String` and the rest to be of type `integer`.

2- A method can have only one varArgs parameter

  • In a method, there can only be one VarArgs parameter.
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies