chapter 4 methods f introducing methods –benefits of methods, declaring methods, and calling...

38
Chapter 4 Methods Introducing Methods Benefits of methods, Declaring Methods, and Calling Methods Passing Parameters Pass by Value Overloading Methods Ambiguous Invocation Scope of Local Variables Method Abstraction The Math Class Case Studies Recursion (Optional)

Upload: nicolette-tongue

Post on 11-Dec-2015

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Chapter 4 Methods Introducing Methods

– Benefits of methods, Declaring Methods, and Calling Methods

Passing Parameters– Pass by Value

Overloading Methods– Ambiguous Invocation

Scope of Local Variables Method Abstraction The Math Class Case Studies Recursion (Optional)

Page 2: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Introducing Methods

Method StructureA method is a collection of statements that are grouped together to perform an operation.

Page 3: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Introducing Methods, cont.•parameter profile refers to the type, order, and number of the parameters of a method.

•method signature is the combination of the method name and the parameter profiles.

•The parameters defined in the method header are known as formal parameters.

•When a method is invoked, its formal parameters are replaced by variables or data, which are referred to as actual parameters.

Page 4: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Declaring Methods

public static int max(int num1, int num2) {

if (num1 > num2) return num1; else return num2;}

Page 5: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Calling Methods

Example 4.1 Testing the max method

This program demonstrates calling a method max to return the largest of the int values

TestMaxTestMax Run

Page 6: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Calling Methods, cont.

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }

public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

pass i pass j

Page 7: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Calling Methods, cont.

The main method i: j: k:

The max method num1: num2: result:

pass 5

5

2

5

5

2

5

pass 2 parameters

Page 8: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

CAUTION

A return statement is required for a nonvoid method. The following method is logically correct, but it has a compilation error, because the Java compiler thinks it possible that this method does not return any value. public static int xMethod(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; }

To fix this problem, delete if (n<0) in the code.

Page 9: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Passing Parameterspublic static void nPrintln(String message, int n) {

for (int i = 0; i < n; i++) System.out.println(message);}

Page 10: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Pass by Value

Example 4.2 Testing Pass by value

This program demonstrates passing values to the methods.

TestPassByValueTestPassByValue Run

Page 11: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Pass by Value, cont.

swap(num1, num2)

swap( n1, n2)

Pass by value

num1

Swap

1

2

n1

n2

1

2

n1

n2

2

1

temp 1

Execute swap inside the swap body

num2

Invoke swap The values of num1 and num2 are passed to n1 and n2. Executing swap does not affect num1 and num2.

Page 12: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Overloading Methods

Example 4.3 Overloading the max Method

public static double max(double num1, double num2) {

if (num1 > num2) return num1; else return num2;}

TestMethodOverloadingTestMethodOverloading Run

Page 13: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Ambiguous Invocation

Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error.

Page 14: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Ambiguous Invocationpublic class AmbiguousOverloading { public static void main(String[] args) { System.out.println(max(1, 2)); }  public static double max(int num1, double num2) { if (num1 > num2) return num1; else return num2; } public static double max(double num1, int num2) { if (num1 > num2) return num1; else return num2; }}

Page 15: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Scope of Local VariablesA local variable: a variable defined inside a

method.Scope: the part of the program where the variable

can be referenced.The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used.

Page 16: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Scope of Local Variables, cont.

You can declare a local variable with the same name multiple times in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks. Thus, the following code is correct.

Page 17: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Scope of Local Variables, cont.// Fine with no errorspublic static void correctMethod() { int x = 1; int y = 1; // i is declared for (int i = 1; i < 10; i++) { x += i; } // i is declared again for (int i = 1; i < 10; i++) { y += i; }}

Page 18: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Scope of Local Variables, cont.

// With no errorspublic static void incorrectMethod() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { int x = 0; x += i; }}

Page 19: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Method Abstraction

You can think of the method body as a black box that contains the detailed implementation for the method.

Method Signature

Method body

Black Box

Optional Input Optional returnvalue

Page 20: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Benefits of Methods

• Write once and reuse it any times.

• Information hiding. Hide the implementation from the user.

• Reduce complexity.

Page 21: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

The Math Class Class constants:

– PI– E

Class methods: – Trigonometric Methods – Exponent Methods– Rounding Methods– min, max, abs, and random Methods

Page 22: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Trigonometric Methods

sin(double a)

cos(double a)

tan(double a)

acos(double a)

asin(double a)

atan(double a)

Page 23: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Exponent Methods exp(double a)

Returns e raised to the power of a.

log(double a)

Returns the natural logarithm of a.

pow(double a, double b)

Returns a raised to the power of b.

sqrt(double a)

Returns the square root of a.

Page 24: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Rounding Methods double ceil(double x)

x rounded up to its nearest integer. This integer is returned as a double value.

double floor(double x)x is rounded down to its nearest integer. This integer is returned as a double value.

double rint(double x)x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double.

int round(float x)Return (int)Math.floor(x+0.5).

