What are the command line arguments in Java?
How to access java command line arguments?
The method of accessing the command line arguments in java is very straightforward. To use these arguments within our java code is simple. They are stored as an array of Strings passed to the main(). It is mostly named as args. Have a look at the common header in the snippet below.
public static void main(String[] args){…}
Example
Let’s look at an example explained in detail below.
// Program to check for command line arguments
public class Example {
public static void main(String[] args) {
// check if the length of args array is < 0
if (args.length <= 0) {
System.out.println("No command line arguments found.");
} else {
System.out.println("The first command line argument is: " + args[0]);
System.out.println("All of the command line arguments are: ");
// iterating the args array and printing all of the command line arguments
for (String index : args)
System.out.println(index);
}
}
}
Execution
To execute the program, pass the arguments on the command line in the following way. We’re using IntelliJ IDE here, you can use any of your choice. For IntelliJ, choose the option, “Run” → “Edit Configurations”. Next, go to the “Program arguments” tab that is second on the available tabs. You can enter your arguments in that block available, click “Ok” and then “Run”. For the same output as this program, use the text below.My name is Andrew.
Output
The first command line argument is: My
All of the command line arguments are:
My
name
is
Andrew.
GO TO FULL VERSION