JRJC - Getting information from the command line

When you want to activate a Java application, you go to the command line and type
    java RunSpotRun
Sometimes, you need to give a little extra information or the program has nothing to do. So at the command line you type
    java SpotRunTo Canada
This page covers how to get that information from the command line and into your program.

All Java applications contain, at a minimum, the following code:

public class
{

    public static void main( String[] args )
    {

    }

}
Technical gibberish: An application must be a public class which contains a public static method called "main" (case is very important). "main" returns "void" which means that it returns nothing.

The important thing for now is that main has one parameter: "String[] args" (it doesn't have to be called "args" although almost everyone always does and you should stick to this standard). This means that the sole parameter is an array of strings (String[]) called "args".

Now let's turn it into something with purpose and will compile.

public class SpotRunTo
{

    public static void main( String[] args )
    {
        System.out.println( "Spot is now in " + args[0] );
    }

}
I added "SpotRunTo" to the first line. This gives my class a name so that Java can tell which program I want to run. I also added a line that will print Spot's current status. "Spot is now in " is a string constant. The "+" performs a string concatenation. "args[0]" gets the first string in "args".

Copy this little program to SpotRunTo.java and compile it (javac SpotRunTo.java). Run it (java SpotRunTo Canada).

Since "args" is nothing more than a plain old array, you can do all sorts of things.



Modify the SpotRunTo program to see how many parameters were passed. Replace

        System.out.println( "Spot is now in " + args[0] );
with
        if ( args.length == 0 )
        {
            System.out.println( "Spot is now home" );
        }
        else
        {
            System.out.println( "Spot is now in " + args[0] );
        }
Compile it.

Now run the program like this

    java SpotRunTo Canada
And now run the program like this
    java SpotRunTo
Notice the difference?

For more information on the args parameter, look in Just Java 1.2 page 70, or Just Java 2 (sixth edition) page 96.




© 2000 Paul Wheaton