# Variable arguments in Java

In 
Published 2023-05-06

This tutorial explains to you how to use variable arguments (variable parameters) in Java. We have an example for you as well.

Sometimes we need to pass a variable number of parameters to a method. This is possible in Java.

Please take a look at the following examples and read carefully the comments. The code is self-explanatory.

Starting from the base application downloaded from Spring Initializr, I updated the main class and added the Calculation class as below:

Calculation.java
package com.example.demo;

import java.util.Arrays;

public class Calculation {

  public Integer sum1(int ... myNumbers) {

    int valToReturn = 0;
    System.out.println("Number of arguments sum1() : "+ myNumbers.length);

    // using for each loop to display contents of a
    for (Integer i : myNumbers) {
      valToReturn = valToReturn + i;
    }
    return valToReturn;
  }

  public Integer sum2(Integer[] args) {

    System.out.println("Number of arguments sum2() : "+ args.length);
    int valToReturn = Arrays.stream(args).reduce(0, (a, b) -> a + b);

    return valToReturn;
  }
}
DemoApplication.java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

import java.util.concurrent.ExecutionException;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) throws InterruptedException, ExecutionException {

		ApplicationContext appContext = SpringApplication.run(DemoApplication.class, args);

		Calculation calc = new Calculation();

		// calc.sum1 could have a variable number of parameters
		var mySum = calc.sum1(10, 20);
		System.out.println("mySum= "+mySum);

		var mySum1 = calc.sum1(10, 20, 30, 40);
		System.out.println("mySum1= "+mySum1);

		Integer[] someNumbers= {10, 20, 30, 40};
		// someNumbers could have a variable length, but "calc.sum2" has only 1 parameter of Integer[] type
		var mySum3 = calc.sum2(someNumbers);
		System.out.println("mySum3= "+mySum3);
	}
}

When I run this code I get the following log:

Number of arguments 1: 2
mySum= 30
Number of arguments 1: 4
mySum1= 100
Number of arguments 2: 4
mySum3= 100

Process finished with exit code 0