In the Method Overloading chapter, we saw that we can write several versions of a method that take different numbers of parameters. But imagine a method that adds numbers. How many versions should we write?
static int sum(int a, int b) { ... }
static int sum(int a, int b, int c) { ... }
static int sum(int a, int b, int c, int d) { ... }
// and so on, forever?
This quickly becomes silly. Java has a better solution called varargs (variable-length arguments), which lets one method accept any number of values.
In this chapter, we will also look at a closely related topic: command-line arguments, which finally explains the String[] args part of main() that we have been writing since our first program.
What are Varargs?
A varargs parameter is written with three dots (...) after the type:
static int sum(int... numbers) {
// numbers can hold zero, one, or many int values
}
Now we can call the same method with any number of int values:
sum();
sum(5);
sum(10, 20);
sum(1, 2, 3, 4, 5);
Varargs were added in Java 5. You have actually been using a varargs method already: System.out.printf() from the Output chapter accepts any number of values after the format text.
How Varargs Work Inside
Here is the secret: inside the method, a varargs parameter is simply an array. When we call sum(10, 20, 30), the compiler quietly packs the values into an array for us:
You write: sum(10, 20, 30);
Compiler turns it: sum(new int[] {10, 20, 30});
Inside sum():
numbers → [ 10 | 20 | 30 ]
index 0 1 2
numbers.length = 3
We will study arrays fully in the Arrays chapter, which comes right after Recursion. For this chapter, we only need three small things, some of which you already saw briefly in the Method Parameters chapter:
numbers.lengthgives how many values were passed.numbers[0]is the first value,numbers[1]the second, and so on. Positions (indexes) start at 0.A
forloop from0tolength - 1visits every value.
A Complete Varargs Example
class Main {
static int sum(int... numbers) {
int total = 0;
for (int i = 0; i < numbers.length; i++) {
total = total + numbers[i];
}
return total;
}
public static void main(String[] args) {
System.out.println(sum());
System.out.println(sum(5));
System.out.println(sum(10, 20));
System.out.println(sum(1, 2, 3, 4, 5));
int[] marks = {70, 80, 90};
System.out.println(sum(marks));
}
}
Output:
0
5
30
15
240
Notice two things:
sum()with no values is allowed. Java passes an empty array (lengthis 0), the loop runs zero times, and the result is0.Because a varargs parameter is really an array, we can also pass an existing
int[]directly, as insum(marks).
Rules of Varargs
Rule 1: A method can have only one varargs parameter, and it must be the last parameter.
Normal parameters can come before it:
static void printReport(String name, int... marks) // OK
But these do not compile:
static void f(int... a, String s) { } // Error: varargs is not last
static void g(int... a, double... b) { } // Error: two varargs
error: varargs parameter must be the last parameter
This rule makes sense. In a call like f(1, 2, 3, "Hi"), Java needs to know where the variable part ends. If the varargs part is always last, everything after the fixed parameters belongs to it.
Rule 2: The values must match the type. sum(1, 2, "three") does not compile, because "three" is not an int.
Rule 3: Inside the method, treat it as an array. It may be empty, so be careful before reading numbers[0].
Varargs with Normal Parameters
Let's write a method that takes a student's name (always required) followed by any number of marks:
class Main {
static void printReport(String name, int... marks) {
if (marks.length == 0) {
System.out.println(name + ": no marks entered");
return;
}
int total = 0;
int highest = marks[0];
for (int i = 0; i < marks.length; i++) {
total = total + marks[i];
highest = Math.max(highest, marks[i]);
}
double average = (double) total / marks.length;
System.out.println(name + ": subjects = " + marks.length
+ ", total = " + total
+ ", highest = " + highest
+ ", average = " + average);
}
public static void main(String[] args) {
printReport("Aman", 78, 85, 92);
printReport("Priya", 88, 95);
printReport("Rohit");
System.out.printf("%s scored %d in %d subjects%n", "Neha", 450, 5);
}
}
Output:
Aman: subjects = 3, total = 255, highest = 92, average = 85.0
Priya: subjects = 2, total = 183, highest = 95, average = 91.5
Rohit: no marks entered
Neha scored 450 in 5 subjects
The first argument always goes to name, and everything after it goes into the marks array. For "Rohit", the array is empty, and our if check avoids reading marks[0] from an empty array.
The last line uses printf(), which is declared in the Java library roughly as printf(String format, Object... args). The format text is the normal parameter, and "Neha", 450, 5 are the varargs.
Varargs and Method Overloading
What happens if a varargs method and a normal method could both handle a call?
static void show(int a, int b) { System.out.println("fixed"); }
static void show(int... a) { System.out.println("varargs"); }
show(1, 2); // fixed
show(1, 2, 3); // varargs
show(1); // varargs
Java always prefers a method without varargs when one matches. It considers varargs methods only as a last option. So show(1, 2) picks the two-parameter version, while show(1, 2, 3) and show(1) can only be handled by the varargs version.
Overloading two varargs methods, however, can easily confuse the compiler:
static void print(int... a) { }
static void print(String... s) { }
print(); // Error
error: reference to print is ambiguous
both method print(int...) in Main and method print(String...) in Main match
With no arguments, both methods match equally well (each would receive an empty array), so Java refuses to guess. The same happens with print(int a, int... b) and print(int... a) when we call print(1). The lesson: avoid overloading varargs methods unless you really need to.
Varargs vs Array Parameter
|
| |
|---|---|---|
Call with separate values: | Yes | No, compile error |
Call with an array: | Yes | Yes |
Call with nothing: | Yes (empty array) | No, compile error |
Position | Must be the last parameter | Can be anywhere |
How many per method | Only one | Any number |
Inside the method | An array | An array |
Command-Line Arguments
Now let's look at main() again:
public static void main(String[] args)
The parameter args is an array of String values. It holds the command-line arguments: extra words we type after the class name when we run the program from a terminal.
java Main Ravi 21 Delhi
│ │ │
│ │ └── args[2] = "Delhi"
│ └───── args[1] = "21"
└────────── args[0] = "Ravi"
The words we typed after Main are split at the spaces (this splitting is done by the terminal), and the JVM puts the pieces into a String array and passes that array to main(). That is how a program can receive input without using Scanner.
Let's print whatever we receive:
class Main {
public static void main(String[] args) {
System.out.println("Number of arguments: " + args.length);
for (int i = 0; i < args.length; i++) {
System.out.println("args[" + i + "] = " + args[i]);
}
}
}
Compile once, then run it with different arguments:
javac Main.java
java Main Ravi 21 Delhi
Output:
Number of arguments: 3
args[0] = Ravi
args[1] = 21
args[2] = Delhi
If an argument contains a space, wrap it in double quotes so that it stays one argument:
java Main "Ravi Kumar" 21
Output:
Number of arguments: 2
args[0] = Ravi Kumar
args[1] = 21
And if we pass nothing at all (java Main), args is an empty array, not null:
Number of arguments: 0
A few useful details:
The class name itself is not part of
args.args[0]is the first word after the class name.With the single-file launcher from the First Java Program chapter, arguments go after the file name:
java Main.java Ravi 21.Anything written before the class name is an option for the JVM, not for your program. For example, in
java -Xmx512m Main Ravi, the option-Xmx512mgoes to the JVM, and onlyRavigoes intoargs.In an IDE, you set program arguments in the Run Configuration instead of typing them.
Arguments Are Always Strings
Even if you type a number, it arrives as text. To do maths with it, we must convert it with Integer.parseInt() (or Double.parseDouble() for decimals). We will learn more about these methods in the Wrapper Classes chapter.
class Main {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: java Main <number1> <number2>");
return;
}
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println(args[0] + args[1]);
System.out.println(a + " + " + b + " = " + (a + b));
}
}
Running java Main 10 20 gives:
1020
10 + 20 = 30
The first line shows the classic trap: args[0] + args[1] joins the two strings "10" and "20" into "1020". Only after converting them to int do we get 30.
Running java Main 5 (only one number) prints the usage message, thanks to our args.length check:
Usage: java Main <number1> <number2>
Without that check, reading args[1] would crash the program. For example, a program that prints args[0] and is run with no arguments fails like this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
And if the text is not a valid number, such as java Main ten 20, parseInt() fails with:
Exception in thread "main" java.lang.NumberFormatException: For input string: "ten"
We will learn how to handle such errors gracefully in the Exception Handling chapter.
main() with Varargs
Since a varargs parameter is just an array, main() can also be written like this:
public static void main(String... args) {
System.out.println("This works too!");
}
The JVM accepts it as a normal entry point. It is a popular interview trick question, but in real code everyone uses String[] args. (As we saw in the Java Program Structure chapter, Java 25 also allows a simpler void main() with no parameters. That form simply has no args to read.)
Common Mistakes
Putting the varargs parameter first.
f(int... a, String s)does not compile. Varargs must be last.Reading
numbers[0]without checking the length. A varargs method can be called with zero values.Adding command-line numbers without converting.
args[0] + args[1]joins text; useInteger.parseInt()first.Expecting
args[0]to be the program name. In Java it is the first real argument (unlike C, whereargv[0]is the program name).Forgetting quotes around arguments with spaces.
java Main Ravi Kumargives two arguments, not one.Overloading varargs methods in ways that make calls ambiguous.
Interview Corner
What is the type of a varargs parameter inside the method? An array.
int... numbersis anint[].Can a method have two varargs parameters? No. Only one, and it must be the last parameter.
Is
public static void main(String... args)valid? Yes.What is
args.lengthwhen no arguments are passed?0.argsis an empty array, nevernull, when the JVM starts the program.Between a fixed-parameter method and a varargs method that both match, which is called? The fixed-parameter method. Varargs is only used when nothing else fits.
Quick Revision
type... namelets a method accept zero or more values, which arrive as an array.String[] argsinmain()receives the words typed after the class name, always as Strings.
Varargs: only one per method, always last, may be empty, can also accept an existing array.
Fixed-parameter overloads win over varargs.
Command-line arguments:
args.lengthtells how many; quote arguments with spaces; convert numbers withInteger.parseInt().