Thursday 23 May 2013

COMMAND LINE ARGUMENTS IN JAVA

In java you can enter any number of command line arguments during the execution of the java program. 

Remember that when you want to run a java program you use the javac command on the command prompt, this command actually compiles your java program, it does not executes it. To execute the command you use the command java followed by the class name that contains your main function. Many of us have a doubt that the file name should be same as that of the class name that contains the main function, but it is not necessary. 

For example you can have a java file with name student.java, at the same time you could have the class name record. When on the command prompt you compile the file student.java using the command
>javac student.java
you will find that a file is created in the same location, this file is record.class
Now to execute this java program we use the following command :-
>java record

We give the command line arguments in the command for executing the file. The class name is followed by the arguments. 
For example 
>java record names.txt

Here is a program that illustrates the use of command line arguments.
By this program we can also have a good idea on how to use command line arguments in our java program.

Source code :-
/********************************************************************************/
public class command_line_arguments {

public static void main(String[] args) {
for(int i=0;i<args.length;i++)
{
System.out.println("args["+i+"] = "+args[i]);
}
System.out.println("WE ARE NOW OUT OF THE LOOP");
}

}
/******************************************************************************/





No comments:

Post a Comment