Command line arguments in Java

Java 8Object Oriented ProgrammingProgramming

Sometimes you will want to pass some information on a program when you run it. This is accomplished by passing command-line arguments to main( ).

A command-line argument is an information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy. They are stored as strings in the String array passed to main( ).

Example

The following program displays all of the command-line arguments that it is called with -

public class CommandLine {
   public static void main(String args[]) {
      for(int i = 0; i<args.length; i++) {
         System.out.println("args[" + i + "]: " + args[i]);
      }
   }
}

Try executing this program as shown here -

$java CommandLine this is a command line 200 -100

Output

This will produce the following result -

args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
raja
Published on 07-Feb-2018 10:25:10
Advertisements