5.1 Basics

Modular programming is useful for a number of reasons. Some of these reasons are:

Java has a number of features that allow us to introduce modularity. The most basic of these is the use of methods. The idea of a method is not new to us. Every program that we have seen contained the method called main. We have also seen many examples of programs that use other methods: our very first program used the method println and we have encountered many others since then: the methods of the class In for reading data, the methods of the class Math that we studied in Chapter 2, and the methods equals and compareTo of the class String. In this chapter, we are going to see how to create our own methods (other than main) as tools for solving our own problems.

To get started, suppose that we have been asked to handle the accounting for a local video rental store. The program's output will consist of a number of pages, each of which should have a heading of the form

Ahmed's Video Wonderland
  70 Roehampton Avenue
      555-1212

Rather than write all the statements that would be needed to print this at each of the required points in the program, it would be more efficient if we could simply give a single command to print a heading whenever it is needed. Since there is no predefined method in Java for performing this task, we must create one. The next example shows how to do so.

Example 1

The following code defines a method that can be used to print a heading at the top of a page. The escape sequence \f in the first println statement causes a "form feed" - a jump to the top of a new page.
public static void printHeading ()
{
   System.out.println("\fAhmed's Video Wonderland");
   System.out.println(" 70 Roehampton Avenue");
   System.out.println(" 555-1212");
} 

The method definition shown in Example 1 looks very much like that of a main method except that the word main has been replaced by the method's identifier, printHeading, and the parentheses that follow the method's identifier are empty.

Once we have defined a method, the simplest way to use it is to place its code in the same class as the program's main method. The definition of the new method can be placed either before or after the main method. If an application program contains a number of methods, then exactly one of them must be called main. When we run such a program, Java seeks out the main method and starts execution of the program at the beginning of this method. Although the main method can be placed anywhere, it is customary to place it either first or last.

When we use a method, we say that we call it or invoke it. If, for example, we have placed the definition of our printHeading method in a class along with a main method, then we could call printHeading from within main by writing the statement
      printHeading();
We must write the parentheses because that is the way that we tell Java that printHeading is a method, not a variable.

Example 2

The following program skeleton shows how the method printHeading might appear and be called in a program.
class Sample
{
   public static void printHeading ()
   {
      // method definition as shown in Example 1
      .
      .
   }
   public static void main (String[] args)
   {
      .
      .
      printHeading();
      .
      .
      printHeading();
      .
      .
      printHeading();
      .
      .
   }
}

Despite the fact that the definition of printHeading precedes that of main, execution of the program starts with the first statement in main. Whenever the statement printHeading(); is encountered, control passes to that method, its statements are executed, and then control passes back to the statement immediately following the call to the method.

Like the main method, methods that we write will, unless directed otherwise, execute their statements until they come to the method's final brace bracket. If we want to terminate execution of the method before this, we can do so by using a return statement.

Example 3

The method printRoot will read a value and then find and print its square root if and only if the value is non-negative.
public static void printRoot ()
{
   System.out.println("Please give a non-negative value");
   double x = In.getDouble();
   if (x < 0)
      return;
   else
      System.out.println("Square root is " + Math.sqrt(x));
} 

Although the use of return statements can be useful, it is often best (and always possible) to avoid them and have the method simply "fall through" to its end, at which point a return occurs automatically.

Exercise 5.1

  1. Explain the difference between a method definition and a method invocation.


  2. In the following program, the executable statements are numbered. Use these numbers to indicate the order in which the statements are executed.
    class Song
    {  
       public static void printChorus ()
       {
          System.out.println(); //1
          System.out.println("Ee-igh, ee-igh, oh!"); //2
          System.out.println(); //3
       } 
       public static void main (String[] args)
       {  
          System.out.println("Old MacDonald had a farm"); //4
          printChorus(); //5
          System.out.println("And on that farm he had" + "a pig"); //6
          printChorus(); //7
       }
    }
  3. Rewrite the method of Example 3 so that it avoids the use of a return statement.


  4. Write a method that will simulate the results of rolling two fair dice by printing two random integer values in the range 1 to 6 along with their total. Sample output from a call to the method could be:
    4 and 3 - a total of 7