Command-line and variable-length arguments
How Java programs receive command-line arguments via the main method's String[] (or String...) parameter and how to write and use variable-length (varargs) parameters with the ... syntax, including rules, examples and common exam points.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Command-line arguments let a Java program receive inputs when it starts (useful for scripts, testing, and small utilities). Variable-length arguments (varargs) let methods accept any number of parameters of the same type without the caller building an array explicitly — this makes APIs cleaner and exam programs shorter.
Key ideas
Properties and assumptions: arguments are always strings; they are not parsed by Java — the shell or command prompt splits text into tokens (typically by whitespace) before Java receives them. Quoting rules (single/double quotes) are handled by the shell/OS.
How to use: inside main you inspect
args.lengthand read elementsargs[0],args[1], ... Indexing is zero-based. Ifargs.length == 0there were no command-line arguments.Common main signatures the compiler/JVM accepts:
public static void main(String[] args)andpublic static void main(String... args). The JVM/launcher requirespublic static voidand a single parameter of typeString[](varargs syntax compiles to the same). If these are not satisfied, the launcher prints: Error: Main method not found in class <ClassName>; please define the main method as: public static void main(String[] args). The parameter name may be anything (not necessarilyargs), and the array passed by the launcher is never null (it may have length 0). You may overloadmain, but only this exact signature is used as the entry point.Variable-length arguments (varargs): a Java language feature that lets a method accept zero or more arguments of a specified type.
- Definition: a varargs parameter is declared as
Type... namein the method parameter list. Example:void printAll(String... items). - How it works: inside the method, the varargs parameter behaves as an array of the declared type (for
String...it isString[]at runtime). The compiler creates an array when the method is called with individual arguments; if the caller already has an array, it can be passed directly. - Rules and constraints (exact statements examiners expect):
- A varargs parameter must be the last parameter in the method's parameter list. Example:
void f(int a, String... s)is valid;void f(String... s, int a)is not. - A method can have at most one varargs parameter.
- At compile time,
T...is translated toT[]for the method signature; therefore you cannot overload two methods that would have identical signatures after this translation (e.g.,m(int[] a)andm(int... a)cause a compile error due to duplicate signature). - Inside the method, treat the varargs parameter exactly like an array: check its
.length, iterate withforor enhanced-for. - You can call
mainaspublic static void main(String... args)if you prefer varargs syntax.
- A varargs parameter must be the last parameter in the method's parameter list. Example:
- Definition: a varargs parameter is declared as
Converting and parsing arguments: since args are strings, convert them using parsing methods (e.g.,
Integer.parseInt,Double.parseDouble). These methods throwNumberFormatException(an unchecked runtime exception) for invalid input — you can handle it with try/catch; you do not need to declare it.Shell/tokenization notes: spaces separate arguments; to include a space inside one argument, use quotes. Example to pass two arguments where the second contains a space: on Unix
java Program first "second with spaces".Overloading and varargs interactions: varargs can make overload resolution confusing. The compiler prefers exact matches; if both a varargs method and a fixed-arity method can match a call, the fixed-arity method is chosen. In general, overload resolution prefers: exact match > primitive widening > boxing > varargs.
Formulas
List of syntax lines to remember:
public static void main(String[] args) — program entry point; args is an array of command-line tokens.
public static void main(String... args) — same as above using varargs syntax.
void method(Type... name) — declare a varargs parameter; inside method it is Type[] name.
if (args.length == 0) — check if no command-line arguments were supplied.
String s = args[i]; — access i-th command-line argument (0-based).
int n = Integer.parseInt(args[i]); — convert string to int; throws NumberFormatException if bad input.
double avg = average(1, 2, 3); — calling a varargs method with individual arguments.
double avg = average(new double[]{1.0, 2.0, 3.0}); — calling varargs with an array explicitly.
Worked examples
- Sum integers passed on the command line (handle incorrect input)
Code (file name SumIntegers.java):
public class SumIntegers {
public static void main(String[] args) {
int sum = 0;
if (args.length == 0) {
System.out.println("No integers provided");
return;
}
try {
for (int i = 0; i < args.length; i++) {
sum += Integer.parseInt(args[i]);
}
System.out.println("Sum = " + sum);
} catch (NumberFormatException e) {
System.out.println("Error: all arguments must be integers");
}
}
}
Run and sample outputs (commands you type):
java SumIntegers 10 20 30
Output:
Sum = 60
java SumIntegers 4 a 6
Output:
Error: all arguments must be integers
- Varargs method to compute average of numbers
Code (file name AverageExample.java):
public class AverageExample {
static double average(double... values) {
if (values.length == 0) return 0.0;
double s = 0.0;
for (double v : values) s += v;
return s / values.length;
}
public static void main(String[] args) {
System.out.println(average(2.0, 3.0, 5.0));
// calling with an array
double[] arr = {10.0, 20.0};
System.out.println(average(arr));
// no arguments
System.out.println(average());
}
}
Run and sample output:
java AverageExample
Output:
3.3333333333333335
15.0
0.0
- Varargs vs array signature conflict (compile-time example)
Code (file name VarargsConflict.java):
public class VarargsConflict {
// The next two method declarations would cause a compile-time error
// because after translation both have the same signature: m(int[])
// void m(int[] a) { }
// void m(int... a) { }
public static void main(String[] args) { }
}
If the commented methods are both uncommented, javac reports an error about duplicate methods. This demonstrates the rule: varargs is syntactic sugar for an array parameter.
Common mistakes
- Declaring more than one varargs parameter in a method (not allowed).
- Writing an incorrect main signature (e.g., missing
publicorstatic); this can cause runtime "NoSuchMethodError: main". - Assuming the shell's quoting rules are Java rules; quoting and tokenization are done by the shell/OS before Java sees arguments.
- Trying to overload a method with
T[]andT...(duplicate signature) or creating ambiguous overloads involving autoboxing and varargs. - Index-out-of-bounds: always check
args.lengthbefore usingargs[i].
For your exam
Types of questions you will see:
- Definition questions: define command-line arguments, varargs, and state rules for varargs (must be last, only one allowed).
- Short notes: how to parse command-line arguments; main method forms; differences between
String[]andString.... - Programs: small programs that read command-line arguments (e.g., compute sum, max, sort) or implement a method using varargs (e.g., find average, concatenate strings).
- Error-finding: given code with varargs misuse or wrong main signature, identify and correct errors.
What full-marks answers include:
- Precise definitions (bold the term if asked), statement of exact rules (e.g., varargs must be last), and code that compiles and handles edge cases (no arguments, bad numeric input). For program questions include sample run and exact output. For theoretical questions explain where tokenization happens (shell) and that arguments are always strings.
Quick check
- How do you declare main using varargs syntax?
- Can a method have two varargs parameters? Why or why not?
- If args = new String[]{"10","20"}, what is args.length and what type is args[0]?
Answers: 1. public static void main(String... args) 2. No — Java allows at most one varargs parameter and it must be the last parameter 3. args.length == 2 and args[0] is a String (value "10").
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?