When we create a Java application we might want to pass a couple of parameters to our program. To get the parameters passed from the command line we can read it from the main(String[] args)
method arguments.
To make a class executable we need to create a main()
method with the following signatures:
public static void main(String[] args) {
}
This method takes an array of String
as the parameter. This array is the parameters that we pass to the program in the command line.
package org.kodejava.basic;
public class ArgumentParsingExample {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i + 1) + " = " +
args[i]);
}
// If you want to check if the number of supplied parameters
// meet the program requirement you can check the size of
// the arguments array.
if (args.length < 3) {
System.out.println(
"You must call the program as follow:");
System.out.println(
"java org.kodejava.example.basic.ArgumentParsingExample arg1 arg2 arg3");
// Exit from the program with an error status, for
// instance we return -1 to indicate that this program
// exit abnormally
System.exit(-1);
}
System.out.println("Hello, Welcome!");
}
}
When we try to run the program without argument we will see the following message:
$ java org.kodejava.basic.ArgumentParsingExample
You must call the program as follow:
java org.kodejava.basic.ArgumentParsingExample arg1 arg2 arg3
And when we pass three arguments we get something like:
$ java org.kodejava.basic.ArgumentParsingExample param1 param2 param3
Argument 1 = param1
Argument 2 = param2
Argument 3 = param3
Hello, Welcome!
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024