/* related posts with thumb nails */

Methods with Varargs:

Varargs represents variable length arguments in methods, which is one of the features introduced by J2SE 5.0. It makes the Java code simple and flexible. Varargs takes the following form:

void method-name (Type . . . argument)

{

}

In the above syntax, Type is the type of an argument; ellipsis (...) is the key to varargs and argument is the name of the variable.

Thus, varargs allows us to declare a method with that allows any number of values to the argument in it. The varargs must be the final argument in the argument list of a method. Varargs is identified by the type of an argument followed by the ellipsis (...) and the name of a variable.

For example, consider the following declaration of the method, sample, which contains the same type of arguments.

public void sample (String username, String password, String mailid);

The above code is an example for simple method declaration. The above method declaration can be replaced by varargs, as shown below:

public void sample(String . . . var_name);

where String... var_name specifies that we can pass any number of String arguments to the sample method. The following program demonstrates varargs.

class Test

{

public static void main(String as[])

{

sample("aa","bb","xx"); // here we are passing 3 arguments

sample("a1","a2","a3","a4","a5"); // here we are passing 5 arguments

}

public static void sample(String ...str)

{

for(String s:str)

System.out.println(s);

}

}

Related Topics:

0 comments:

Post a Comment