Clean β’ Professional
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
}
}
args is a String array (String[]).args.length gives the number of arguments passed.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
Number of arguments: 3
Argument 0: Java
Argument 1: 123
Argument 2: Hello
args[0] β first argumentargs[1] β second argumentNote: Accessing an index not passed will throw ArrayIndexOutOfBoundsException.
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
String[] args).args.length to check number of arguments.Integer.parseInt()Double.parseDouble()Float.parseFloat() etc.args.length will be 0.