Introduction
In this article we discuss command line arguments in Java.
What is command line argument
An argument passed when a Java program is run is called a command line argument. The arguments can be used as input. So, it provides a convenient way to check out the behavior of the program on various values. We can pass any number of arguments from the command prompt or nearly anywhere a Java program is executed. This allows the user to specify configuration information when the application is launched.
Advantages
- We can provide any number of arguments using a command line argument.
- Information is passed as Strings. So we can convert it to numeric or another format easily.
- While launching our application it is useful for configuration information.
1. Example
In this example, we are printing the first command line argument as in the following.
CommandLineEx.java
class CommandLineEx
{
public static void main(String x[])
{
System.out.println("First Command line Argument is: "+x[0]);
}
}
Output
2. Example
In this example, we are printing or showing all the command-line arguments using a for loop.
CommandLineEx1.java
class CommandLineEx1
{
public static void main(String x[])
{
for(int a=0;a<x.length;a++)
System.out.println(x[a]);
}
}
Output
3. Example
In this example; we show a program that supports only numeric command-line arguments, using parse int to convert a string value to a number (like "1234" string as a number 1234).
CommandLineEx2.java
class CommandLineEx2
{
public static void main(String x[])
{
int argFirst;
if (x.length>0)
{
try
{
argFirst = Integer.parseInt(x[0]);
System.out.println(x[0]);
}
catch (NumberFormatException nfe)
{
System.err.println("Given argument" + " should be an integer");
}
}
}
}
Output
This program throws a NuberFormatException if the format of x[0] is not valid as in the following.
When we provide an integer value it works fine as in the following.