Previous | Next | Trail Map | Writing Java Programs | The Nuts and Bolts of the Java Language


The main() Method

class Count {
    public static void main(String args[])
        throws java.io.IOException
    {
        int count = 0;

        while (System.in.read() != -1)
            count++;
        System.out.println("Input has " + count + " chars.");
    }
}    
In the Java language, when you execute a class with the Java interpreter, the runtime system starts by calling the class's main() method. The main() method then calls all the other methods required to run your application.

The main() Method in The Anatomy of a Java Application provides a more thorough discussion about the main() method.

Accepting a Filename on the Command Line

The main() method accepts a single parameter: an array of Strings. This parameter is the mechanism through which the runtime system passes command line arguments to your application. Currently, the character-counting application ignores its command line arguments. Let's modify the program to accept a command line argument and have it count the characters in the file specified on the command line. Compare this version of the character-counting program with the original version listed above.
import java.io.*;

class CountFile {
    public static void main(String args[])
	throws java.io.IOException, java.io.FileNotFoundException
    {
        int count = 0;
	InputStream is;

        if (args.length == 1)
	    is = new FileInputStream(args[0]);
	else
	    is = System.in;
	
        while (is.read() != -1)
            count++;

	if (args.length == 1)
	    System.out.println(args[0] + " has "+ count + " chars.");
	else
	    System.out.println("Input has " + count + " chars.");
    }
}
In this implementation of the character-counting program, if the user specifies a name on the command line then the application counts the characters in the file. Otherwise, the application acts as it did before and reads from the standard input stream. Now, run the new version of the program on this text file and specify the name of the file ("testing") on the command line.

For more information about command line arguments refer to the Command Line Arguments lesson.


Previous | Next | Trail Map | Writing Java Programs | The Nuts and Bolts of the Java Language