long round(double x)Return (long)Math.floor(x+0.5).

Page 25: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

min, max, abs, and random

max(a, b)and min(a, b)Returns the maximum or minimum of two parameters.

abs(a)Returns the absolute value of the parameter.

random()Returns a random double valuein the range [0.0, 1.0).

Page 26: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Example 4.4 Computing Mean and Standard Deviation

Generate 10 random numbers and compute the mean and standard deviation

ComputeMeanDeviationComputeMeanDeviation Run

n

xmean

n

ii

1

1

)(

1

2

12

nn

xx

deviation

n

i

n

ii

i

Page 27: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Example 4.5 Obtaining Random Characters

Write the methods for generating random characters. The program uses these methods to generate 175 random characters between ‘!' and ‘~' and displays 25 characters per line. To find out the characters between ‘!' and ‘~', see Appendix B, “The ASCII Character Set.”

RandomCharacterRandomCharacter Run

Page 28: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Example 4.5 Obtaining Random Characters, cont.

Appendix B: ASCII Character Set

Page 29: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Case Studies

Example 4.6 Displaying Calendars

The program reads in the month and year and displays the calendar for a given month of the year.

PrintCalendarPrintCalendar Run

Page 30: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Design Diagram

printCalendar (main)

readInput printMonth

getStartDay printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Page 31: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Recursion (Optional)

Example 4.7 Computing Factorial

factorial(0) = 1;

factorial(n) = n*factorial(n-1);

ComputeFactorialComputeFactorial Run

Page 32: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Example 4.7 Computing Factorial, cont.

factorial(4) = 4*factorial(3)

factorial(3) = 3*factorial(2)

factorial(2) = 2*factorial(1)

factorial(1) = 1*factorial(0)

Step 6: factorial(1) returns 1 (1*1)

main method: factorial(4)

Step 1: factorial(4) calls factorial(3)

factorial(4) is called in the main

Step 2: factorial(3) calls factorial(2)

Step 3: factorial(2) calls factorial(1)

factorial(0) = 1

Step 4: factorial(1) calls factorial(0)

Step 5: factorial(0) returns 1

Step 7: factorial(2) returns 2 (2*1)

Step 8: factorial(3) returns 6 (3*2)

Step 9: factorial(4) returns 24 (4*6)

Page 33: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Example 4.7 Computing Factorial, cont.

Space Requiredfor factorial(4)

1 Space Requiredfor factorial(4)

2 Space Requiredfor factorial(3)

Space Requiredfor factorial(4)

3

Space Requiredfor factorial(3)

Space Requiredfor factorial(2)

Space Requiredfor factorial(4)

4

Space Requiredfor factorial(3)

Space Requiredfor factorial(2)

Space Requiredfor factorial(1)

Space Requiredfor factorial(4)

5

Space Requiredfor factorial(3)

Space Requiredfor factorial(2)

Space Requiredfor factorial(1)

Space Requiredfor factorial(0)

Space Requiredfor factorial(4)

6

Space Requiredfor factorial(3)

Space Requiredfor factorial(2)

Space Requiredfor factorial(1)

Space Requiredfor factorial(4)

7

Space Requiredfor factorial(3)

Space Requiredfor factorial(2)

Space Requiredfor factorial(4)

8 Space Requiredfor factorial(3)

Space Requiredfor factorial(4)

9

Page 34: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Fibonacci Numbers

Example 4.8 Computing Finonacci Numbers0 1 1 2 3 5 8 13 21 34 55 89…f0 f1

fib(2) = fib(0) + fib(1);

fib(0) = 0;

fib(1) = 1;

fib(n) = fib(n-2) + fib(n-1); n>=2

Page 35: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Fibonacci Numbers, cont

ComputeFibonacciComputeFibonacci Run

Page 36: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Fibonnaci Numbers, cont.

fib(4)=

fib(3) + fib(2)

call fib(3)

1

fib(3)= fib(2) + fib(1)

2 return fib(3)

call fib(2)

fib(2)= fib(1) + fib(0)

3

return fib(2)

call fib(1)

fib(1)= 1

4

return fib(1)

fib(2)= fib(1) + fib(0)

7

fib(0)= 0

5

fib(1)= 1

6 fib(1)= 1

8

return fib(1)

fib(0)= 1

9

Page 37: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Towers of Hanoi

Example 4.9 Solving the Towers of Hanoi Problem

Solve the towers of Hanoi problem.

TowersOfHanoiTowersOfHanoi Run

Page 38: Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading

Towers of Hanoi, cont.

A

A

B

C

Step 0: Starting status

C

B

Step 2: Move disk 2 from A to C

A B

Step 3: Move disk 1 from B to C

C

A B

Step 4: Move disk 3 from A to B

C

A B

Step 5: Move disk 1 from C to A

CA B

Step 1: Move disk 1 from A to B

C

A B

Step 7: Mve disk 1 from A to B

C

A B

Step 6: Move disk 2 from C to B

C