When to use vararg methods in Java?

Java 8Object Oriented ProgrammingProgramming

Whenever, you want to pass different number of arguments each time you call a method you should use vararg methods.

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.


Live Demo

public class Main {
   static int sumvarargs(int... intArrays) {
      int sum, i;
      sum = 0;
      for(i = 0; i< intArrays.length; i++) {
         sum += intArrays[i];
   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);


The sum of the numbers is: 55
Published on 02-Jan-2018 07:21:26