View RSS Feed

Java Object

Arbitrary Number of Arguments

Rate this Entry
by , 04-26-2012 at 06:17 PM (1668 Views)
A construct known as varargs could be used so that for passage of the arbitrary values number to a method. Varargs can be used when numbers of argument types that shall be passed are not known. This is actually the shorter way for array creation that is done manually.

For usage of the varargs last parameter type shall be followed (by an ellipsis). Then shall come space, then parameter name. Call method by any number, of that parameter, which will also include none
Java Code:
public Polygon polygonFrom(Point... corners) {
    int numberOfSides = corners.length;
    double squareOfSide1, lengthOfSide1;
    squareOfSide1 = (corners[1].x - corners[0].x)
                     * (corners[1].x - corners[0].x) 
                     + (corners[1].y - corners[0].y)
                     * (corners[1].y - corners[0].y);
    lengthOfSide1 = Math.sqrt(squareOfSide1);

    // more method body code follows that creates and returns a 
    // polygon connecting the Points
Corners would be treated as array inside the method. You can call method either with argument sequence or with array. Code which is present in method body treats the parameter to be as array, in any case.
Varargs will be seen most commonly along with the printing methods, like printf method:
Java Code:
public PrintStream printf(String format, Object... args)
Permits arbitrary object numbers to printed. Call it like this:
System.out.printf("%s: %d, %s%n", name, idnum, address);

Submit "Arbitrary Number of Arguments" to Facebook Submit "Arbitrary Number of Arguments" to Digg Submit "Arbitrary Number of Arguments" to Submit "Arbitrary Number of Arguments" to StumbleUpon Submit "Arbitrary Number of Arguments" to Google