In Java, command-line arguments are pieces of data that can be passed to a Java program when it is executed from the command line. These arguments are passed as an array of strings to the main
method of the program, which is the entry point of the program.
Here is an example of how to access command-line arguments in a Java program:
public class Main { public static void main(String[] args) { // Print the first command-line argument System.out.println(args[0]); // Print the second command-line argument System.out.println(args[1]); // Print all command-line arguments for (String arg : args) { System.out.println(arg); } } }Source:www.lautturi.com
To pass command-line arguments to a Java program, you can specify them after the name of the program when you execute it from the command line. For example:
java Main arg1 arg2 arg3
In this example, the args
array in the main
method will contain the following elements:
args[0] = "arg1" args[1] = "arg2" args[2] = "arg3"
You can use command-line arguments to pass input data to your Java program or to control its behavior.