• No results found

Statement Forms

5.1 A quick overview of methods

You have been working with methods ever since Chapter 2. Before turning to the details of how methods work, it helps to review the basic terminology for methods that was introduced in that chapter. First of all, a method consists of a set of statements that have been collected together and given a name. The act of executing the set of statements associated with a method is known as calling that method. To indicate a method call in Java, you write the name of the method, followed by a list of expressions enclosed in parentheses. These expressions are called arguments and allow the caller to pass information to the method.

As an example, consider the first line from the Add2Integers program that appeared as Figure 2-2, which looks like this:

println("This program adds two integers.");

This statement represents a call to the println method, which prints out a line of information on the console. To make any sense of that idea, however, the println method has to know what information to display. Here, that information is provided through the argument, which consists of the string "Thisprogramaddstwointegers.". Once called, a method takes the data supplied as arguments, does its work, and then returns to the point in the program at which the call was made. Remembering what the calling program was doing and being able to get back precisely to that point is one of the defining characteristics of the method-calling mechanism. The operation of going back to the calling program is called returning from the method. As part of the return operation, methods can also send results back to the calling program, as illustrated by the readInt method in the now-familiar declaration

int n1 = readInt("Enter n1: ");

After the readInt method performs its task of reading in an integer from the user, it passes that integer back to the calling program as the value of the call. This operation is called returning a value.

Methods as mechanisms for hiding complexity Take another look at the line

which begins the Add2Integers program. When this program first appeared back in Chapter 2, the text described what the println method does in very simple terms: it takes the string you have provided as an argument and makes it appear on the console that is supplied as part of every ConsoleProgram. The text, however, was silent on the question of how println accomplishes that operation. The details of the underlying implementation remain largely a mystery, which to a certain extent makes the operation of println seem like magic.

In J. K. Rowling’s Harry Potter and the Chamber of Secrets, Arthur Weasley warns that you should “never trust anything that can think for itself if you can’t see where it keeps its brain.” While that may be sage advice in the wizarding world, programmers must often do precisely that. You did not write println and indeed would have no way of doing so at this point in your study of programming. It would be extremely difficult even to understand how it works. Even so, there is nothing to stop you from using it effectively.

In fact, one of the great advantages of methods is that you can use them without having to understand the complexity that goes on underneath. Methods provide a way of hiding lower-level implementation details so that the caller need not be bothered by them. In computer science, this technique is called information hiding. The fundamental idea, which was championed by David Parnas in the early 1970s, is that the complexity of programming systems is best managed by making sure that details are visible only to those levels of the program at which they are relevant. The programmers who implement println and make sure that it works need to know those details. The programmers that merely use println can remain blissfully unaware of all that underlying mechanism. Methods as tools for programmers rather than users

Students who are just beginning their study of programming sometimes have difficulty understanding the distinction between methods and programs. To some extent, both programs and methods have the effect of collecting a sequence of statements and giving it a single name. If you look at the Add2Integers program, it acts as if it is a shorthand for the set steps contained in its run method.

It is, however, important to keep these concepts distinct. The principal difference between a method and a program lies in who or what makes use of it. When, as a user, you sit down in front of your computer and start up an application, you are running a program that performs some action on your behalf. Thus, programs are invoked by and serve the needs of an external user. Methods, on the other hand, provide a mechanism by which a program can invoke a set of previously defined operations on its behalf. The operation of a method is thus internal to the program domain.

Be careful to differentiate in your mind the ideas of input and output in the program domain and the related concepts of arguments and results in the method domain. Input and output refer to communication between a

program and its user. Arguments and results represent communication between a method and its caller.

A similar confusion often arises between the arguments and program input on the one hand, and return values and program output on the other. It is easy to see input data entered using r e a d I n t as analogous to values passed as arguments. Both, after all, represent a way of passing data into some piece of a program. Despite that conceptual similarity, it is critically important to make a sharp distinction between input operations, such as readInt, and the use of

arguments in the method domain. A method like readInt provides a mechanism for getting input from the user. When readInt needs an input value, whoever is sitting in front of the terminal must physically enter that value on the keyboard. Arguments to a

method, on the other hand, provide a means for a method to receive input from its caller, which is simply another part of the program. Data passed in the form of arguments may have been entered by the user at an earlier point in the program, but could just as easily have been calculated as part of the program operation. You should also be careful to differentiate the use of output operations, such as println, from the technique of returning a result. When you use println, the output appears on the console. When a method returns a result, that information goes back to its caller, which is free to use it in whatever way makes sense for the program. New programmers have a tendency to use input/output operations within methods when the logic of the situation calls for using arguments and results.

Method calls as expressions

In Chapter 3, method calls were listed as one of the categories of Java expressions. As you try to understand how methods fit into the overall Java framework, it will often be helpful to remember that a method call is simply an expression and can be used in any context in which an expression can appear. Moreover, the arguments to a method are also expressions, which can themselves contain method calls or any other operations that would be legal in an expression.

To illustrate that methods and their arguments are expressions, it is useful to introduce several standard methods from the Math class, which are listed in Figure 5-1. As you can see from the list of available methods, the Math class includes many of the standard

FIGURE 5-1 Selected methods from the Math class

Math.abs(x)

The absolute value of x, which can be of any numeric type.

Math.min(x, y)

The smaller of x and y.

Math.max(x, y)

The larger of x and y.

Math.sqrt(x)

The square root of the value x.

Math.log(x)

The natural logarithm of x, which uses the mathematical constant e as its base.

Math.exp(x)

The inverse logarithm of x, which is ex.

Math.pow(x, y)

The value x raised to the y power.

Math.sin(theta)

The trigonometric sine of the angle theta; in the Math class, all angles are measured in radians.

Math.cos(theta)

The cosine of the angle theta.

Math.tan(theta)

The tangent of the angle theta.

Math.asin(x)

The angle whose sine is x.

Math.acos(x)

The angle whose cosine is x.

Math.atan(x)

The angle whose tangent is x.

Math.toRadians(degrees)

Converts an angle from degrees to radians.

Math.toDegrees(radians)

mathematical functions you learned in high-school algebra and trigonometry. For example, the Math class includes the method sqrt for taking the square root of its argument, as well as sin and cos for trigonometric sines and cosines. Each of these methods takes a double as an argument and returns a result, also of type double. You can use these methods in simple statements, such as

double root3 = Math.sqrt(3.0);

or in more complicated ones. For example, you can compute the distance from the origin to the point (x, y) using the standard distance formula for points in a plane:

distance =

√⎯⎯⎯⎯⎯

x2 + y2

In Java, this formula corresponds to the statement

double distance = Math.sqrt(x*x + y*y);

Similarly, you can compute a tangent using the trigonometric identity tan θ = sin θ

cos θ

which can be written in Java as

double tangent = Math.sin(theta) / Math.cos(theta);