SoFunction
Updated on 2025-03-08

Detailed explanation of Java Varargs variable parameters usage

Java1.5 provides a new feature called varargs, which is variable length parameters.

"Varargs" means "variable number of arguments". Sometimes it is simply called "variable arguments".

A method to define variable number of real parameters: as long as three consecutive "." (i.e. "..." is added between the "type" and "parameter name" of a formal parameter (i.e. "...", an ellipsis in the sentence in English), it can match an uncertain real parameter.

The following example creates the sumvarargs() method to count the values ​​of all numbers.

We have added 4 parameters to the Main method here, new int[]{10, 12, 33, 7}. In fact, you can continuously add different parameters here, and the method of calculating sum can be processed according to the parameters you added.

GIT

Please refer to the source code on GitHub:

/cwiki-us/java-tutorial/blob/master/src/main/java/com/ossez/lang/tutorial/usecases/

SRC

package ;

import org.;
import org.;

/**
 * variable arguments use case
 */
public class VarargsCase {
  private static final Logger logger = ();

  /**
   * sumVarargs
   *
   * @param intArrays
   * @return
   */
  static int sumVarargs(int... intArrays) {
    int sum, i;
    sum = 0;
    for (i = 0; i < ; i++) {
      sum += intArrays[i];
    }
    return (sum);
  }

  /**
   * Main Function
   *
   * @param args
   */
  public static void main(String args[]) {
    int sum = 0;
    sum = sumVarargs(new int[]{10, 12, 33, 7});
    ("The Sum of the arrays: {}", sum);
  }
}

OUTPUT

The output result of the program running is:

2020/01/27 14:33:52 DEBUG [] - The Sum of the arrays: 62

Extended Learning

Java instance - Varargs mutable parameters use

ava1.5 provides a new function called varargs, which is variable length parameters.

"Varargs" means "variable number of arguments". Sometimes it is simply called "variable arguments"

A method to define variable number of real parameters: as long as three consecutive "." (i.e. "..." is added between the "type" and "parameter name" of a formal parameter (i.e. "...", an ellipsis in the sentence in English), it can match an uncertain real parameter.

The following example creates the sumvarargs() method to count the values ​​of all numbers:

document

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

The output result of the above code running is:

The sum of the numbers is: 55

The above are all the relevant knowledge points introduced this time. If you have any additional content, please contact my editor.