Experiments in Java


Notes for Session J1: An Introduction to Java

The main method. You may recall that a class's main method is declared as

  public static void main(String[] args)

What does everything mean?

The ``main'' names the method. Every Java application needs a main method. When you execute a Java application, the Java interpreter knows to start with main.

The main method must be public, which means that the method can be called by other classes and other objects. Arguably, something else (the Java interpreter) is calling this class, so it must be public.

The main method must be static, which means that it is associated with the class as a whole and not just with individual objects. In general, Java methods are associated with objects, and can only be used if you've created a corresponding object. Since we don't always want to create objects for our applications, main is static.

The main method has type void, which means that the method does not return a value. Many methods are like mathematical functions. For example, we might say that a square-root function (method) returns a number, and a ``make up a nonsense word'' method returns a word. Because our program will not ``return'' values (simply interact with the user), it needs this void.

The terms in parentheses are the parameters to the method. Many methods have parameters. For example, a square-root function would take a number as a parameter, and a ``translate to Pig Latin'' function might take a word as a parameter. The args gives us a name for the parameter. The String[] says that this parameter is a list of words (``Strings'' in Java parlance).

Where do these strings come from? Java, at least in part, comes from an environment (Unix) in which programs are typically invoked from a command line (as in DOS). In addition to specifying the name of the program, you can add information that helps the program work. For example, the Unix ``print'' command accepts files to print as parameters and can also accept information on which printer to use. The designers of Java knew that many programmers would need similar capabilities. You won't need those capabilities in your early programs, but you might need them later.

Aren't you sorry you didn't wait?

Experiment J1.1, Step 4. In some cases, the Java interpreter is smart enough to find related classes, even without an explicit import statement. However, good practice dictates that you use such statements.


Copyright (c) 1998 Samuel A. Rebelsky. All rights reserved.

Source text last modified Wed Oct 6 12:32:56 1999.

This page generated on Wed Oct 6 12:33:24 1999 by Siteweaver.

Contact our webmaster at rebelsky@math.grin.edu