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.
|
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.
|
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.
|
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.
|