Java
Command-Line Arguments
The command-line arguments in Java allow us to
pass arguments during the execution of the program.
class
Cla {
public static void main(String[] args) {
System.out.println("Command-Line
arguments are");
// loop through all arguments
for(String str: args) {
System.out.println(str);
}
}
}
to
run this program using the command line.
1. To
compile the code
javac
Cla.java
2. To run
the code
java Cla
Now
suppose we want to pass some arguments while running the program, we can pass
the arguments after the class name. For example,
java Cla MY
NAME IS ABCD
arguments
passed to the program through the command line. Now, we will get the following
output.
Command-Line arguments are
MY
NAME
IS
ABCD
In the
above program, the main() method includes an array of
string named args as its parameter.
The String
array stores all the arguments passed
through the command line.
Passing Numeric Command-Line Arguments
The main() method of every Java
program only accepts string arguments. Hence it is not possible to pass numeric
arguments through the command line.
However,
we can later convert string arguments into numeric values.
Example: Numeric Command-Line Arguments
class Ncla {
public static void main(String[] args)
{
for(String str: args) {
// convert into integer type
int argument = Integer.parseInt(str);
System.out.println("Argument in
integer form: " + argument);
}
}
}
Let's try
to run the program through the command line.
// compile
the code
javac Ncla.java
// run the
code
java Ncla 12
34
Here 12 and 34 are command-line
arguments. Now, we will get the following output.
Arguments in integer form
12
34
In the
above example, notice the line
int argument
= Intege.parseInt(str);
Here,
the parseInt() method of the Integer class converts the string
argument into an integer.
Similarly,
we can use the parseDouble() and parseFloat() method to convert the
string into double and float respectively.