Var_arg method

(Variable number of argument method)

1. Until 1.4 version we cannot declare a method with variable number of argument if there is a change in number of argument compulsory we should go for new method.It increase length of code and reduce readability.

2. To overcome this problem SUN people introduce var_arg method in 1.5 version according to this we can declare a method which can take variable number of argument,such type of method called var_arg method.

3. we can declare a var_arg method as follows:

method_name(data_type... variable_name)

e.g: m1(int... x)

*we can call this method by passing any number of int value including zero number:

m1();

m1(10);

m1(10,30,20);

m1(10,20,30,40,50);


sample program:


class Test
{
public static void sum(int... x)
{
int total = 0;

for(int x1:x)
{

total = total +x1;

}
system.out.println(total);
}

public static void main(String[] args)
{

sum(); o/p:0;

sum(10,20); o/p:30

sum(10,20,30);o/p:60

}

}

4. Internally var_arg method parameter will be converted into one-dimensional array.Hence, within the var_arg method we can differentiate value by using INDEX.

5.Inside a class we cannot declare var_arg method and corresponding one-dimensional array method simultaneously otherwise we will get compile time error.

e.g:

class Test{
public void m1(int... x){
system.out.println("var_arg"); (invalid we will get compile time error saying "cannot declare both m1(int[] x) and m1(int... x) in Test")
}

public void m1(int[] x){
system.out.println("one-dimensional array");
}

}

NOTE:

In general var_arg method will get least priority i.e if no other method matched than only var_arg method will get chance,it is exactly same as default case inside switch.










NEXT PAGE



PREVIOUS PAGE