The command-line argument is an argument passed at the time of running the java program.
The argument can be received in the program and used as an input. So, it provides an convenient way to check out the behaviour of the program on different values. You can pass any numbers of arguments fromthe command prompt.
Example of command-line argument:
In this example,we are receiving only one argument and dispalying it. For running this program, you must pass at least one argument from the command prompt.
class Test{
public static void main(String []args){
System.out.println("first argument is: "+args[0]);
}
}
To compile by : javac Test.java
To run : java Test roop
Output: roop
Example of command-line arguments that prints all the values:
In below example,we are printing all the arguments passed from the command-line.For this purpose,we have traversed the array (args) of main method using for loop.
class Test{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}
}
To compile : javac Test.java
To run: java Test my name roop and age is 25 and
Output: my
name
roop
and
age
is
25
and
No comments:
Post a Comment