English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn about Java command line arguments with the help of examples.
In JavaCommand Line ArgumentsAllowing us to pass parameters during program execution.
As the name suggests, parameters are passed via the command line.
class Main { public static void main(String[] args) { System.out.println("Command line arguments are"); //Traverse all arguments for(String str: args) { System.out.println(str); } } }
Let's try to run the program using the command line.
1.Compile the code
javac Main.java
2.Run the code
java Main
Now, suppose we want to pass some arguments when running the program. We can pass arguments after the class name. For example,
java Main apple ball cat
Here, apple, ball, and cat are the arguments passed to the program via the command line. Now, we will get the following output.
Command Line Arguments are Apple Ball Cat
In the above program, the main() method includes a string array named args as a parameter.
public static void main(String[] args) {...}
A String array stores all the arguments passed via the command line.
NoteParameters are always stored as strings and always enclosed bySpaceSeparated by
Each Java program's main() method only accepts string arguments. Therefore, it is impossible to pass numeric arguments via the command line.
However, later we can convert string arguments to numeric values.
class Main { public static void main(String[] args) { for(String str: args) { //Convert to integer type int argument = Integer.parseInt(str); System.out.println("Integer argument: " + argument); } } }
Let's try to run the program through the command line.
//Compile the code javac Main.java //Run the code java Main 11 23
here11and23are command line arguments. Now, we will get the following output.
Arguments in integer form 11 23
In the above example, please note the following line
int argument = Integer.parseInt(str);
Here, the parseInt() method of the Integer class converts the string argument to an integer.
Similarly, we can use the parseDouble() and parseFloat() methods to convert strings to double and float, respectively.
NoteA NumberFormatException is thrown if the argument cannot be converted to the specified numeric value.