Chapter 4. Methods and Testing
So far, we’ve written programs that have only one method, named main. In this chapter, we’ll show you how to organize programs into multiple methods. We’ll also take a look at the Math class, which provides methods for common mathematical operations. Finally, we’ll discuss strategies for incrementally developing and testing your code.
Defining New Methods
Some methods perform a computation and return a result. For example, nextDouble reads input from the keyboard and returns it as a double. Other methods, like println, carry out a sequence of actions without returning a result. Java uses the keyword void to define such methods:
publicstaticvoidnewLine(){System.out.println();}publicstaticvoidmain(String[]args){System.out.println("First line.");newLine();System.out.println("Second line.");}
In this example, the newLine and main methods are both public, which means they can be invoked (or called) from other classes. And they are both void, which means that they don’t return a result (in contrast to nextDouble). The output of the program is shown here:
First line. Second line.
Notice the extra space between the lines. If we wanted more space between them, we could invoke the same method repeatedly. Or we could write yet another method (named threeLine) that displays three blank lines:
publicclassNewLine{publicstaticvoidnewLine(){System.out.println();}publicstaticvoidthreeLine(){newLine();newLine();newLine();}publicstatic ...