Java | Var-args method

05 min read

Var-args Method:

  • Varargs — variable length arguments.
  • A method that takes a variable number of arguments is called a variable-arity method or var-args method.
  • A good example of a var-args method:

printf( ) method takes a variable number of arguments, which it formats & then outputs.

(eg) printf("hello"); ---> 1 argument

printf("%d", n);  ---> 2 arguments

printf("%d%d", m, n);  ---> 3 arguments

  • A variable-length argument is specified by 3 periods (.....)

(eg) void method 1 (int . . . a) //There should be a gap here

By seeing such a method signature, the compiler understands that method1( ) can be called with 0 or more arguments. 'a' is implicitly declared as an array of type int[ ] & hence inside method1( ), 'a' is accessed using the normal array syntax.

Example:

class varargs
{
void method 1(int .....a)                    
System.out.println(a.length);           
for(int x : a)                                        
System.out.println(x);                  
}
public static void main(String[] args)
{
method 1 ( 1 0);
method 1(1, 2, 3);
method 1 ( );
}

Output:

1 (length of the array when the method is called first time)
10
3 (length)
1
2
3
0(length)

 

  • If there is more than one parameter for the method, then the varargs parameter must be the last.
  • There must be only one varargs parameter.
  • Varargs method can also be overloaded.
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error