C

Core Java tutorial for beginners

Clean • Professional

Core Java – Command-line Arguments in Java

3 minute

Command-line Arguments in Java (As Arrays)

In Java, command-line arguments are parameters passed to a program when it is run from the terminal or command prompt. These arguments are received as an array of Strings in the main method.

Syntax

public class MyClass {
    public static void main(String[] args) {
        // args is a String array containing command-line arguments
    }
}
  • args is a String array (String[]).
  • Each element of the array corresponds to a command-line argument.
  • args.length gives the number of arguments passed.

Example 1 – Printing Command-line Arguments

public class CommandLineArgsExample {
    public static void main(String[] args) {
        System.out.println("Number of arguments: " + args.length);

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

Run Example

java CommandLineArgsExample Java 123 Hello

Output

Number of arguments: 3
Argument 0: Java
Argument 1: 123
Argument 2: Hello

Accessing Arguments

  • args[0] → first argument
  • args[1] → second argument
  • And so on…

Note: Accessing an index not passed will throw ArrayIndexOutOfBoundsException.


Converting Arguments to Other Types

Since command-line arguments are Strings, you often need to convert them to numbers or other types.

Example – Convert String to Integer

public class ArgsConversion {
    public static void main(String[] args) {
        if(args.length > 0) {
            int num = Integer.parseInt(args[0]); // Convert first argument to int
            System.out.println("Square: " + (num * num));
        } else {
            System.out.println("No arguments passed!");
        }
    }
}

Example – Sum of Numbers from Command-line Arguments

public class SumArgs {
    public static void main(String[] args) {
        int sum = 0;

        for(String arg : args) {
            sum += Integer.parseInt(arg); // Convert each argument to int
        }

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

Run Example

java SumArgs 10 20 30

Output

Sum: 60

Points to Remember

  • Command-line arguments are always passed as String arrays (String[] args).
  • Use args.length to check number of arguments.
  • Convert arguments to numeric types using:
    • Integer.parseInt()
    • Double.parseDouble()
    • Float.parseFloat() etc.
  • Can pass numbers, words, file paths, or configuration values.
  • If no arguments are passed, args.length will be 0.
  • Useful for dynamic input, automation scripts, file processing, and configuration settings.

🏆 Top 5 Interview Questions – Command-line Arguments

1. What is the purpose of command-line arguments in Java?

Answer:

  • Command-line arguments allow you to pass data to a Java program at runtime without hardcoding values.
  • They are received as an array of String objects in the main method:
public static void main(String[] args) { }

2. How do you convert a command-line argument from String to int?

Answer: Command-line arguments are always Strings, so you need parsing:

public class CommandLineExample {
    public static void main(String[] args) {
        int number = Integer.parseInt(args[0]); // convert first argument to int
        System.out.println("Number is: " + number);
    }
}

Other conversions:

  • Double.parseDouble(args[0]) → for double
  • Boolean.parseBoolean(args[0]) → for boolean

Always handle NumberFormatException if the input may be invalid.


3. Can command-line arguments accept file paths or configuration values?

Answer: Yes, Any text can be passed as an argument, including:

  • File paths: "C:\\Users\\file.txt"
  • URLs: "<https://example.com>"
  • Configuration values: "debug=true" or "maxThreads=10"
public class FilePathExample {
    public static void main(String[] args) {
        String filePath = args[0];
        System.out.println("File path: " + filePath);
    }
}

4. What happens if no arguments are passed to main(String[] args)?

Answer:

  • args will be an empty array (length = 0), not null.
  • Accessing args[0] without checking length causes ArrayIndexOutOfBoundsException.
public class NoArgsExample {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("No arguments passed!");
        }
    }
}

5. Difference between args and regular method parameters?

Answer:

Featureargs (Command-line)Regular Method Parameters
PurposePass data at runtime from terminalPass data programmatically when calling method
TypeAlways String[]Can be any type (int, double, Object, etc.)
SourceExternal input (command line)Internal code (caller method)
OptionalCan be empty (args.length=0)Depends on method signature


Article 0 of 0