Saturday, 19 November 2016

Command Line Arguments

  • You can pass information into a program when you run it. This is accomplished by passing command-line arguments to main( ).
  • command-line argument is the information that directly follows the program's name on the command line when it is executed. 
  • The command-line arguments are stored as strings in the String array passed to main( ). You have to use the index for accessing the argument which starts from 0 as given below program.
  • Here we pass two numbers using command line and add these two numbers into sum variable and display it. 
  • The Integer.parseInt(args[0]) uses parseInt( ) method of Integer wrapper class which converts string object to primitive integer type. Note that when you pass command line arguments they are collected in a string array.
  • The program source code is given below:


PROGRAM
class CmdLineArgDemo {

 public static void main(String[] args) {

  int no1 = Integer.parseInt(args[0]);
  int no2 = Integer.parseInt(args[1]);
  
  int sum = no1 + no2;
  System.out.println("Addition of two numbers is "+sum);
 }

}

The output of the code is given below:

OUTPUT
C:\>javac CmdLineArgDemo.java
C:\>java CmdLineArgDemo 10 21
Addition of two numbers is 31

Here 10 & 21 are called command line arguments which are passed to java interpreter while running the program.

No comments:

Post a Comment