|
All the programs we've written to date have been quite simple, well under fifty lines of code each. As programs grow in size it begins to make sense to break them into parts. Each part can perform a particular calculation and possibly return a value. This is especially useful when the calculation needs to be repeated at several different places in the program. It also helps to define a clearer picture of the flow of the program, much like an outline shows the flow of a book.
Each calculation part of a program is called a method. Methods are logically the same as C's functions, Pascal's procedures and functions, and Fortran's functions and subroutines.
The above programs have already used a number of methods although these were all methods provided by the system. When we wrote System.out.println("Hello World!); in the first program we were using the System.out.println() method. (To be more precise we were using the println() method of the out member of the System class, but we'll talk more about that in Chapter 4.) The System.out.println() method actually requires quite a lot of code, but it is all stored for us in the System libraries. Thus rather than including that code every time we need to print, we just call the System.out.println() method.
You can write and call your own methods too. Let's look at a simple example. Java has no built-in factorial method so we'll write one. The following is a simple program that requests a number from the user and then calculates the factorial of that number.
We'll use two methods in the program, one that checks to see if the user has in fact entered a valid positive integer, and another that calculates the factorial. However we'll start by writing the main method of the program:
class Factorial { public static void main(String args[]) { int n; while ((n = getNextInteger()) = 0) { System.out.println(factorial(n)); } } // main ends here } Among other things this code demonstrates that methods make it possible to design the flow of a program without getting bogged down in the details. We've simply named two methods, getNextInteger() and factorial() without worrying about their exact implementations. We can add the rest of the code in smaller, easier-to-understand pieces. Let's write the factorial method first.
long factorial (long n) { int i; long result=1; for (i=1; i <= n; i++) { result *= i; } return result; } // factorial ends here
|