Command Line Arguments in Java Explained

Command Line Arguments

Command line arguments provide a mechanism to pass data to a Java program at the time of execution, rather than hardcoding values or requesting interactive input. They enable programs to behave dynamically based on external input and are widely used in automation scripts, backend services, build tools, and production deployments.

In Java, command line arguments are handled through the main method and are available to the program before execution begins.


Purpose of Command Line Arguments

Command line arguments are used to:

They are especially useful in environments where programs are executed via scripts, schedulers, or CI/CD pipelines.


🔷 Command Line Arguments in Java

🔹 Program Entry Point

Every Java application starts execution from the main method:

public static void main(String[] args)

Here:


🔹 Key Characteristics of args

Even numeric values like 10 or 20 are received as strings.


🔹 Passing Command Line Arguments

Step 1: Compilation

javac Program.java

Step 2: Execution with Arguments

java Program value1 value2 value3

Each space-separated value becomes one element in the args array.


🔹 Basic Example: Accessing Arguments

Code

class CommandLineDemo {
    public static void main(String[] args) {
        System.out.println(args[0]);
        System.out.println(args[1]);
    }
}

Execution

java CommandLineDemo Java Programming

Output

Java
Programming

🔹 How Java Stores These Values

Command executed:

java Test 10 20 30

Internally:

args[0] → "10"
args[1] → "20"
args[2] → "30"

Array size:

args.length == 3

This mapping is automatic and handled by the JVM.


🔹 Iterating Over Command Line Arguments

Using Traditional for Loop

for (int i = 0; i < args.length; i++) {
    System.out.println(args[i]);
}

Execution

java Test A B C

Output

A
B
C

Using Enhanced for Loop

for (String value : args) {
    System.out.println(value);
}

Output (same input)

A
B
C

Both approaches are correct.
Choose based on whether index access is required.


🔹 Type Conversion of Arguments (Critical Concept)

Command line arguments are always strings.
Explicit conversion is required for numeric or logical operations.


🔸 String → int

int number = Integer.parseInt(args[0]);

🔸 String → double

double price = Double.parseDouble(args[1]);

🔸 String → boolean

boolean status = Boolean.parseBoolean(args[2]);

Accepted boolean values:


⚠️ Conversion Failure

If input cannot be converted:

Integer.parseInt("abc");

Result:

NumberFormatException

This is a runtime exception.


🔹 Complete Example with Type Conversion

Code

class Calculator {
    public static void main(String[] args) {

        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);

        int sum = a + b;
        System.out.println("Sum = " + sum);
    }
}

Execution

java Calculator 10 20

Output

Sum = 30

🔹 Validating Command Line Arguments (Best Practice)

Checking Argument Count

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

Prevents:


Handling Invalid Input

try {
    int value = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
    System.out.println("Invalid number format");
}

Prevents:


🔹 Default Values for Missing Arguments

Very common in real applications (servers, tools, utilities).

Example

int port = 8080;

if (args.length > 0) {
    port = Integer.parseInt(args[0]);
}

System.out.println("Running on port: " + port);

Execution

java Server

Output:

Running on port: 8080
java Server 9090

Output:

Running on port: 9090

🔹 Execution Flow Summary

  1. JVM starts the program
  2. main(String[] args) is called
  3. Command line values populate args
  4. Program logic processes them
  5. Conversion + validation ensures safety

Command Line Arguments vs User Input

AspectCommand Line ArgumentsUser Input
Input TimeProgram startRuntime
InteractionNon-interactiveInteractive
AutomationHighLow
Use CaseConfigurationUser-driven logic

Common Errors and Pitfalls

Such mistakes often cause runtime failures.


Use Cases in Professional Applications

Command line arguments are commonly used for:

They allow programs to remain flexible without code changes.


Best Practices

These practices improve reliability and usability.


Limitations of Command Line Arguments

For complex input, configuration files or environment variables are preferred.


Command Line Arguments in IDEs

Most IDEs allow specifying arguments:

This ensures consistency between development and deployment.


Takeaway

Conclusion

Command line arguments allow Java programs to receive input at execution time, enabling dynamic behavior without modifying source code. They are passed as a string array to the main method and require explicit validation and type conversion. Proper use of command line arguments improves automation, configurability, and deployment flexibility. Mastery of this concept is essential for developing production-ready Java applications.

🤖
PrepCampusPlus AI Tutor
Scroll to Top