Working with args
In Java, the args[] array stores command line arguments passed to the
program during execution.
Let’s explore what happens when we work with args — both when valid inputs are provided
and when they are missing.
Adding Two Numbers Using Command Line Arguments
Let's look at a simple program where we try to pass two numbers and add them:
class Main {
public static void main(String[] args) {
System.out.println(args[0] + args[1]);
}
}
Now compile and run the program from the command line:
D:/shikshasanchar/> javac Main.java
D:/shikshasanchar/> java Main 7 9
Output:
79
Explanation:
Even though we passed two numbers, the output is not 16. That's because command line arguments are always received as strings. So here, "7" + "9" results in string concatenation — "79" instead of addition. To actually add the numbers, we must convert the string arguments to integers using:
int sum = Integer.parseInt(args[0]) + Integer.parseInt(args[1]);
What If Fewer or No Arguments Are Passed?
Let’s look at a program expecting two command line arguments:
class Main {
public static void main(String[] args) {
System.out.println(args[0]);
System.out.println(args[1]); // May cause an exception
System.out.println("Hello");
}
}
Case 1 : Passing only one argument
D:/shikshasanchar/> java Main Something
Output:
Something
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of range
Explanation:
You passed only one argument (args[0] = "Something"), but the program also tries to
access args[1], which doesn't exist.
This causes an ArrayIndexOutOfBoundsException and the program terminates
abnormally.
Case 2 : Passing no arguments at all
D:/shikshasanchar/> java Main
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of range
Explanation:
Here, args[] is completely empty, so even trying to access args[0]
results in an error.
Summary
- The
args[]array holds command line inputs and is always of String type. - When adding numeric arguments, convert them to integers first to avoid string concatenation.
- Always validate the number of arguments before accessing them, to prevent exceptions.
- If arguments are missing, accessing out-of-range indexes in
args[]will cause your program to crash.