Understanding Varargs in Java: 2 Minute Guide For Non-Dummies

By Angsuman Chakraborty, Gaea News Network
Sunday, April 30, 2006

Varargs allows variable number of arguments in methods and constructors. Let’s start with a simple example.

public static void main(String … args) {
    for(String arg:args) {
        System.out.println(arg);
    }
}

Varargs can be thought of as an array with simplifications. A simple use case is: int sum(int… data)

Key Points

  • Method with varargs is called only when no other method signature matches the invocation.
  • Only one varargs per method can be declared.
  • Varargs should be the last argument(set) for a method. So public void varargtest(int i, String … args) is valid but public void varargtest(String … args, int i) is not.
  • Zero or more arguments can be passed for varargs unlike an array where at least a null has to be provided.

Now you are all set to play with varargs in Java. Go forth and enjoy!

Discussion

rohit
May 21, 2010: 12:33 am

what is … in varags


A
October 20, 2009: 6:49 am

this is een onderhoud verkoppen


Vikas Parikh
YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :