What is Command Line Arguments? Example of Command Line Arguments. Discuss about Command Line Arguments with example
Command Line Arguments:-
There may be occasions when we may like our program to act in a particular way depending on the input provided at the time of execution. This is achieved in Java programs by using what are known as command line arguments. Command line arguments arc parameters that are supplied to the application program at the time of invoking it for execution)It may be recalled that Program 3.4 was invoked for execution at the command line as follows:
java Test
Here, we have not supplied any command line arguments. Even if we supply arguments, the program does not know what to do with them.
We can write Java programs that can receive and use the arguments provided in the
command line. Recall the signature of the main() method used in our earlier example programs:
command line. Recall the signature of the main() method used in our earlier example programs:
(public static void main (String args [ ] )
As pointed out earlier, args is declared as an array of strings (known as string objects) Any arguments provided in the command line (at the time of execution) are passed to the array args as its elements. We can simply access the array elements and use them in the program as we wish. For example, consider the command line
java Test BASIC FORTRAN C++ Java
This command line contains four arguments. These are assigned to the array args as follows:
BASIC args [0]
FORTRAN args [1]
C++ args [2]
Java args [3]
The individual elements of an array are accessed by using an index or subscript like args [ 1] The value of i denotes the position of the elements inside the array. For example, args [2 ] denotes the third element and represents C+ +. Note that Java subscripts begin with 0 and not 1
Example of Command Line Arguments :-
/*
* This program uses command line
* arguments as input
*/
Class ComLineTest
{
public static void main (String args [ ])
{
int count, i=0;
String String;
count = args.length;
System.out.println("Number of arguments = " + count);
while (i<count)
{
string = args [i];
i = i + 1;
System.out.println("i+ ":" + " java is" +string+ "!");
}
}
}
/*
* This program uses command line
* arguments as input
*/
Class ComLineTest
{
public static void main (String args [ ])
{
int count, i=0;
String String;
count = args.length;
System.out.println("Number of arguments = " + count);
while (i<count)
{
string = args [i];
i = i + 1;
System.out.println("i+ ":" + " java is" +string+ "!");
}
}
}
Program 3.4 Another simple program for testing
class Test
{
public static void main (String args [ ])
{
system.out.println("Hello");
system.out.println("Welcome to the world of programming101");
system.out.println("Let us learn Programmers and Theory");
}
}
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment