Java 5: Varargs
Suppose you are creating a method, but you aren't sure how many arguments your method is going to accept. So, to address this problem var-args were introduced with Java 1.5 release. Prior to Java 1.5, we need to create overloaded method to handle variable number of parameters. Varargs is short name of variable length argument. Syntax: A variable-length argument is specified by three periods(…). For Example, public static int sum(int ...i) { // method body } Above syntax tells the compiler that the sum() method can take zero or more arguments of type int. class Test { public static int sum(int ...i) { int sum = 0; for (int a: i) sum+=a; return sum; } public static void main(String []args){ System.out.println(sum(1,2,3)); System.out.println(sum()); System.out.println(sum(1,2)); } } Output: 6 0 3
Comments
Post a Comment