DEV Community

Mohammed mhanna
Mohammed mhanna

Posted on

Java Program with Command-Line Arguments

1️⃣ Program Purpose

Demonstrates:

Receiving command-line arguments (args[]) in main.

Validating input (args.length).

Parsing Strings to integers (Integer.parseInt).

Creating and filling arrays dynamically.

Calculating values based on a formula.

Formatted output using printf.

2️⃣ Program Code

public class Main {
    public static void main(String[] args) {
        // Check number of command-line arguments
        if (args.length != 3) {
            System.out.printf("Error: Please re-enter the entire command, including%n" +
                              "an array size , initial value and increment.%n");
        } else {
            // Convert command-line arguments from String to int
            int arrayLength = Integer.parseInt(args[0]);
            int initialValue = Integer.parseInt(args[1]);
            int increment = Integer.parseInt(args[2]);

            // Create array dynamically
            int[] array = new int[arrayLength];

            // Fill array with calculated values
            for (int counter = 0; counter < array.length; counter++) {
                array[counter] = initialValue + increment * counter;
            }

            // Print header
            System.out.printf("%s%8s%n", "Index", "Value");

            // Display array values
            for (int counter = 0; counter < arrayLength; counter++) {
                System.out.printf("%5d%8d%n", counter, array[counter]);
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

3️⃣ Command-Line Arguments (args)

args is a String array provided automatically by the JVM.

Each argument after the class name in the terminal is stored as an element:

java Main 5 0 4
args[0] = "5"   // array size
args[1] = "0"   // initial value
args[2] = "4"   // increment
Enter fullscreen mode Exit fullscreen mode

Length check: args.length tells you how many arguments were passed.

Behind the scenes: JVM creates the array and calls Main.main(args) automatically.


4️⃣ Parsing Arguments

All command-line arguments are Strings, even numbers.

Convert to integers:

int arrayLength = Integer.parseInt(args[0]);
int initialValue = Integer.parseInt(args[1]);
int increment = Integer.parseInt(args[2]);
Enter fullscreen mode Exit fullscreen mode

Always validate input (args.length) to prevent exceptions.


5️⃣ Array Creation

Array is created dynamically using the first argument:

int[] array = new int[arrayLength];

Enter fullscreen mode Exit fullscreen mode

Can hold any number of elements specified by the user.


6️⃣ Calculating Array Values

Loop over array indices:

for (int counter = 0; counter < array.length; counter++) {
    array[counter] = initialValue + increment * counter;
}
Enter fullscreen mode Exit fullscreen mode

Formula: value = initial + increment × index

EX:

initialValue = 0, increment = 4, arrayLength = 5
array = [0, 4, 8, 12, 16]
Enter fullscreen mode Exit fullscreen mode

7️⃣ Displaying Results

Print header:

System.out.printf("%s%8s%n", "Index", "Value");

Enter fullscreen mode Exit fullscreen mode

Print each array element aligned:

System.out.printf("%5d%8d%n", counter, array[counter]);

Enter fullscreen mode Exit fullscreen mode

Output example:

Index Value
0 0
1 4
2 8
3 12
4 16


8️⃣ Running the Program

In CMD:

javac Main.java       # Compile
java Main 5 0 4       # Run with arguments

Enter fullscreen mode Exit fullscreen mode

In IntelliJ:

Go to Run → Edit Configurations.

Set Program Arguments: 5 0 4.

Click Run → Output appears in the IDE console.


9️⃣ Key Concepts Illustrated

Command-Line Arguments

Automatically passed to main(String[] args).

Always Strings; need parsing for numbers.

Input Validation

Check args.length to ensure correct number of arguments.

Dynamic Array Creation

Array size determined at runtime by user input.

For Loop Calculation

Can generate sequences programmatically.

Formatted Output

printf allows aligned tables and readable output.

JVM Behind-the-Scenes

JVM creates args[] array and passes it to main automatically.


💡 Tip for Notes:
You can draw a flow like this:

Terminal input → JVM parses → args[] → Parse to int → Array → Fill → Display


Key Takeaways

args[] is filled by JVM automatically from terminal input.

Always validate args.length to avoid errors.

Command-line arguments are Strings → must parse to numbers if needed.

Arrays can be dynamic in size based on user input.

Formatted output makes results readable.

You can run this program either via CMD or IntelliJ terminal, or by setting Program Arguments in IntelliJ run configuration.

Top comments (0)