Var arg method in Java

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.

  • Implementation of var args method

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.

要查看或添加评论,请登录

Devidas Sabale的更多文章

  • All About Array

    All About Array

    What is Array: Array is group of primitive data, group of objects. Array is group of similar data (homogeneous data).

    1 条评论
  • Data Types in Java

    Data Types in Java

    Java is a strongly typed programming language. Therefore, you have to mention the type of value before compilation…

  • What is literal in Java?

    What is literal in Java?

    Literals are the constant values that can be assigned to a variable. Types of literals: Decimal Literal Octal Literal…

    2 条评论
  • Why Java is not a fully object oriented programming language?

    Why Java is not a fully object oriented programming language?

    Here are reasons: Primitive Data Types: In Object Oriented Programming everything should be object. But in Java there…

社区洞察

其他会员也浏览了