C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Introduction to Java

Accept & Process Command-Line Arguments - Java Program

public class CommandLineDemo {

    public static void main(String[] args) {

 

        // Check if arguments are passed

        if (args.length == 0) {

            System.out.println("No command-line arguments found!");

            return;

        }

 

        System.out.println("Number of arguments: " + args.length);

        System.out.println("Arguments received:");

 

        // Display each argument

        for (int i = 0; i < args.length; i++) {

            System.out.println("Argument " + (i + 1) + ": " + args[i]);

        }

 

        // Example: If arguments are numbers, process them

        try {

            int sum = 0;

            for (String s : args) {

                sum += Integer.parseInt(s); // convert string to number

            }

            System.out.println("Sum of numeric arguments = " + sum);

        } catch (NumberFormatException e) {

            System.out.println("One or more arguments are not numbers. Skipping numeric processing.");

        }

    }

}

Output

 


Output 1 (When Passing Arguments)

Command Used:
java CommandLineDemo Hello Java 123

OUTPUT :
Number of arguments: 3
Arguments received:
Argument 1: Hello
Argument 2: Java
Argument 3: 123
One or more arguments are not numbers. Skipping numeric processing.
 
Output 2 (Numeric Arguments)

Command Used:
java CommandLineDemo 10 20 30

OUTPUT :
Number of arguments: 3
Arguments received:
Argument 1: 10
Argument 2: 20
Argument 3: 30
Sum of numeric arguments = 60
 


Explanation

Command-line arguments come from args[]

public static void main(String[] args)

  • args is an array of strings containing values typed after the program name.

Example:

java CommandLineDemo A B C

→ args[0] = "A"
→ args[1] = "B"
→ args[2] = "C"

Checking if arguments are passed

if (args.length == 0)

Stops program if no arguments are provided.

Loop to print each argument

for (int i = 0; i < args.length; i++)

    System.out.println("Argument " + (i + 1) + ": " + args[i]);

Convert arguments to integers

sum += Integer.parseInt(s);

  • Converts each string to integer
  • If any argument is non-numeric → caught by NumberFormatException

Displays processed result

If data is numeric → sum is printed.