Mastering Java Command-Line Arguments: How to Pass and Parse Parameters
Java Command-Line Arguments
Discover how to pass and parse command‑line arguments in Java, with practical examples that cover string and numeric inputs.
Command‑line arguments let you supply data to a Java program at runtime. They are entered directly after the class name when launching the application from a terminal.
Example: Command‑Line Arguments
class Main {
public static void main(String[] args) {
System.out.println("Command‑Line arguments are:");
for (String str : args) {
System.out.println(str);
}
}
}
Compile and run the program from the command line:
javac Main.java
java Main apple ball cat
The output will be:
Command‑Line arguments are: apple ball cat
In the main() method, String[] args holds every argument passed from the terminal. Arguments are always stored as strings and separated by whitespace.
Tip: Even if you intend to use numeric values, they arrive as strings. You can convert them later.
Passing Numeric Command-Line Arguments
Although main() only accepts String parameters, you can transform those strings into numeric types using parsing methods.
Example: Numeric Command-Line Arguments
class Main {
public static void main(String[] args) {
for (String str : args) {
int value = Integer.parseInt(str);
System.out.println("Argument as integer: " + value);
}
}
}
Compile and execute with numeric arguments:
javac Main.java
java Main 11 23
The output will be:
Argument as integer: 11 Argument as integer: 23
The key line is:
int value = Integer.parseInt(str);
Here Integer.parseInt() converts the string to an int. You can also use Double.parseDouble() or Float.parseFloat() for other numeric types.
Warning: If a string cannot be parsed, Java throws a NumberFormatException. Always validate input before parsing.
Java
- Master Java Operators: Types, Syntax, & Practical Examples
- Java Comments: Types, Usage, and Best Practices
- Mastering Java if…else: Control Flow Explained
- Master Java Constructors: Types, Usage, and Practical Examples
- Java this Keyword Explained: Practical Uses, Constructors, and More
- Mastering Java's super Keyword: Advanced Usage & Practical Examples
- Mastering Java Interfaces: Concepts, Implementation, and Best Practices
- Mastering Java Try‑with‑Resources: Automatic Resource Management Explained
- Java Annotations Explained: Types, Placement, and Practical Examples
- Command‑Line Arguments in Java: A Practical Guide with Code Examples