Command Line Args

Command Line arguments

There may be occasions when we may like our program to act in a particular way depending on the type of input provided at the time of execution. This is achieved in java programs by using what are known as command line arguments. Command line arguments are the parameters that are supplied to the application program at the time of invoking it for execution.

For example

Java test

Here we have not supplied any type of command line arguments. Even if we supply arguments, the program does not know what to do with them.

Public static void main(String args [ ] )

Args is declared as an array of strings (known as string objects ) . Any arguments provided in the command line ( at the time of execution ) are passed to the array args as its elements. We can simple access the array and use them in prograph as we wish. For example consider the command line :

Java test BASIC FORTRAN C ++ JAVA

The command line contains four arguments . These are assignment to the array args as follows :

BASIC - args [0]

FOTRAN - args[1]

C ++ -  args [2]

JAVA  - args[3]

The individual elements of an array are accessed using an index or subscript like args[i]. the value of I denotes the position of elements inside the array.

For example : Use of Command Line arguments

Class comlinetest

{

Public static void main ( string args[ ] )

{

int count , i =0;

String string;

System.out.println( “ Number of arguments = “+ count );

While ( i < count )

{

String = args[i];

I = I + 1 ;

System.out.println( i+  “:” + “ Java is “ + string);

}

}

}

Compiling and running the above program

Java conlinetest simple object oriented distributed robust secure portable multithreaded dynamic

Upon execution, the command line arguments simple , object oriented etc are passed to the program through the array args . that is the element args[0] contains simple, args[1] contains object oriented and so on. These elements are accesed using the loop variable i .

Name = args[i]

The index i is incremented using while loop until all the arguments are accessed. The number of arguments is obtained by the statement

Count = args.length;

The output of the program would be as follows :

Number of arguments = 8

Java is simple

Java is object oriented

Java is distributed

Java is robust

Java is secure

Java is portable

Java is multithreaded

Java is dynamic

Leave Comment

Important Topics

Title
OOPS
Data Types
JAVA
JVM
Command Line Args
Machine Neutral
Scope of Variables
Operators :
Generic Type Casting
IF Else
Switch Statement
The while statement
The do statement
The for statement
Classes, objects and methods
Constructors
Methods Overloading
Static Members
Nesting of methods
Inheritance : Extending a Class
Overriding methods
Overriding methods
Final variable and methods
Abstract class in Java
Visibility control