Var arg method in Java
Prior to learning this concept, I used to think that we could not change the syntax of the main method.
But we can make syntactical changes in the main method.
When we are not sure about the number of parameters in the method then we can use the var arg method. This will reduce the length of the code. We do not need to use method overloading in some problems.
Let's take one example.
Suppose the user wants the addition of numbers that he sending. If a user sends 2 numbers, then code for this will
public int sum (int num1, int num2){
int result = num1+num2;
return result;
}
But in case another user sends 3 numbers, then we have to modify our code as follows:
领英推荐
public int sum (int num1, int num2, int num3){
int result = num1+num2+num3;
return result;
}
Here we doing a repetition. And repetition in Java is a crime.
So var args method is a solution for this problem.
public int sum(int ...x){
int result = 0;
for(int number: x){
int result = result + number;
}
return result;
}
sum(1,2,3);
sum(3,4,5);
int ...x represents an array of integers.
Therefore, we can use var arg in our main method.
public class Test{
public static void main (String ...a){
System.out.println(a.length);
}
}
The above code is 100% valid in java.