Sunday, 26 July 2015

Applied Java: varargs

varargs in Java (introduced in java 5)

As the name suggest, varargs is a feature introduced in Java 5 to support the variable number of arguments during calling a method. However this is a quite old feature in some other languages like c, c++ etc.  This feature is applied when you want  a to write a generic method which can take a arbitrary number of arguments to work upon. 
    public static void log(String pattern, Object... args) {
        System.out.println(String.format(pattern, args));
    }
The above method can take any number of objects as arguments but very first argument must a string value. For example:
        log("You tell me that your name is : %s", name);
        log("You tell me that your fist name is : %s and last name is %s", firstName, lastName);

These both statements will call the "log" method. 

How it works:

When a method having varargs is invoked, compiler try to match the actual arguments with the declared arguments and wrap the trailing arguments in an java array object and then pass it. So it is actually same as below:

   log("You tell me that your name is : %s", new Object[] {name} );
   log("You tell me that your fist name is : %s and last name is %s", new Object[] {firstName, lastName});

Remember, java compiler can wrap only trailing arguments in an array object. So it is illegal to have varargs in beginning or middle of the argument list.

Link: http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html







No comments:

Post a Comment