codescracker


java

Java Command Line Arguments



« Previous Tutorial Next Tutorial »


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

A command-line argument is the information that directly follows the program's name on the command line when it is executed. It's rather easy to access the command-line arguments inside a Java program, they are stored as strings in the String array that passed to the args parameter of the main(). The first command-line argument is stored at the args[0], the second at the args[1], and so on. For instance, consider the following example program that displays all of the command-line arguments it is called with :

Java Command Line Arguments Example

Here is an example on command line arguments in Java:

/* Java Program Example - Java Command-Line Arguments
* This program displays all command-line arguments */

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

Now try executing the above program, as shown below:

java CommandLine this is a test 200 -2

When you do this, you will watch the following output:

args[0] : this
args[1] : is
args[2] : a
args[3] : test
args[4] : 200
args[5] : -2

Note - All the command-line arguments are passed as strings. You must convert the numeric values to their internal forms manually.


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test