← Back to Chapters

Java Var-Args

? Java Var-Args

? Quick Overview

Var-args (variable arguments) in Java allow a method to accept zero or more arguments of the same type. They simplify method calls by removing the need to explicitly create arrays.

? Key Concepts

  • Introduced in Java 5
  • Uses ... (ellipsis) syntax
  • Internally treated as an array
  • Only one var-args parameter is allowed
  • Var-args must be the last parameter

? Syntax / Theory

Var-args make methods flexible when the number of inputs is unknown. They improve readability and reduce overloaded methods.

? View Code Example
// Method using var-args to accept multiple integers
static void printNumbers(int... numbers) {
// Loop through all received values
for (int n : numbers) {
System.out.println(n);
}
}

? Code Example(s)

? View Code Example
// Demonstrating var-args usage in main method
public class VarArgsDemo {
public static void main(String[] args) {
// Calling method with different number of arguments
printSum(10);
printSum(10, 20, 30);
printSum();
}
// Var-args method to calculate sum
static void printSum(int... values) {
int sum = 0;
for (int v : values) {
sum += v;
}
System.out.println("Sum = " + sum);
}
}

? Live Output / Explanation

Output

Sum = 10
Sum = 60
Sum = 0

The method printSum works with one value, multiple values, or even no values. Java automatically converts the arguments into an integer array.

✅ Tips & Best Practices

  • Use var-args when method overloading becomes excessive
  • Always place var-args at the end of parameter list
  • Avoid ambiguity with overloaded methods
  • Use meaningful parameter names

? Try It Yourself

  • Create a var-args method to find the maximum number
  • Write a method that joins multiple strings
  • Experiment with var-args and normal parameters together