Varargs as Arrays
What You'll Learn
You'll learn that inside a method, a varargs parameter behaves exactly like an array and can be accessed using all standard array operations.
The Core Idea
When you declare a method with varargs (using ...), Java actually converts those variable arguments into an array behind the scenes. This means inside your method body, you can treat the varargs parameter just like any other array—using indexing, checking its length, or looping through its elements.
Think of varargs as a convenient delivery service: the caller sends individual items separately, but the method receives them all neatly packaged in an array box.
How It Works
public static void printNumbers(int... numbers) {
// 'numbers' is an int[] array
System.out.println("Length: " + numbers.length);
// Access by index
if (numbers.length > 0) {
System.out.println("First: " + numbers[0]);
}
// Loop like any array
for (int i = 0; i < numbers.length; i++) {
System.out.println("Item " + i + ": " + numbers[i]);
}
}
You can call this method with any number of arguments:
printNumbers(5); // numbers = {5}
printNumbers(10, 20, 30); // numbers = {10, 20, 30}
printNumbers(); // numbers = {} (empty array)
Why This Matters
Because varargs are arrays internally, you have full array capabilities: checking length to see how many arguments were passed, using loops to process them, or accessing specific elements by index. You never need to worry about conversion—Java handles it automatically.
Key Takeaway: Varargs parameters are arrays inside the method body—you can use length, indexing ([i]), and loops just like with any array.