How to make a method take variable lentgth argument as an input using Java



Problem Description

How to make a method take variable lentgth argument as an input?

Solution

This example creates sumvarargs() method which takes variable no of int numbers as an argument and returns the sum of these arguments as an output.

public class Main {
   static int  sumvarargs(int... intArrays) {
      int sum, i;
      sum = 0;
      for(i = 0; i< intArrays.length; i++) {
         sum += intArrays[i];
      }
      return(sum);
   }
   public static void main(String args[]) {
      int sum = 0;
      sum = sumvarargs(new int[]{10,12,33});
      System.out.println("The sum of the numbers is: " + sum);
   }
}

Result

The above code sample will produce the following result.

The sum of the numbers is: 55

The following is an another sample example of Varargs

public class HelloWorld {
   static void display(String... values) {
      System.out.println("display method invoked ");
      for(String s:values) {
         System.out.println(s);  
      }  
   } 
   public static void main(String args[]) { 
      display();
      display("Tutorialspoint");
      display("my","name","is","Sairamkrishna Mammahe");
   }   
}  

The above code sample will produce the following result.

display method invoked 
display method invoked 
Tutorialspoint
display method invoked 
my
name
is
Sairamkrishna Mammahe
java_methods.htm
Advertisements