Command-line arguments allow users to customize program execution by passing input parameters directly from the terminal or console when launching the JVM.
Every value passed after the class name is captured as an element inside the String[] args array:
# Terminal invocation:
java Calculator 15 25 add
public class Calculator {
public static void main(String[] args) {
// Validate argument length
if (args.length < 3) {
System.out.println("Usage: java Calculator <num1> <num2> <add|sub|mul|div>");
return;
}
// Convert String arguments to numerical primitives
double num1 = Double.parseDouble(args[0]);
double num2 = Double.parseDouble(args[1]);
String operation = args[2].toLowerCase();
double result = switch (operation) {
case "add" -> num1 + num2;
case "sub" -> num1 - num2;
case "mul" -> num1 * num2;
case "div" -> {
if (num2 == 0) throw new ArithmeticException("Cannot divide by zero!");
yield num1 / num2;
}
default -> throw new IllegalArgumentException("Unknown operator: " + operation);
};
System.out.println("Result: " + result);
}
}
Exam Question: "Can we rename String[] args to String[] params or use varargs String... args?"
Answer: Yes! The parameter name args is purely conventional; you can rename it to String[] myArgs without issue. Furthermore, since Java 5, writing public static void main(String... args) (using varargs syntax) is 100% valid and recognized by the JVM launcher!
Now let us explore the immutable Java String class, memory allocation, and the String Constant Pool. Proceed to: Java String Class & SCP Pool →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Understanding array structures.
Parsing numbers with Integer.parseInt().
Public static void main breakdown.
String manipulation.