Methods with variable length arguments

  • In Java, you can define methods that have a variable-length argument list provided that all arguments have the same data type


  • How to define a method with a variable-length argument list:

        public static returnType methodName( typeName... paramName )
        {
            ... // Use the paramName variable as a array variable
        }

  • Java will treat this definition as:

        public static returnType methodName( typeName[] paramName )
        {
            ... // Use the paramName variable as a array variable
        }

Methods with variable length arguments   example

How to define and use variable-length arguments in Java:

    public static void main(String[] args)
    {
        double sum;
        
        sum = listSum(1, 2, 3);    // Call listSum() with 3 arguments
        System.out.println(sum);
        
        sum = listSum(1, 2, 3, 4); // Call listSum() with 4 arguments
        System.out.println(sum);
    }

    public static double listSum( double... x )
    {
        double s = 0;
        
        for (int i = 0; i < x.length; i++ )
            s = s + x[i];  // Use x like an array...
            
        return s;
    } 

DEMO: demo/08-array/09-var-len-arg/VarLenArg.java

Methods with variable length arguments   important note

Note:   you cannot define an array parameter to pass variable-length arguments:

    public static void main(String[] args)
    {
        double sum;
        
        sum = listSum(1, 2, 3);    // Error !
        System.out.println(sum);
        
        sum = listSum(1, 2, 3, 4); // Error !
        System.out.println(sum);
    }

    public static double listSum( double[] x )
    {
        double s = 0;
        
        for (int i = 0; i < x.length; i++ )
            s = s + x[i];  
            
        return s;
    } 

Reason:   a list of numbers is not an array

DEMO: demo/08-array/09-var-len-arg/Error.java