Programming & Scripting Tutorials

Java: Variable Length Arguments



Sometimes when creating functions you don't know how many arguments its going to take.
This is done using an ellipsis (...).

Here is an example of a function which takes variable length arguments:

public static int SumOf(int...numbers){


}

As you can see this currently does nothing, so lets make it do something with the input:

public class Main{
    public static void main(String[] args){
        System.out.println(SumOf(12, 3, 91, 22, 334, 63));
    }

    public static int SumOf(int...numbers){
    int total = 0;
    for(int item : numbers){
    total+=item;
    }
    return total;
    }
}

You can see this outputs 525 as expected.

This Java tutorial was written by


Back to Java

Advertisement: