Java Command Line Arguments
On the off chance that any information worth is gone through summon brief at the season of running of system is known as order line contention as a matter of course every charge line contention will be dealt with as string quality and those are put away in string cluster of principle() strategy.
Syntax for Compile and Run CMD programs
Compile By -> Javac Mainclass.java
Run By -> Java Mainclass value1 value2 value3 ....................
Run By -> Java Mainclass value1 value2 value3 ....................
Example of command-line argument in java
class CommandLineExample { public static void main(String args[]) { System.out.println("Argument is: "+args[0]); } }
Compile and Run above programs
Compile By > Javac CommandLineExample.java
Run By > Java CommandLineExample Porter
Run By > Java CommandLineExample Porter
Output
Argument is: Porter
Example of command-line argument in java
class SumDemo { public static void main(String args[]) { System.out.println("Sum: "+args[0]); } }
Compile and Run above programs
Compile By > Javac SumDemo.java
Run By > Java SumDemo 10 20
Run By > Java SumDemo 10 20
Output
Sum: 30
At the point when the above explanation is executing the accompanying arrangement of steps will happen.
- Class loader sub-framework loads SumDemo alongside Command line argument(10, 20) and in fundamental memory.
- JVM take the stacked class SumDemo alongside Command line contentions (10, 20) and spot the quantity of qualities in the length variable that is 2.
- JVM searches for primary() that is JVM will put the Command in the principle() through string class that is.
- Consequently all the CMD line contentions of java are sending to fundamental() technique accessible as exhibit of object of String class (each CMD are accessible or put away in primary strategy as cluster of object of String class).
- JVM calls the fundamental() strategy as for stacked class SumDemo that is SumDemo.main().
Accept command line arguments and display their values
class CMD { public static void main(String k[]) { System.out.println("no. of arguments ="+k.length); for(int i=0;i< k.length;i++) { System.out.println(k[i]); } } }
Note: Except + operator any numeric operation not allowed in command line arguments.
Square of Number by reading value from command prompt.
class squareDemo { int no, result; void square(String s) { int no=Integer.parseInt(s); result=no*no; System.out.println("Square: " +result); } } class CMD { public static void main(String args[]) { System.out.println("no of arguments: "+args.length); squareDemo obj=new squareDemo(); obj.square(args[0]); } }