It is possible to write very large Java programs with all code inside a single main method. Most programmers prefer to break up their programs using methods (and classes, which are not discussed here). Methods offer advantages including:

Methods are also known as functions or procedures. These terms sometimes have different meanings, especially with respect to classes. At the introductory level, they are often used interchangeably. This website prefers the term method.

Program written entirely in main method

public static void main(String[] args)
{
    System.out.println("Daily schedule");
    
    System.out.println("Wake up");
    System.out.println("Make breakfast");
    
    System.out.println("Feed the baby");
    System.out.println("Burp the baby");
    System.out.println("Change the baby");
    
    System.out.println("Make lunch");
    
    System.out.println("Feed the baby");
    System.out.println("Burp the baby");
    System.out.println("Change the baby");
    
    System.out.println("Hope that the baby naps");
    
    System.out.println("Make dinner");
    
    System.out.println("Feed the baby");
    System.out.println("Burp the baby");
    System.out.println("Change the baby");
}

Note that the code to handle the baby is repeated.

Program written with careForBaby method

private static void careForBaby()
{
    System.out.println("Feed the baby");
    System.out.println("Burp the baby");
    System.out.println("Change the baby");
}

public static void main(String[] args)
{
    System.out.println("Daily schedule");
    
    System.out.println("Wake up");
    System.out.println("Make breakfast");
    
    careForBaby();
    
    System.out.println("Make lunch");
    
    careForBaby();
    
    System.out.println("Hope that the baby naps");
    
    System.out.println("Make dinner");
    
    careForBaby();
}

The code to care for the baby has been moved to the careForBaby method. The careForBaby method can be written and tested independently from the rest of the program. Each time the careForBaby method is called, the code inside is run.

The method had a header:

private static void careForBaby()

Within the main method, the code inside the careForBaby method is run by calling the method: careForBaby();

Within the main method, each time the careForBaby method is called, the code inside is executed before the main method continues.

Output of both programs

Daily schedule
Wake up
Make breakfast
Feed the baby
Burp the baby
Change the baby
Make lunch
Feed the baby
Burp the baby
Change the baby
Hope that the baby naps
Make dinner
Feed the baby
Burp the baby
Change the baby

Both programs produce the same output in the same order.

Methods with parameters

A Java method can accept parameters that can be used to affect how the method behaves when called. See Methods with parameters for details.

Comments

Comment on Writing and calling methods