Command Line Arguments in Java with Example

In this tutorial, we will learn about the command line arguments in Java with the help of example programs.

The command line arguments in Java allow the programmers to pass arguments (i.e. values) to the main() method during the execution of the program from the outside.

It represents the arguments passed to the main() method. To catch and store these arguments, the main() method has a parameter, String args[ ] as:

public static void main(String args[ ])

In the main() method, args[ ] is a one-dimensional array of string type. It can store a group of strings, passed to the main() method from the outside by the programmer.

The programmer should pass these arguments from the outside at the time of executing the program at the command prompt.

We can use these command line arguments or values as input in the Java program. Let’s understand it with the help of an example.

Simple Example of Command-line argument in Java


When we run a Java program from the command prompt, we can input values that get passed to the main() method as strings.

For example, suppose that we entered the following command to run CommandLine program from the command prompt, as:

C:\> java CommandLine hello 10 world

This command has three command-line arguments beyond the java CommandLine command: hello, 10, and world.

These three arguments are automatically passed into the main() method and stored in the args parameters (args[ ]) in the form strings.

This is because args[ ] is a one dimensional string type array. It can store as many command-line arguments as we enter.

To access these arguments inside main() method, we will need to use args with a subscript in square brackets. For example, args[0] is the first argument, args[1] is the second argument, args[3] is the third argument and so on.
[adinserter block=”5″]
In the current example, hello is stored as a string in args[0], 10 is stored as a string in args[1], and world is stored as a string in args[2]. See the below figure.

Java command line arguments example

How does Command Line Arguments work in Java?


The command line arguments works as follows:

1. When we will run CommandLine Java program, the operating system passes the list of arguments to the JVM.

2. Sometimes, the operating system modifies arguments list by interpreting their meanings and may pass a modified list of arguments to the JVM.

3. The JVM parses a list of arguments using a space as a separator.

4. It creates a string array whose length is the same as the number of argument values in the list.

5. It populates an array of string with elements in the arguments list sequentially.

6. Finally, JVM passes an array of string to the main() method of the CommandLine class that we are running.

7. If we do not provide command line argument, JVM creates a string array of length zero and passes it to the main() method.

8. We can also pass space-separated words as one argument. For it, we will need to enclose them in double quotes. We can also avoid the operating system interpretation of special characters by enclosing them in double quotes.

Command line arguments Example Programs


Let’s write a very simple Java program to demonstrate a command line argument in Java. In this example program, we will receive only one argument value and print it.
[adinserter block=”2″]
To run this java program, we must have to pass at least one argument value from the command prompt.

Program code 1:

public class CommandLine {
public static void main(String[] args) 
{
 System.out.println("First argument is: "+args[0]); 
 System.out.println("Second argument is: "+args[1]);
 System.out.println("Third argument is: "+args[2]);
  }
}

 

Let us try to run this Java program through the command prompt.

Steps to run the above Java program

To compile and run java program from the command prompt, follow the all the below steps:

1. Save the program as CommandLine.java in the system.

2. Open the command prompt window and write the following command in the command prompt to compile the program:

javac CommandLine.java

3. After a successful compilation of the program, write the following command in the command prompt to run the program:

java CommandLine

4. Now suppose we want to pass three argument values while running the program. So, we can pass the argument values after the class name. For example,

java CommandLine hello 10 world

Here, hello, 10, and world are argument values passed to the program through the command line. Now, we will get the following desired output of this program.

Output:
    First argument is: hello
    Second argument is: 10
    Third argument is: world

In the above program, the main() method contains an array of strings named args[ ] as a parameter. This array of string stores all the arguments passed via the command line.


Note: Argument values are always stored as strings and always separated by white-space after the name of class.

How to print all values through command line arguments?


Let’s take an example program in which we will print all the arguments passed through the command line. For this purpose, we have used for loop for traversing the array.

Program code 2:

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

When we will execute the above program, the following output may generate at the command prompt:

C:\> javac CommandLine.java
C:\> java CommandLine This is an example program for command line arguments.
Output:
      Command line arguments are:
      args[0]: This 
      args[1]: is 
      args[3]: an 
      args[4]: example 
      args[5]: program 
      args[6]: for 
      args[7]: command 
      args[8]: line 
      args[9]: arguments.

How to pass numeric command line arguments in Java?


In a Java program, the main() method only takes data of type string. Therefore, we can never pass numeric arguments (i.e. values) via the command line.

If we pass these numeric arguments to main(), they are converted into string and we can’t use them as numbers. So, we can’t perform any numeric operations with them.

But, we can convert these string argument values into numeric values with the help of parseInt() method of Integer class. Let’s take an example to understand it more clearly.

Program code 3:

public class NumericArguments {
public static void main(String[] args) 
{
 for(String str: args)
 {
// Converting string arguments into integer type.
   int argument = Integer.parseInt(str);
   System.out.println("Arguments in integer form are: " +argument);
 }
  }
}

Let us try to run this program through the command line.

// compile the code
   javac NumericArguments.java

// run the code
   java NumericArguments 20 45

In this command, 20 and 45 are command-line arguments. Now, the program may produce the following output.

Output:
     Arguments in integer form are: 20
     Arguments in integer form are: 45

In the above example, we have used the parseInt() method of the Integer class to convert the string argument into an integer.

Similarly, we can use Double class’s parseDouble() and Float class’s parseFloat() methods to convert the string into double and float, respectively.


Note: If the passing arguments cannot be converted into a specific numeric value, then an exception named NumberFormatException occurs.

How to pass Command line arguments in Eclipse IDE


Using Run configurations, we can also pass command-line arguments to the main() method in Eclipse IDE. For this, just follow the all steps below:

Step 1: Write your Java program in Eclipse IDE.

Step 2: On the editor, right-click and go to “Run As” option. Inside it, choose the “Run Configurations…” option.

Step 3: When you will choose Run Configurations…, a pop-up window will open on the screen.

In the pop-up window, click on the Arguments tab. Now you enter your the command line argument values in the “Program arguments:” text box.

Step 4: After entering the values, click on the Run button. As you will click on the Run button, you will get the output on the console in Eclipse IDE.

Let’s take an example program in which we will calculate the factorial of a number in Eclipse IDE. We will pass the command line arguments to the main() method in Eclipse IDE.

Program code 5:

public class Factorial {
public static void main(String[] args) 
{
  int i, fact = 1;
  int number = Integer.parseInt(args[0]);
  for(i = 1; i <= number ; i++)
  {
    fact = fact * i;
  }
  System.out.println("The factorial of " + number + " is " +fact);
  }
}

To run this program, right click on the eclipse editor and go to Run As option. After that, select Run Configurations… Now click on the Arguments tab and write 4 in the Program arguments text box.

When you will click on Run button, you will get the following output.

Output:
      The factorial of 4 is 24

In this tutorial, you have learned command line arguments in Java with the help of some useful examples. Hope that you will have understood the basic concepts of command-line arguments and practiced all programs.

In the next tutorial, we will learn about recursion in Java with the help of examples.
Thanks for reading!!!

⇐ Prev Next ⇒