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