Docsity

Methods - Java Programming Language - Lecture Slides, Slides of Computer Science

Partial preview of the text

Download Methods - Java Programming Language - Lecture Slides and more Slides Computer Science in PDF only on Docsity!

Chapter 4: Methods

  • Method Structure
  • Declaring Methods
  • Calling Methods
  • Passing Parameters
  • Pass by Value
  • Overloading Methods
  • Method Abstraction
  • The Math Class
  • Recursion (Optional)

Method Structure

A method is

a collection

of

statements

that are

grouped

together to

perform an

operation.

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

modifier returnValueType

methodName parameters

return value

method body

method heading

Calling Methods

Example 4.1 Testing the max method

This program demonstrates calling a

method max to return the largest of the

int values

TestMax (^) Run

Passing Parameters

void nPrintln(String message, int n)

for (int i=0; i

Overloading Methods

Example 4.3 Overloading the max

Method

double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; }

TestMethodOverloading (^) Run

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 return value

Trigonometric Methods

  • sin(double a)
  • cos(double a)
  • tan(double a)
  • acos(double a)
  • asin(double a)
  • atan(double a)

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.

Using Math Methods

Example 4.4 Computing Mean and Standard Deviation

Generate 10 random numbers and compute the mean and standard deviation

ComputeMeanDeviation (^) Run

n

x

mean

n

i

∑ i

= =^1

1

1

2

−

−

= n

x mean deviation

n

i

i

Case Studies

Example 4.5 Displaying Calendars

The program reads in the month and

year and displays the calendar for a

given month of the year.

PrintCalendar (^) Run

Recursion (Optional)

Example 4.6 Computing Factorial

factorial(0) = 1;

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

ComputeFactorial (^) Run

Fibonnaci Numbers

Example 4.7 Computing Finonacci

Numbers

Find Fibonacci numbers using recursion.

fib(0) = 1;

fib(1) =1;

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

ComputeFibonacci (^) Run