Easy Tutorial
❮ Net Localip Env Compile ❯

Java Example - Varargs Usage for Variable Arguments

Java Examples

Java 1.5 introduced a new feature called varargs, which stands for variable-length arguments.

"Varargs" means "variable number of arguments" and is sometimes simply referred to as "variable arguments".

To define a method with a variable number of arguments, you simply need to add three consecutive dots ("...") between the "type" and "parameter name" of a formal parameter, allowing it to match an indefinite number of actual arguments.

Main.java File

public class Main {
    static int sumvarargs(int... intArrays){
        int sum, i;
        sum = 0;
        for(i = 0; i < intArrays.length; i++) {
            sum += intArrays[i];
        }
        return(sum);
    }
    public static void main(String args[]){
        int sum = 0;
        sum = sumvarargs(new int[]{10, 12, 33});
        System.out.println("Sum of the numbers: " + sum);
    }
}

The output of the above code is:

Sum of the numbers: 55

Java Examples

❮ Net Localip Env Compile ❯