Command Line Arguments in Java


A command-line argument is nothing but the information that we pass after typing the name of the Java program during the program execution. The command requires no arguments. The code illustrates that args length gives us the number of command line arguments. If we neglected to check args length, the command would crash if the user ran it with too few command-line arguments.

A command-line argument is information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy. They are stored as strings in the String array passed to main ( ).

This is a Java program that uses command line arguments to print the values entered by the user.

  • The import java.lang.*; line is not necessary as the java.lang package is automatically imported.
  • The class command declares a class named command.
  • The public static void main(String args[]) method is the entry point of the program. It takes an array of strings named args as an argument.
  • The for loop iterates through the elements of the args array using args.length to determine the number of elements in the array.
  • The System.out.println(args[i]); statement prints each element of the args array to the console.

Source Code

//02 Command Line Arguments in Java
import java.lang.*;
 
class command
{
	public static void main(String args[])
	{
		for(int i=0;i<args.length;i++)
		{
			System.out.println(args[i]);
		}
	}
}

Output

ram
sam
ravi
To download raw file Click Here

Basic Programs