- In Java, when you launch an application, you can pass command-line arguments to the application’s main method through an array of Strings.
public static void main( String[] args )
- Each element in the array is one command-line argument.
Steps to pass command line arguments to the application.
Write your Java program
public class DisplayArguments { public static void main(String[] args) { if(args.length == 0) System.out.println("Pls enter arguments"); for(int i=0; i<args.length; i++) System.out.println("args[" + i + "]: " + args[i]); } }
Compile your Java program
Open Command prompt and type
javac DisplayArguments.java
If there are no errors then you can run your program.
Run your Java program
In the command prompt, type
java DisplayArguments Hello, How are you? 1 2 3
args[0]: Hello,
args[1]: How
args[2]: are
args[3]: you?
args[4]: 1
args[5]: 2
args[6]: 3
The arguments are separated by spaces.
In case, if you want Hello, How are you? to be interpreted as a single argument, then you should enclose them within quotation marks (“”).
java DisplayArguments “Hello, How are you?” 1 2 3
The arguments are stored in the String array named as args, which is the parameter of the main method.