Complete Java Programs


The main method

A Java program contains a method called main that is run automatically when the program starts. The main method is similar to the Execute part of a Cinnameg program.

The heading for main is required to be as follows.

  public static void main(String[] args)
The argument args is an array of strings. We will encounter arrays a little later. For now, you can safely ignore args. Just be sure to write the heading exactly as shown.


The form of a program

To write a program, choose a name for the program. Let's say you have chosen to call the program Rabbit. Create a file called Rabbit.java. In that file, write the program in the following form. (We will discuss imports later.)

  put imports here

  public class Rabbit
  {
    public static void main(String[] args)
    {
      ... say what main does
    }

    ... any additional method definitions
  }
It is important that the name that you write in the program matches the name of the file. If you decide to call the program Lizard, then it must be in a file called Lizard.java. The case of letters matters. It will not work to put a program called Lizard in a file called lizard.java.

Java does not care how you order your method definitions. It allows a method to use other methods that are defined after it in the program.

For example, here is a complete java program that displays a table of factorials. It would be placed in a file called Factorial.java.

  public class Factorial
  {
    public static void main(String[] args)
    {
      long n = 1;
      while(n <= 10)
      {
        System.out.println(n + "! = " + factorial(n));
        n++;
      }
    }

    public static long factorial(long n)
    {
      if(n == 1) return 1;
      else return n * factorial(n-1);
    }
  }


Compiling and running a Java program

To compile and run a Java program called Rabbit.java directly (not using these web pages) on Linux, do the following steps.

  1. Compile the program using command

      javac Rabbit.java
    
    If there are errors, you will be told. If not the compiler will be silent, and will create a file called Rabbit.class that is the translated version of your program.

  2. After the program compiles successfully, run it using command

      java Rabbit
    
    Notice that you do not write Rabbit.java, just Rabbit.

If your program is called Frog, replace Rabbit by Frog.


Summary

A Java program starts with imports (if you need them) and then defines a class. Write the methods inside the class.

One of the methods is called main. It must have heading

  public static void main(String[] args)

Do not try to write one method inside another method. Write the methods side by side, inside the class.