Tuesday, March 17, 2015

HOw To Use Variable Arguments In JAVA

In this post I am going to talk about varags in JAVA. Varargs is the short term for variable argument. Vararg allows a method to have zero or multiple number of parameters.Sometimes when we create methods we have no idea how many parameters should have to that method. As an example we want to create a method which calculate the total of few numbers , and the number of parameters to this method is differed from time to time. To solve this problem java gives us a concept called varargs.

Syntax for write a vararg is as this.

return_type method_name(data_type...variableName){}  


Below code segment describes how can we use varargs.

public class Test {
    
    //Here method parameter is a vararg.
    public static int total(int...num) {
        int sum=0;
        for(int a:num){
        sum=sum+a;
        }
        return sum;
    }
    
    public static void main(String[] args) {
        
        System.out.println("total ="+total());
        System.out.println("total ="+total(5,10));
        System.out.println("total ="+total(5,10,15));
        System.out.println("total ="+total(5,10,15, 20));
        

    }

}

Output of the above program is given below.

total =0
total =15
total =30
total =50

When using varargs we have to follow several rules.

1. There can only be one varargs in a method.
2. If there are few arguments in the method vararg should come as the final argument of that method.


No comments:

Post a Comment