Java Programming – In this java tutorial, you will understand how to pass command line arguments in java with step by step examples.
COMMAND LINE INPUTS
- Providing necessary input values (arguments) to the main() method at the time of program execution
- We can pass input arguments to main() method either manual (e.g. dos command window) or automatic(e.g. IDE)
- By default, all the command line parameters are string array.
- An array index starts from 0 to n-1.
- Java provides two approaches for handling CMD arguments. They are
- Using Manual Approach (via CMD)
- Using Automated Approach (via IDE)
I. MANUAL APPROACH
- In the manual approach, the java interpreter takes only one argument.
- The argument is a string as a line of text. By default, this inputs are converted as string array (string[] arr)
I. EXAMPLE OF COMMAND LINE ARGUMENTS (CMD)
(using Notepad-Manual Way)
1. SOURCE CODE
(JTest.java)
public class JTest
{
// main() method definition
public static void main(String[] arr)throws Exception
{
// checking CMD inputs using the built-in length property of array
if(arr.length!=0)
{
System.out.println(“City Names”);
System.out.println(“City 1: “+arr[0]);
System.out.println(“City 2: “+arr[1]);
}
else
{
System.out.println(“No Arguments\nPlease provide the input Arguments”);
}
}
}
2. OUTPUT
2.1 SUCCESS CASE (IF ARGUMENTS ARE GIVEN)
2.2 FAILURE CASE (IF NO ARGUMENTS ARE GIVEN)
II. AUTOMATIC APPROACH (VIA IDE)
- In the automatic approach, the user has to specify the command line inputs to the “program arguments” section of the current project folder in netbeans IDE.
II. EXAMPLE OF COMMAND LINE INPUTS
(using Netbeans IDE)
1. SOURCE CODE
(JCommandLine.java)
public class JCommandLine
{
// main() method definition
public static void main(String[] args)
{
System.out.println(“—————————-“);
System.out.println(“\tCommand Line Arguments”);
System.out.println(“—————————-“);
// checking CMD inputs using the built-in length property of array
if(args.length!=0)
{
System.out.println(“City Names”);
for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}
else
{
System.out.println(“No Arguments\nPlease provide the input Arguments”);
}
}
}
2. PROJECT CONFIGURATION FOR CMD INPUTS
STEP 1: Select “Properties” by right-clicking on current project folder
STEP 2: Select “Run” from Left Menu and provide input arguments (separated by space) to Arguments Text Box on Right side
3. OUTPUT
3.1 SUCCESS CASE (IF ARGUMENTS ARE GIVEN)
3.2 FAILURE CASE (IF NO ARGUMENTS ARE GIVEN)
MORE TUTORIALS