COMMAND LINE ARGUMENT
PROCESSIONG IN JAVA
COMMAND-LINE
ARGUMENT
PROCESSING IN JAVA
Understanding how to handle arguments passed
during program execution
WHAT ARE COMMAND-LINE
ARGUMENTS?
- Inputs passed to a Java program from the
terminal or command prompt.
- Stored in the `String[] args` array in the
`main` method.
SYNTAX
public class Example {
public static void main(String[] args) {
// Code here
}
}
```
- `args` is the name of the parameter (can
be anything).
- It is an array of `String` type.
HOW TO PASS ARGUMENTS
**Command:**
```bash
java Example Hello World
```
**Output:**
- `args[0] = "Hello"`
- `args[1] = "World"`
EXAMPLE PROGRAM
public class CommandLineExample {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i
+ ": " + args[i]);
}
}
}
OUTPUT EXAMPLE
**Run:**
```bash
java CommandLineExample Java Programming
```
**Output:**
```
Argument 0: Java
Argument 1: Programming
```
USE CASES
- Passing filenames or configuration options.
- Providing inputs without using a scanner or
GUI.
- Useful for automation and scripting.
POINTS TO REMEMBER
- Arguments are always strings — must be
parsed if you need integers.
- `args.length` gives the number of
arguments.
- Use `Integer.parseInt(args[0])` to convert to
numbers.
ERROR HANDLING EXAMPLE
public class SafeArgs {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Please provide at
least one argument.");
} else {
System.out.println("First argument: " +
args[0]);
}
}}
CONCLUSION
- Simple and effective way to input data
during runtime.
- Helps in creating flexible and dynamic
applications.
THANK
YOU