Java command line argument
Command line arguments
Command line arguments are the optional argument that supplied by the user or programmer at run time. In java command line arguments are handled by the main() function. It is an Array of string so that you can pass argument in the form of String only.
Java command line argument Example
class JavaCommandLine{ public static void main(String args[]){ System.out.println("First String Argument is: "+args[0]); } }
Compile by > javac CommandLineExample.java
Run by > java JavaCommandLine pTutorial
First String Argument is: pTutorial
Java command line argument example to add n numbers
class CommandLineExample{ public static void main(String s[]){ int sum=0; for(int i=0;i<s.length;i++) { int k=Integer.parseInt(s[i]); sum=sum+k; } System.out.println(sum); } }
Compile by > javac CommandLineExample.java
Run by > java CommandLineExample 10 15
25
Output
You can add any numbers at run time by using this example. The parseInt method of Integer class is used to convert string argument into the Integer argument.
Some points about Command line argument.
- It’s not mandatary to keep the name of argument is "args" you can keep any name.
- The given argument is always in the form of String.