The Main Method in a Standard Java Program - dummies

By Barry Burd

When you run the small Java program in this listing, the computer displays the word Hello in a dialog box. The figure shows a copy of the code from the listing with arrows indicating what happens when the computer runs the code. The bulk of the code contains the declaration of a method named main.


package org.allyourcode.myfirstproject;
public class MyFirstJavaClass {
   * @param args
  public static void main(String[] args) {
                                   (null, "Hello");

Like any Java method, the main method is a recipe:

How to make scrambled eggs:
  Combine eggs and milk
  Whisk until smooth
  Pour into preheated frying pan
  Cook for 2 to 3 minutes while stirring the mixture
  Add salt, pepper, and garlic powder
  Add cheese a little at a time
  Cook for another 2 to 3 minutes
How to follow the main instructions for MyFirstJavaClass:
    Display "Hello" in a dialog box on the screen.

The word main plays a special role in Java. In particular, you never write code that explicitly calls a main method into action. The word main is the name of the method that’s called into action when the program begins running.

When the MyFirstJavaClass program runs, the computer automatically finds the program’s main method and executes any instructions inside the method’s body. In the MyFirstJavaClass program, the main method’s body has only one instruction. That instruction tells the computer to display Hello in a dialog box on the screen.

None of the instructions in a method is executed until the method is called into action. But if you give a method the name main, that method is called into action automatically.