Command line arguments in java is very important concept in any programming language.
In this tutorial we will see what is command line augments, how to pass command line arguments in java, command line arguments in java example and program to pass command line argument.
What is command line arguments?
The arguments that are pass on to main() at the command prompt are called as command line arguments.
These are the parameters that are supplied to application program at the time of invoking for execution.
That is passing the argument which executing the program.
We write the java program which uses the arguments that are provided by command line at the time of execution.
The signature of main in java programming is,
public static void main(String args[])
which is used to accept the arguments that are passes by command line.
The argument args[] which is declared as array of string accepts theses arguments.
This array of string (args[]) stores the number of arguments from command line.
that is whenever we pass argument it will stored in args[] array.
How to pass command line arguments in java ?
To pass arguments from command line while executing program we simply write arguments that we want to pass to program.
Syntax to pass command line arguments
java filename argument_1, argument_2 …. argument_N
Command line arguments example in java
Consider following statement passing arguments to Test.java program from command line.
java Test C C++ JAVA COBOL
In above example we are passing 4 arguments which are C C++ JAVA and COBOL..
When this statement executed (when we run) theses arguments are assigned to the array args[] as follows
args[0] = C
args[1] = C++
args[2] = JAVA
args[3] = COBOL
(Note : array index starts with Zero )
After assigning arguments program is executed as we used these arguments in program.
Command line arguments in java program
1 2 3 4 5 6 7 8 9 10 11 12 |
public class Test { public static void main (String[]args) { int i; for (i = 0; i < args.length; i++) System.out.println (args[i]); } } |
Run the program from command prompt.
While running the code pass some arguments.
java Test C C++
Output :

Explanation
1. Passing the arguments from command prompt
java Test C Cpp Java
we passed three arguments while running program.
2. After passing arguments it go to main method
and arguments of main that is args[] stores the command line arguments that we have passed.
args[0]=C
args[1]=Cpp
args[2]=Java
3. We print arguments using for loop
for (i = 0; i < args.length; i++) =>args.length finds length of arguments so args=3
At iteration 1
i=0 , 0<3 condition true
System.out.println (args[i]); => C
At iteration 2
i=1 , 1<3 condition true
System.out.println (args[i]); => Cpp
At iteration 3
i=2 , 2<3 condition true
System.out.println (args[i]); => Java
At iteration 4
i=3 , 3<3 condition false
4. End with the program.
Leave a Reply