Command Line Argument in Java (Easy Explanation with Code & Output)

 



Command Line Arguments in Java

Easy Explanation with Code & Output

🧠 Introduction to Command Line Arguments in Java

Ever wondered how Java programs accept input without asking the user during execution? That's where command line arguments come into play. They're a simple yet powerful way to feed data directly when running a Java program.

🤔 What are Command Line Arguments?

Command Line Arguments are values passed to the program when you run it from the terminal/command prompt. They allow you to give input without using Scanner or BufferedReader.

💡 Why Use Command Line Arguments?

Automation: Pass input without manual effort
Testing: Feed different values without editing code
Configuration: Use them to pass file paths or flags

🔧 Basics of Command Line Arguments

📌 Syntax of Command Line Arguments

java ClassName arg1 arg2 arg3

These arguments are passed to the main() method like this:

public static void main(String[] args)

Here, args is an array of String.

🧪 How Java Accepts Command Line Inputs

The JVM (Java Virtual Machine) automatically stores any passed command-line arguments into the args[] array.

✍️ Writing Your First Java Program with Command Line Arguments

🖥️ Code Example

public class HelloArguments {
    public static void main(String[] args) {
        System.out.println("You entered " + args.length + " arguments.");
        for (int i = 0; i < args.length; i++) {
            System.out.println("Argument " + (i + 1) + ": " + args[i]);
        }
    }
}

📘 Explanation of the Code

args.length tells how many arguments were passed.
args[i] fetches each argument one by one.

📤 Sample Output

If you run it as:

java HelloArguments Apple Banana Mango

Output:

You entered 3 arguments.
Argument 1: Apple
Argument 2: Banana
Argument 3: Mango

🔄 Reading and Using Command Line Arguments

💡 Example: Sum of Two Numbers

public class SumExample {
    public static void main(String[] args) {
        int num1 = Integer.parseInt(args[0]);
        int num2 = Integer.parseInt(args[1]);
        int sum = num1 + num2;

        System.out.println("Sum: " + sum);
    }
}

🔎 Output

java SumExample 5 10
Sum: 15

Handling Errors in Command Line Arguments

🚫 Missing Arguments

if (args.length < 2) {
    System.out.println("Please provide 2 numbers.");
    return;
}

⚠️ Format Exceptions

Using Integer.parseInt() with non-numeric values causes NumberFormatException.

try {
    int x = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
    System.out.println("Please enter valid integers.");
}

🔁 Looping Through Command Line Arguments

for (String arg : args) {
    System.out.println("Arg: " + arg);
}

This is a for-each loop, great for readability and cleaner code.

🔄 Type Conversion and Parsing

double price = Double.parseDouble(args[0]);
float rating = Float.parseFloat(args[1]);

Java offers many methods like:

Integer.parseInt()
Double.parseDouble()
Float.parseFloat()
Boolean.parseBoolean()

🚀 Advanced Usage

📂 Passing File Paths or Configuration

java ConfigReader /home/user/config.txt

You can use args[0] to read and open files dynamically.

👍 Best Practices

Always validate args.length before accessing elements
Use try-catch to handle bad inputs
Provide clear messages if arguments are missing

🌍 Real-World Applications

Build tools like Maven use command line args
Java commands like javac and java use flags and arguments
CLI-based automation scripts often rely on these inputs

😵 Common Mistakes

Not checking args.length
Wrong parsing (e.g., Integer.parseInt("abc"))
Out-of-bounds error with args[5] when only 2 args exist

🔍 Pros and Cons

✅ Pros

Simple to use
Great for automation
Doesn't require interactive input

❌ Cons

Limited for complex inputs
Must be used carefully to avoid crashes

📌 Summary

Command Line Arguments in Java are a powerful tool that lets you pass values directly during program execution. They're great for small utilities, scripts, and tools. Just remember: always validate, convert carefully, and make your programs user-friendly.

🏁 Conclusion

Understanding command line arguments can simplify your Java programs and make them more dynamic and flexible. Whether you're a student just starting out or a developer scripting a tool, command line inputs are your best friend when you need fast, efficient, and clean input handling.

FAQs

1. What is args[] in Java?

It's a String array that stores the values passed when you run your program via terminal.

2. Can I pass multiple values via command line?

Yes! Just separate them with spaces when you run the program.

3. How do I handle no arguments?

Use args.length to check if arguments exist before accessing them.

4. Can command line arguments be optional?

Yes. Just use default values if an argument is missing.

5. What is the type of command line arguments in Java?

They are always String, so you need to parse them into numbers or booleans manually.


Post a Comment

0 Comments