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


The main() Method

As you learned in The main() Method(in the Getting Started trail) in The "Hello World" Application the runtime system executes a Java program by calling the application's main() method. The main() method then calls all the other methods required to run your application.

The main() method in the character-counting example initializes the count variable, then stops at System.in.read() and waits for the user to type characters. When the user finishes typing, the program displays the number of characters typed.

Accepting a Filename on the Command Line

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;
        String filename;

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

        System.out.println(filename + " 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 information about command line arguments refer to the Setting Program Attributes(in the Writing Java Programs trail) lesson.


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