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.

Comments

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.