The Main Method in a Java Program

By Barry Burd

The figure has a copy of the code from the listing. The bulk of the code contains the declaration of a method named main. (Just look for the word main in the code’s method header.) For now, don’t worry about the other words in the method header — public, static, void, String, and args.

image0.jpg

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

How to make biscuits:
    Heat the oven.
    Roll the dough.
    Bake the rolled dough.

or

How to follow the main instructions for a Displayer:
    Print "You’ll love Java!" 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 is called into action automatically when the program begins running.

So look back at the figure. When the Displayer program runs, the computer automatically finds the program’s main method and executes any instructions inside the method’s body. In the Displayer program, the main method’s body has only one instruction. That instruction tells the computer to print You’ll love Java! on the screen. So in the figure, You’ll love Java! appears on the computer screen.

The instructions in a method aren’t executed until the method is called into action. But, if you give a method the name main, that method is called into action automatically.

Almost every computer programming language has something akin to Java’s methods. If you’ve worked with other languages, you may remember things like subprograms, procedures, functions, subroutines, subprocedures, or PERFORM statements. Whatever you call it in your favorite programming language, a method is a bunch of instructions collected and given a new name.