Java Method Varargs Variable-Length Arguments

Introduction

Java method can accept a variable number of arguments.

This feature is called varargs which is short for variable-length arguments.

A method with a variable number of arguments is called a variable-arity method, or a varargs method.

A variable-length argument is specified by three periods ....

For example, here is how myTest() is written using a vararg:


void myTest(int... v) { 
     //your Code
}

myTest() can be called with zero or more arguments.

v is implicitly declared as an array of type int[].

Inside myTest(), v is accessed using the normal array syntax.

// Demonstrate variable-length arguments. 
public class Main { 
 
  // myTest() now uses a vararg. 
  static void myTest(int ... v) { 
    System.out.print("Number of args: " + v.length + 
                       " Contents: "); 
 
    for(int x : v) 
      System.out.print(x + " "); 
 
    System.out.println(); /* w ww. j  av  a2 s . co m*/
  } 
 
  public static void main(String args[])  
  { 
    myTest(10);      // 1 arg 
    myTest(1, 2, 3); // 3 args 
    myTest();        // no args 
  } 
}

The variable-length parameter must be the last parameter declared by the method.

For example, this method declaration is acceptable:

int test(int a, int b, double c, int ... vals) {                                                     
    //...
}

For example, the following declaration is incorrect:

int test(double c, int ... vals, boolean stopFlag) // Error! 

Here, we cannot declare a regular parameter after the varargs parameter.

There must be only one varargs parameter.

For example, this declaration is also invalid:

int test(double c, int ... vals, double ... morevals) { // Error! 

The following code shows how to mix normal parameter and a variable-length argument:

// Use varargs with standard arguments. 
public class Main { 
 
  // Here, msg is a normal parameter and v is a 
  // varargs parameter. 
  static void myTest(String msg, int ... v) { 
    System.out.print(msg + v.length + 
                       " Contents: "); 
 
    for(int x : v) 
      System.out.print(x + " "); 
 
    System.out.println(); //from  w w  w. j a v  a 2s. c o  m
  } 
 
  public static void main(String args[])  
  { 
    myTest("One vararg: ", 10); 
    myTest("Three varargs: ", 1, 2, 3);  
    myTest("No varargs: ");  
  } 
}



PreviousNext

Related