Command-line Arguments in Java (As Arrays)
In Java, command-line arguments are parameters passed to a program when it is run from the terminal or command prompt. These arguments are received as an array of Strings in the main method.
Syntax
public class MyClass {
public static void main(String[] args) {
// args is a String array containing command-line arguments
}
}
argsis a String array (String[]).- Each element of the array corresponds to a command-line argument.
args.lengthgives the number of arguments passed.
Example 1 – Printing Command-line Arguments
public class CommandLineArgsExample {
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("Argument " + i + ": " + args[i]);
}
}
}
Run Example
java CommandLineArgsExample Java 123 Hello
Output
Number of arguments: 3
Argument 0: Java
Argument 1: 123
Argument 2: Hello
Accessing Arguments
args[0]→ first argumentargs[1]→ second argument- And so on…
Note: Accessing an index not passed will throw ArrayIndexOutOfBoundsException.
Converting Arguments to Other Types
Since command-line arguments are Strings, you often need to convert them to numbers or other types.
Example – Convert String to Integer
public class ArgsConversion {
public static void main(String[] args) {
if(args.length > 0) {
int num = Integer.parseInt(args[0]); // Convert first argument to int
System.out.println("Square: " + (num * num));
} else {
System.out.println("No arguments passed!");
}
}
}
Example – Sum of Numbers from Command-line Arguments
public class SumArgs {
public static void main(String[] args) {
int sum = 0;
for(String arg : args) {
sum += Integer.parseInt(arg); // Convert each argument to int
}
System.out.println("Sum: " + sum);
}
}
Run Example
java SumArgs 10 20 30
Output
Sum: 60
Points to Remember
- Command-line arguments are always passed as String arrays (
String[] args). - Use
args.lengthto check number of arguments. - Convert arguments to numeric types using:
Integer.parseInt()Double.parseDouble()Float.parseFloat()etc.
- Can pass numbers, words, file paths, or configuration values.
- If no arguments are passed,
args.lengthwill be0. - Useful for dynamic input, automation scripts, file processing, and configuration settings.
