← Back to Core Java Course | Chapter 5: Methods & Arrays | Lesson 6 of 10

Java Variable Arguments (varargs)

Varargs let a method accept any number of the same kind of inputs, like a bag that stretches. Inside the method they behave like an array.
Syntax
java
static returnType methodName(dataType... values) {
    // values behaves like an array
}

methodName(a, b, c);

Introduction to Varargs

Varargs (variable arguments) let a method accept any number of arguments of the same type without the caller needing to build an array first, using the Type... name syntax.

Internally, Java collects whatever arguments you pass into a regular array before the method body runs.

Example: Introduction to Varargs

java
// Define the class Main
public class Main {
	static int sum(int... numbers) {
		// Declare total and set it to 0
		int total = 0;
		for (int n : numbers) {
			total += n;
		}
		// Send total back to the caller
		return total;
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Print a line to the console
		System.out.println(sum(1, 2, 3));
	}
}

Varargs Syntax Rules

A method can declare at most one varargs parameter, and it must be the last parameter in the signature, because the compiler needs to know unambiguously where the fixed parameters end and the variable-length group begins.

Example: Varargs Syntax Rules

java
// Define the class Main
public class Main {
	static void printAll(String label, int... numbers) {
		// Print to the console without a newline
		System.out.print(label + ": ");
		for (int n : numbers) {
			// Print to the console without a newline
			System.out.print(n + " ");
		}
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		printAll("Scores", 90, 85, 77);
	}
}

Varargs as Arrays

Since the varargs parameter really is just an array under the hood, you can pass an existing array directly instead of listing individual values, and the method behaves identically either way.

This is handy when the values already come from another array or a collection converted to one.

Example: Varargs as Arrays

java
// Define the class Main
public class Main {
	static int sum(int... numbers) {
		// Declare total and set it to 0
		int total = 0;
		for (int n : numbers) {
			total += n;
		}
		// Send total back to the caller
		return total;
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Declare values and set it to {4, 5, 6}
		int[] values = {4, 5, 6};
		// Print a line to the console
		System.out.println(sum(values));
	}
}

Overloading Varargs Methods

You can overload a varargs method with fixed-arity versions of the same name, but the compiler prefers the most specific matching signature, so ambiguous overloads (e.g. two versions that could both match a given call) will fail to compile rather than silently picking one.

Example: Overloading Varargs Methods

java
public class Main {
	static int sum(int a, int b) {
		return a + b;
	}
	static int sum(int... numbers) {
		int total = 0;
		for (int n : numbers) {
			total += n;
		}
		return total;
	}
	public static void main(String[] args) {
		System.out.println(sum(1, 2)); // matches the fixed-arity version
		System.out.println(sum(1, 2, 3));
	}
}

Empty Varargs

Calling a varargs method with no arguments at all is legal; the parameter still exists inside the method as an array, just with a length of 0.

Code that assumes the array always has at least one element will throw an ArrayIndexOutOfBoundsException in that case, so guard against an empty array explicitly.

Example: Empty Varargs

java
// Define the class Main
public class Main {
	static int sum(int... numbers) {
		// Print a line to the console
		System.out.println("Length: " + numbers.length);
		// Declare total and set it to 0
		int total = 0;
		for (int n : numbers) {
			total += n;
		}
		// Send total back to the caller
		return total;
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Print a line to the console
		System.out.println(sum());
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Placing the varargs parameter first, when it must be the last parameter.
  2. Declaring two varargs parameters in one method, which is a compile error.
  3. Calling f(null) and being surprised that the array is null, so it can throw NullPointerException.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.