Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Java Methods: Understanding the Basics - Prof. Jennifer E. Walter, Study notes of Computer Science

An introduction to java methods, including an overview of method calls, static methods in the math class, writing your own methods, and methods involving control statements. It covers the general form of a method definition, returning values, and using control statements within methods.

Typology: Study notes

Pre 2010

Uploaded on 08/19/2009

koofers-user-9a4
koofers-user-9a4 🇺🇸

5

(1)

10 documents

1 / 6

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Chapter 5Methods
The Art and Science of
An Introduction
to Computer Science
ERIC S. ROBERTS
Java
Methods
C H A P T E R 5
With method and logic one can accomplish
anything. —Agatha Christie, Poirot Investigates, 1924
CMPU-101
Computer Science I:
Problem-Solving and Abstraction
Fall 2008
Jennifer Walter
(adapted from slides by Eric Roberts)
A Quick Overview of Methods
You have been working with methods ever since you wrote
your first Java program in Chapter 2. Most of the programs
you have seen have used method calls such as println and
setColor.
At the most basic level, a method is a sequence of statements
that has been collected together and given a name. The name
makes it possible to execute the statements by just providing
the method name.
The following terms are useful when learning about methods:
Invoking a method using its name is known as calling that method.
A method call is preceded by either this, an object name, or a class
name and . (the dot operator)
The caller can pass information to a method by using arguments.
When a method completes its operation, it returns to its caller, on the
line it was called.
A method can pass information to the caller by returning a result.
Method Calls are Expressions
Method calls in Java are expressions. Methods that return a
value can be used as terms in an expression just like variables
and constants and those that don’t can be used on their own.
The Math class in the java.lang package defines several
methods that are useful in writing mathematical expressions.
Suppose, for example, that you n eed to compute the distance
from the origin to the point (x, y), which is given by
x
2 + y
2
You can apply the square root function by calling the sqrt
method in the Math class like this:
double distance = Math.sqrt(x * x + y * y);
Static (Class) Methods
Recall the keyword static, used when defining named
constants. This keyword is also used when defining certain
methods. When static is used in a method definition, a
method can be called by using the following pattern:
ClassName.methodName(argument list);
Note that you need to include the name of the class before a
static method name. Methods like Math.sqrt are called
static methods and are defined with the keyword static in
the definition as shown below:
public static double sqrt(double x) {
Static Method calls on the Math Class
Math.abs(x)Returns the absolute value of x
Math.min(x, y)Returns the smaller of x and y
Math.max(x, y)Returns the larger of x and y
Math.sqrt(x)Returns the square root of x
Math.log(x)Returns the natural logarithm of x (loge x )
Math.exp(x)Returns the inverse logarithm of x (e
x
)
Math.pow(x, y)Returns the value of x raised to the y power (x y
)
Math.sin(theta)Returns the sine of theta, measured in radians
Math.cos(theta)Returns the cosine of theta
Math.tan(theta)Returns the tangent of theta
Math.asin(x)Returns the angle whose sine is x
Math.acos(x)Returns the angle whose cosine is x
Math.atan(x)Returns the angle whose tangent is x
Math.toRadians(degrees)Converts an angle from degrees to radians
Math.toDegrees(radians)Converts an angle from radians to degrees
Writing Your Own Methods
The general form of a method definition is
scope type name(parameter declaration list) {
statements in the method body
}
where scope indicates who has access to the method, type
indicates the return type, n ame is the identifier of the method,
and parameter declaration list is a list of declarations of
variables that are local to the method.
All methods must be defined directly inside the class braces
(do not define methods inside the curly braces of other
methods)
pf3
pf4
pf5

Partial preview of the text

Download Java Methods: Understanding the Basics - Prof. Jennifer E. Walter and more Study notes Computer Science in PDF only on Docsity!

Chapter 5—Methods The Art and Science of An Introduction

ERIC S. ROBERTS^ Java^ to Computer Science

Methods

C H A P T E R 5 With method and logic one can accomplish anything. —Agatha Christie, Poirot Investigates, 1924

CMPU-

Computer Science I:

Problem-Solving and Abstraction

Fall 2008

Jennifer Walter

(adapted from slides by Eric Roberts)

A Quick Overview of Methods

  • You have been working with methods ever since you wrote your first Java program in Chapter 2. Most of the programs you have seen have used method calls such as println and setColor.
  • At the most basic level, a method is a sequence of statements that has been collected together and given a name. The name makes it possible to execute the statements by just providing the method name.
  • The following terms are useful when learning about methods:
  • Invoking a method using its name is known as calling that method.
  • A method call is preceded by either this , an object name, or a class name and. (the dot operator)
  • The caller can pass information to a method by using arguments.
  • When a method completes its operation, it returns to its caller, on the line it was called.
  • A method can pass information to the caller by returning a result.

Method Calls are Expressions

  • Method calls in Java are expressions. Methods that return a value can be used as terms in an expression just like variables and constants and those that don’t can be used on their own.
  • The Math class in the java.lang package defines several methods that are useful in writing mathematical expressions. Suppose, for example, that you need to compute the distance from the origin to the point ( x , y ), which is given by x^2 + y^2 You can apply the square root function by calling the sqrt method in the Math class like this: double distance = Math.sqrt(x * x + y * y);

Static (Class) Methods

  • Recall the keyword static, used when defining named constants. This keyword is also used when defining certain methods. When static is used in a method definition, a method can be called by using the following pattern: ClassName. methodName ( argument list );
  • Note that you need to include the name of the class before a static method name. Methods like Math.sqrt are called static methods and are defined with the keyword static in the definition as shown below: public static double sqrt(double x) {

Static Method calls on the Math Class

Math.abs( x ) Returns the absolute value of x Math.min( x , y ) Returns the smaller of x and y Math.max( x , y ) Returns the larger of x and y Math.sqrt( x ) (^) Returns the square root of x Math.log( x ) (^) Returns the natural logarithm of x (log e x ) Math.exp( x ) (^) Returns the inverse logarithm of x ( e x^ ) Math.pow( x , y ) Returns the value of x raised to the y power ( x y^ ) Math.sin( theta ) Returns the sine of theta, measured in radians Math.cos( theta ) Returns the cosine of theta Math.tan( theta ) Returns the tangent of theta Math.asin( x ) Returns the angle whose sine is x Math.acos( x ) Returns the angle whose cosine is x Math.atan( x ) Returns the angle whose tangent is x Math.toRadians( degrees ) Converts an angle from degrees to radians Math.toDegrees( radians ) Converts an angle from radians to degrees

Writing Your Own Methods

  • The general form of a method definition is scope type name ( parameter declaration list ) { statements in the method body } where scope indicates who has access to the method, type indicates the return type, name is the identifier of the method, and parameter declaration list is a list of declarations of variables that are local to the method. All methods must be defined directly inside the class braces (do not define methods inside the curly braces of other methods)

Writing Your Own Methods

scope type name ( parameter declaration list ) { statements in the method body }

  • The first line in the method declaration above is called the method header line or signature.
  • The most common value for scope is private , which means that the method is available only within its own class. If other classes need access to it, scope should be public. If scope is public, you are exporting the method for other programmers to use.
  • If a method does not return a value, type should be void.
  • To return a value from a method, you must include a return statement in the method body.

Methods that Return Values

  • You can return a value from a method by including a return statement inside the method body, which is usually written as return expression ; where expression is a Java expression that specifies the value you want to return of the type specified in the method header.
  • As an example, the method definition private double feetToInches(double feet) { return INCHES_IN_FOOT * feet; } converts a distance in feet to the equivalent number of inches, relying on the fact that there are 12 inches in a foot and that INCHES_IN_FOOT is a named constant set equal to 12.

Writing Your Own Methods

  • The int n inside the parentheses is a parameter. / multiplies given number by 2 / private int doubleNum(int n) { return 2 * n; }
  • The this.doubleNum inside the constructor is a call to the doubleNum method. / constructor of UseDouble class,* *calls doubleNum / public UseDouble() { this.start(); int num = this.doubleNum( 3 ); }
  • The 3 inside the parentheses is an argument.

Writing Your Own Methods

  • The int n, int z inside the parentheses are parameters. / return the result of 2n+z /* private int nX2PlusZ(int n, int z) { return 2 * n + z; }
  • The this.nX2PlusZ inside the constructor is a call to the nX2PlusZ method. / constructor of UsenX2PlusZ / public UsenX2PlusZ () { this.start(); this.println(""+this.nX2PlusZ(3,4)); }
  • The 3 and 4 inside the parentheses are arguments.

Parameters declare local variables

Parameter lists contain pairs, consisting of type names followed by identifiers. These identifiers are local variable names. Calling a method with an argument list is exactly the same as initializing each of the local variables declared in the parameter list. Whenever you are considering local variable names within a method, you must also consider each parameter name to be a local variable.

Mechanics of the Method-Calling Process

When you call a method, the following actions occur: The argument list in the method call is evaluated in the context of the calling method.

Each argument’s value is copied into the corresponding parameter variable. Assignment follows the order in which the arguments appear: the first argument is copied into the first parameter variable, and so on.

  1. The statements in the method body are evaluated in sequence. If a return statement is run, the return value is computed and substituted for the method call in the calling method.

Execution continues from where it left off in the calling method.

Methods that Return Nothing

If a method doesn’t return anything, you specify its return type as void. A very simple method that returns nothing is shown below: private void printDirections() { this.println("Welcome to my program!"); this.println("To get started, click "+ "anywhere in the window."); } This "void" method would be called by the statement this.printDirections(); in either the constructor or in some other method in the same class body. Instead of a return value, this method has a side- effect , printing text to the console.

The factorial Method

  • The factorial of a number n (which is usually written as n! in mathematics) is defined to be the product of the integers from 1 up to n. Thus, 5! is equal to 120, which is 1 x^2 x^3 x^4 x^ 5. private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { *result = i; } return result; }
  • The following method definition uses a for loop to compute the factorial function:

Exercise: Testing Powers of Two

  • Write a predicate method called isPowerOfTwo that defines an integer parameter called n and returns true if n is a power of two, and false otherwise. The powers of 2 are 1, 2, 4, 8, 16, 32, and so forth; numbers that are less than or equal to zero cannot be powers of two. private boolean isPowerOfTwo(int n) { if (n < 1) return false; while (n > 1) { if (n % 2 == 1) return false; n /= 2; } return true; }

Decomposition

One of the most important advantages of methods is that they make it possible to break a large task down into successively simpler pieces. This process is called decomposition. Complete Task Suppose, for example, that you have been given a large task that seems too large to code in a single constructor. Subtask 1 Subtask 2 Subtask 3 Before you start writing any code, you should think about the problem with an eye toward breaking the complete task into simpler subtasks. Subtask 2a Subtask 2b Some of the subtasks may themselves be so difficult that it makes sense to break them into even smaller subtasks. You can then continue the process until each individual subtask is manageable. One of the most important advantages of methods is that they make it possible to break a large task down into simpler pieces, a process called decomposition. Once you have completed the decomposition, you can then write a method to implement each subtask.

The Combinations Function

  • To illustrate method calls, the text uses a function C ( n, k ) that computes the combinations function, which is the number of ways one can select k elements from a set of n objects.
  • Suppose, for example, that you have a set of five coins: a penny, a nickel, a dime, a quarter, and a dollar: How many ways are there to select two coins? penny + nickel penny + dime penny + quarter penny + dollar nickel + dime nickel + quarter nickel + dollar dime + quarter dime + dollar quarter + dollar for a total of 10 ways.

Combinations and Factorials

  • Fortunately, mathematics provides an easier way to compute the combinations function than by counting all the ways. The value of the combinations function is given by the formula C ( n, k ) = n^! k! x( nk )!
  • Given that you already have a factorial method, it is easy to turn this formula directly into a Java method, as follows: private int combinations(int n, int k) { return factorial(n) / (factorial(k) * factorial(n - k)); }

Choosing a Decomposition Strategy

  • How do you decompose large tasks into smaller ones?
  • If the real-world problem has natural subdivisions, those subdivisions usually provide a useful basis for designing the program decomposition.
  • Each subtask in the decomposition should perform a single function that is easy to name and describe.
  • One of the primary goals of decomposition is to simplify the programming process. A good decomposition strategy must therefore limit the spread of complexity. As a general rule, each level in the decomposition should take responsibility for certain details and avoid having those details percolate up to higher levels.

Drawing a Train

  • As its primary illustration of decomposition, the text uses the problem of writing a GraphicsProgram to draw a train:
  • Although it would be possible to write a single constructor to draw the necessary graphical objects, such a program would be very difficult to read. Fortunately, the problem has a natural decomposition, at least at the first level: public DrawTrain() { Draw the engine. Draw the boxcar. Draw the caboose. } DrawTrain

Using Pseudocode

  • Although the constructor public DrawTrain() { Draw the engine. Draw the boxcar. Draw the caboose. } suggests the decomposition for the DrawTrain program, it is not legal Java code, being a combination of English and Java. Such informal descriptions are called pseudocode.
  • It is important to remember that you don’t need to implement each of the steps before you can turn this pseudocode into legal Java. Each of the English lines will simply be a method call. All you need to do at this point is give each method a name and decide what arguments those methods need.

Parameters for Drawing Train Cars

  • The DrawTrain program in the text makes the following assumptions: - The caller will always want to supply the location of each car. - All train cars are the same size and have the same basic structure. - Engines are always black. - Boxcars come in many colors, which means the caller must supply it. - Cabooses are always red.
  • These assumptions imply that the headers for drawEngine , drawBoxcar , and drawCaboose will look like this: private void drawEngine(double x, double y) private void drawBoxcar(double x, double y, Color color) private void drawCaboose(double x, double y)

Looking for Common Features

  • Another useful strategy in choosing a decomposition is to look for features that are shared among several different parts of a program. Such common features can be implemented by a single method.
  • In the DrawTrain program, every train car has a common structure that consists of the frame for the car, the wheels on which it runs, and a connector to link it to its neighbor. - The engine is black and adds a smokestack, cab, and cowcatcher. - The boxcar is colored as specified by the caller and adds doors. - The caboose is red and adds a cupola.
  • You can use a single drawCarFrame method to draw the common parts of each car, as described in the text.

Algorithmic Methods

  • Methods are important in programming because they provide a structure in which to express and encapsulate algorithms. Algorithms are abstract expressions of a solution strategy. Implementing an algorithm as a method makes that abstract strategy concrete.
  • Algorithms for solving a particular problem can vary widely in their efficiency. It makes sense to think carefully when you are choosing an algorithm because making a bad choice can be extremely costly.
  • Section 5.5 in the text looks at two algorithms for computing the greatest common divisor of the integers x and y, which is defined to be the largest integer that divides evenly into both.