Variable Argument Method in Java

A method which is able to process variable numbers of parameters is called VarArgs method. Most of us came across a function ‘printf()‘ in ‘C’ which is an example of variable argument type function.

VarArgs methods are very useful in terms of application programming. Lets create a VarArgs method using JAVA.

public class VarArgsSampleClass {

public static void main(String args[]){
VarArgsSampleClass varArgsSample = new VarArgsSampleClass();

varArgsSample.varArgsMethod(10, “A”,”B”); varArgsSample.varArgsMethod(20, “C”, “D”, “E”, “F”);

}

/** * varArgsMethod – This method demonstrate VarAgrs in Java. * @param i This is int argument. * @param args This is the variable argument String type parameter.

*/

public void varArgsMethod(int i, String… args){ System.out.print(“\n” + i); for(String arg: args) { System.out.print(“, ” + arg); } } } Output –

10, A, B

20, C, D, E, F

150 150 Burnignorance | Where Minds Meet And Sparks Fly!