Java Command Line Arguments



In this article, we will learn how to use command-line arguments in Java. Command-line arguments provide a way to pass information to a program when it is executed from the command line. These arguments are passed to the main method of the Java program as an array of String values, allowing the program to access and use them directly.

Problem Statement

Given a Java program, the task is to display all of the command-line arguments passed to the program when it is executed.

Input

Command-line arguments:
this is a command line 200 -100
Output
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

Steps to display command-line arguments

The following are the steps to display command-line arguments

  • Define the main method with a parameter of type String[] to accept command-line arguments.
  • Use a loop to iterate over the args array and print each command-line argument.
  • Display the index and the value of each argument.
  • Java Program to display command-line arguments.

Java program to display command-line arguments

The following program displays all of the command-line arguments:

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

Try executing this program as shown here -

$java CommandLine this is a command line 200 -100

Output

args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

Code Explanation

The program accepts command-line arguments passed when the program is executed. The main method takes these arguments in the args array. A for loop is used to iterate over the array, and for each argument, it prints the index and the value of the argument using System.out.println(). This allows the program to display all of the passed arguments dynamically when the program is executed from the command line.

Updated on: 2024-11-07T17:45:37+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements