Structure of a Java Program

Note: the parts of the examples I've put in italics are things you'll fill in, e.g. with your own class name, your own method definitions, your own instance-variable declarations. The parts I've put in typewriter font are Java keywords, and must be spelled exactly as I do.
  1. A Java program is a series of one or more class definitions.

  2. A class definition is a class header with some method and instance-variable declarations in between the curly braces.

  3. An instance variable declaration usually looks like
    private type variable-name ;
    and always appears inside the curly-braces of a class definition, but not inside any of its method definitions. For example,
    class Foo {
        private int x;
        ...
        }

    The words "public" or "protected" may be substituted for "private", but not unless you have a good reason to do so ("the program doesn't compile" does not count as a good reason in itself!) In most cases, if other classes really need to get at your instance variables, I recommend writing access methods instead of making the variables themselves public.

    Instance variables can be initialized, e.g.

    private int x=3;
    although I tend to favor initializing instance variables explicitly inside a constructor. You can also define several variables on the same line, e.g.
    private int x=3, y=7, z;

  4. A method definition is a method header with some statements and local-variable declarations in between the curly braces.

  5. A local variable declaration looks a lot like an instance variable declaration, but it doesn't have the words private, public, or protected, and it is always inside a method. It looks like
    type-name varname, varname, ... varname;
    Note that you can declare several local variables of the same type in one declaration, or one in each of several statements; it doesn't matter. Like instance variables, local variables can be initialized:
    type-name varname=value, varname=value;
  6. A parameter variable declaration looks a lot like a local variable declaration, but rather than being inside a method, it is inside the parentheses in a method header. Since a parameter variable declaration isn't a statement, it doesn't end with a semicolon. Unlike instance variable declarations and local variable declarations, each parameter variable must be immediately preceded by a type. And unlike instance variable declarations and local variable declarations, parameter variables cannot be initialized, since they are merely place-holders for values that will be provided when somebody uses the method.

    An example of a method header with several parameter variable declarations follows:

           public int myMethod (int thisOne, int thatOne, String theOtherOne)
           
    The following examples are incorrect and will produce syntax errors:

Last modified: Fri Jan 19 13:50:55 EST 2001
Stephen Bloch / sbloch@boethius.adelphi.edu