Command Line Arguments:
Command Line Arguments are those arguments which are passed during executing a program through console.
Arguments passed from console can be used in a java program and can be taken as an input.
Example:
public class CommandLineArguments
{
public static void main(String args[])
{
/*args[0] gets the first value we passed as command line argument
* and displaying that value
*/
System.out.println(args[0]);
/*args[1] gets the second value we passed as command line argument
* and displaying that value
*/
System.out.println(args[1]);
}
}
- compile it > javac
CommandLineArguments
.java
- run by > java
CommandLineArguments
Hello Hey
Output: Hello
Hey
In the above example we have passed two command line arguments 'Hello' and 'Hey'.
We can pass any number of command line arguments and these elements can be accessed as “args[0]” , “args[1]” , “args[2]” etc or we can traverse the array using for loop.
for(int i=0;i<args.length;i++)
System.out.println(args[i]); //traversing the whole array
}
0 Comment(s)