0% found this document useful (0 votes)
29 views

CPCS202 06 Methods S19

Uploaded by

AHMED A FATANI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

CPCS202 06 Methods S19

Uploaded by

AHMED A FATANI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 154

Chapter 6:

Methods
Objectives
 To define methods with formal parameters (§6.2).
 To invoke methods with actual parameters (i.e., arguments) (§6.2).
 To define methods with a return value (§6.3).
 To define methods without a return value (§6.4).
 To pass arguments by value (§6.5).
 To develop reusable code that is modular, easy to read, easy to debug,
and easy to maintain (§6.6).
 To write a method that converts hexadecimals to decimals (§6.7).
 To use method overloading and understand ambiguous overloading
(§6.8).
 To determine the scope of variables (§6.9).
 To apply the concept of method abstraction in software development
(§6.10).
 To design and implement methods using stepwise refinement (§6.10).

© Dr. Jonathan Cazalas Chapter 6: Methods page 2


Program 1: Sum Many Numbers
 Write a program that will sum three sets of
numbers and then display the sum of each:
– sum of integers from 1 to 10
– sum of integers from 20 to 37
– sum of integers from 35 to 49
 Remember:
– Step 1: Problem-solving Phase
– Step 2: Implementation Phase

© Dr. Jonathan Cazalas Chapter 6: Methods page 3


Program 1: Sum Many Numbers
 Step 1: Problem-solving Phase
– Algorithm:
 This program is really easy
 For each set of numbers:
– make a variable sum
– make a for loop and sum from the first number to the second
number
– print the final sum
 So this is very easy to do
 Unfortunately, we have to do it three times!

© Dr. Jonathan Cazalas Chapter 6: Methods page 4


Program 1: Sum Many Numbers
 Step 2: Implementation
public class SumManyNumbers{
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);

sum = 0;
for (int i = 20; i <= 37; i++)
sum += i;
System.out.println("Sum from 20 to 37 is " + sum);

sum = 0;
for (int i = 35; i <= 49; i++)
sum += i;
System.out.println("Sum from 35 to 49 is " + sum);
}
}

© Dr. Jonathan Cazalas Chapter 6: Methods page 5


Program 1: Sum Many Numbers
 Observation
– Each sum is doing something very similar
– In fact, each sum is essentially doing the same thing
– The only difference is the range of numbers
 the starting and ending numbers of the sum
– So why do we *repeat* our code three times?
– Wouldn't it be nice if we could write "common" code
and then reuse it when needed?
 That would be PERFECT!
– This is the idea of methods!
© Dr. Jonathan Cazalas Chapter 6: Methods page 6
Program 1: Sum Many Numbers
 Step 2: Implementation

 Here, we write a method to calculate the sum


– And then, inside main, we call/invoke the method three times
 You don't need to understand this perfectly right now
 We will spend the next two weeks understanding it!
© Dr. Jonathan Cazalas Chapter 6: Methods page 7
Methods
 What is a method?
– A method is a collection of statements grouped
together to perform an operation.
– Guess what?
 You have already used many predefined methods!
 Examples:
System.out.println System.exit
Math.pow Math.random
input.nextInt "some string".toUpper

 These methods are defined in the Java library


 In this chapter, you learn how to create your own methods!
© Dr. Jonathan Cazalas Chapter 6: Methods page 8
Defining a Method
 A method consists of:
– method name
– parameters
– return value type
– Body

 Syntax:
modifier returnValueType methodName(list of parameters) {
// Method body
}

© Dr. Jonathan Cazalas Chapter 6: Methods page 9


Defining a Method
 Sample method:
– We will now look at a sample method
– This method is VERY easy
 Given two integers, find the larger value
– Although the logic is easy, we will study this sample
method in detail
– We need to understand the anatomy of a method
 anatomy: a study of the structure or internal workings of
something
 In summary: we need to fully understand all components of
the method and how it works!
© Dr. Jonathan Cazalas Chapter 6: Methods page 10
Defining a Method
 Sample method:
– Given two integers, determine the maximum value

© Dr. Jonathan Cazalas Chapter 6: Methods page 11


Defining a Method
 Method Header:
– Specifies the modifiers, return value type, method
name, and parameters of the method

© Dr. Jonathan Cazalas Chapter 6: Methods page 12


Defining a Method
 Modifiers:
– The static modifier is used for all methods in 202
 the reason will be discussed later

© Dr. Jonathan Cazalas Chapter 6: Methods page 13


Defining a Method
 Return Value:
– Some methods compute a value and return it
 returnValueType is the data type of the return value

© Dr. Jonathan Cazalas Chapter 6: Methods page 14


Defining a Method
 Return Value:
– Some methods compute a value and return it
 returnValueType is the data type of the return value
– Other methods perform operations but do not return a
value
 In this case, returnValueType is the keyword void.
 Example:
– The returnValueType is void in the main method.
– If a method returns a value, it is called a value-
returning method
– Else, it is called a void method
© Dr. Jonathan Cazalas Chapter 6: Methods page 15
Defining a Method
 Formal Parameters:
– These are the variables defined in the method header
 Think of formal parameters as placeholders

© Dr. Jonathan Cazalas Chapter 6: Methods page 16


Defining a Method
 Actual Parameters:
– When a method is invoked, you must send actual
values, which are then saved as formal parameters

© Dr. Jonathan Cazalas Chapter 6: Methods page 17


Defining a Method
 Actual Parameters:
– When a method is invoked, you must send actual
values, which are then saved as formal parameters
– These actual (real) values are called actual parameters
– Note:
 You can use the word "parameters" or the word "arguments"
 BOTH are well-known
– The parameter list (or the argument list) refers to the
method's type, order, and number of parameters

© Dr. Jonathan Cazalas Chapter 6: Methods page 18


Defining a Method
 Parameters:
– The parameter list (or the argument list) refers to the
method's type, order, and number of parameters
– Parameters are optional
– This means that some methods may have no
parameters
– In fact, you know some methods already, which have
no parameters:
 Math.random()
– There are no parameters for the Math.random() method

© Dr. Jonathan Cazalas Chapter 6: Methods page 19


Defining a Method
 Method Signature:
– The method name and the parameter list together
constitute the method signature.

© Dr. Jonathan Cazalas Chapter 6: Methods page 20


Defining a Method
 Method Body:
– Collection of statements that implement the method

© Dr. Jonathan Cazalas Chapter 6: Methods page 21


Calling a Method
 Remember:
– A method is a collection of statements grouped
together to perform an action
– So inside the method, you define the actions
 You "do" everything that you want the method to "do"
 Question:
– How do we "start" the method? How do we run it?
 Answer:
– We call or invoke the method.

© Dr. Jonathan Cazalas Chapter 6: Methods page 22


Calling a Method
 Two ways to call a method, depending on
whether the method returns a value or not
1. If the method returns a value, the "call" is usually
treated as a value:
 Example:
int larger = max(3, 4);
– Here, we "call" the method, max(3, 4)
– The maximum number, which is 4, will get returned
– We save that value (4) into the variable larger
 Example:
System.out.println(max(3, 4));
– Here, we directly print the result, which is 4

© Dr. Jonathan Cazalas Chapter 6: Methods page 23


Calling a Method
 Two ways to call a method, depending on
whether the method returns a value or not
2. If the method returns void, the "call" to the method
is a basic statement.
 Example of the println() method:
System.out.println("This is a parameter.");
– Here, we "call" the println() method
– We send over the String, "This is a parameter"
– That method receives the string and prints to output

© Dr. Jonathan Cazalas Chapter 6: Methods page 24


Calling a Method
 Program Control
– When you run a program, the control of the program
is in "main" (the main method)
 This is called program control
– When your call a method from main, program control
is transferred to the method you called
– main is basically waiting for the method to finish
 Once the method finishes, program control returns to main
 A called method returns control to the caller
– when its return statement is executed, or
– when its method-ending closing brace is reached

© Dr. Jonathan Cazalas Chapter 6: Methods page 25


Program 2: TestMax
 Write a program that will call another method,
max, to determine the maximum of two
numbers. Method max should return the
maximum value.
 Remember:
– Step 1: Problem-solving Phase
– Step 2: Implementation Phase

© Dr. Jonathan Cazalas Chapter 6: Methods page 26


Program 2: TestMax
 Step 1: Problem-solving Phase
– Algorithm:
 In main, we just make two integers and give a value
– Of course, we could ask the user for two numbers
– Or we could generate two random numbers
• These are easy things and are not the purpose of this example
 Next, we call the max method
 This means we need to write a max method!
– max method should be easy
– Just check which number is larger
– Save the larger number into a variable
– Finally, return that variable (the larger number)

© Dr. Jonathan Cazalas Chapter 6: Methods page 27


Program 2: TestMax
 Step 2: Implementation

© Dr. Jonathan Cazalas Chapter 6: Methods page 28


Program 2: TestMax
 Step 2: Implementation Details

– main method is from


lines 3 – 9
– On line 6, main calls
method max
– Method max is from
lines 12 – 21
– On line 21, result
is returned to main
© Dr. Jonathan Cazalas Chapter 6: Methods page 29
Program 2: TestMax
 Run the Program:

Click here to view and trace code


© Dr. Jonathan Cazalas Chapter 6: Methods page 30
animation

Calling Methods, cont.

pass the value of i


pass the value of j

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

© Dr. Jonathan Cazalas Chapter 6: Methods page 31


animation

Trace Method Invocation


i is now 5

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

© Dr. Jonathan Cazalas Chapter 6: Methods page 32


animation

Trace Method Invocation


j is now 2

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

© Dr. Jonathan Cazalas Chapter 6: Methods page 33


animation

Trace Method Invocation


invoke max(i, j)

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

After this line executes, program control go to method max.

© Dr. Jonathan Cazalas Chapter 6: Methods page 34


animation

Trace Method Invocation


invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2

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

Program control is now at method max.

© Dr. Jonathan Cazalas Chapter 6: Methods page 35


animation

Trace Method Invocation


declare variable result

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

© Dr. Jonathan Cazalas Chapter 6: Methods page 36


animation

Trace Method Invocation


(num1 > num2) is true since num1
is 5 and num2 is 2

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

© Dr. Jonathan Cazalas Chapter 6: Methods page 37


animation

Trace Method Invocation


result is now 5

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

© Dr. Jonathan Cazalas Chapter 6: Methods page 38


animation

Trace Method Invocation


return result, which is 5

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

Now, the maximum value is returned.


Program control returns to main.

© Dr. Jonathan Cazalas Chapter 6: Methods page 39


animation

Trace Method Invocation


return max(i, j) and assign the
return value to k

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

© Dr. Jonathan Cazalas Chapter 6: Methods page 40


animation

Trace Method Invocation


Execute the print statement

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

© Dr. Jonathan Cazalas Chapter 6: Methods page 41


Caution
 A return statement is required for a value-
returning method
 Consider the following method:
– This method is 100% public static int sign(int n) {
if (n > 0)
logically correct return 1;
– However, it will give else if (n == 0)
return 0;
a compile error! else if (n < 0)
return -1;
– Why? }

© Dr. Jonathan Cazalas Chapter 6: Methods page 42


Caution
 Why does this method give a compile error?
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else if (n < 0)
return -1;
}

 Java sees that this method must return an int


 Java makes sure that a value must always be returned
 Java does not allow the possibility that a value will not be
returned
 If this possibility exists, Java will give a compile error
© Dr. Jonathan Cazalas Chapter 6: Methods page 43
Caution
 Why does this method give a compile error?
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else if (n < 0)
return -1;
}

 Yes, this code is logically correct for us


– Clearly, n can only be bigger than 0, equal, or less than zero
 However, Java sees the if/elseif/elseif block and Java
expects that "maybe" there can be an "else" statement
 And if that else statement is true, Java has no guarantee that
we will return inside that statement…therefore, an error
© Dr. Jonathan Cazalas Chapter 6: Methods page 44
Caution
 Why does this method give a compile error?
– In summary: Java thinks it is possible that this method
will not return a value.
– An easy solution is presented below:

 We simply remove the condition of the final else if


statement, indicating that this is the final option
© Dr. Jonathan Cazalas Chapter 6: Methods page 45
Calling a Method
 Activation Record:
– Each time a method is called, the system creates an
activation record
– The activation record stores all parameters and
variables for the method.
– The activation record is then placed in a specific area
of memory known as a call stack.
 aka "execution stack", "machine stack" or just "the stack"

© Dr. Jonathan Cazalas Chapter 6: Methods page 46


Calling a Method
 Activation Record:
– When methodA calls methodB, for example, the
activation record for methodA is kept intact
 A new activation record for methodB is created for this
new methodB that was just called
 When methodB finishes its work and returns to the caller,
which was methodA, the activation record of methodB is
then removed from the stack of records
 Why?
– Because methodB is finished!
– Confused? Let us see an example…

© Dr. Jonathan Cazalas Chapter 6: Methods page 47


animation

Trace Call Stack


i is declared and initialized

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; i: 5

if (num1 > num2)


result = num1; The main method
else is invoked.
result = num2;
return result;
}

© Dr. Jonathan Cazalas Chapter 6: Methods page 48


animation

Trace Call Stack


j is declared and initialized

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) { j: 2


int result; i: 5

if (num1 > num2)


result = num1; The main method
else is invoked.
result = num2;
return result;
}

49 page 49
© Dr. Jonathan Cazalas Chapter 6: Methods
animation

Trace Call Stack


Declare k

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);
} Space required for the
main method
k:
public static int max(int num1, int num2) { j: 2
int result; i: 5

if (num1 > num2)


result = num1; The main method
else is invoked.
result = num2;
return result;
}

50 page 50
© Dr. Jonathan Cazalas Chapter 6: Methods
animation

Trace Call Stack


Invoke max(i, j)

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);
} Space required for the
main method
k:
public static int max(int num1, int num2) { j: 2
int result; i: 5

if (num1 > num2)


result = num1; The main method
else is invoked.
result = num2;
return result;
}

51 page 51
© Dr. Jonathan Cazalas Chapter 6: Methods
animation

Trace Call Stack


pass the values of i and j to num1
and num2

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); num2: 2
} num1: 5
Space required for the
public static int max(int num1, int num2) {
int result; main method
k:
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;
return result; The max method is
} invoked.

52 page 52
© Dr. Jonathan Cazalas Chapter 6: Methods
animation

Trace Call Stack

Declare result

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
System.out.println(
"The maximum between " + i + result:
" and " + j + " is " + k); num2: 2
} num1: 5
Space required for the
public static int max(int num1, int num2) {
int result; main method
k:
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;
return result; The max method is
} invoked.

53 page 53
© Dr. Jonathan Cazalas Chapter 6: Methods
animation

Trace Call Stack

(num1 > num2) is true

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
System.out.println(
"The maximum between " + i + result:
" and " + j + " is " + k); num2: 2
} num1: 5
Space required for the
public static int max(int num1, int num2) {
int result; main method
k:
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;
return result; The max method is
} invoked.

54 page 54
© Dr. Jonathan Cazalas Chapter 6: Methods
animation

Trace Call Stack

Assign num1 to result

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
Space required for the
System.out.println( max method
"The maximum between " + i + result: 5
" and " + j + " is " + k); num2: 2
} num1: 5
Space required for the
public static int max(int num1, int num2) {
int result; main method
k:
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;
return result; The max method is
} invoked.

55 page 55
© Dr. Jonathan Cazalas Chapter 6: Methods
animation

Trace Call Stack

Return result and assign it to k

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
Space required for the
System.out.println( max method
"The maximum between " + i + result: 5
" and " + j + " is " + k); num2: 2
} num1: 5
Space required for the
public static int max(int num1, int num2) {
int result; main method
k:5
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;
return result; The max method is
} invoked.

56 page 56
© Dr. Jonathan Cazalas Chapter 6: Methods
animation

Trace Call Stack


Execute print statement

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);
} Space required for the
main method
k:5
public static int max(int num1, int num2) { j: 2
int result; i: 5

if (num1 > num2)


result = num1; The main method
else is invoked.
result = num2;
return result;
}

57 page 57
© Dr. Jonathan Cazalas Chapter 6: Methods
Calling a Method
 Activation Record and Call Stacks:
– While the last animated example was great, here is a
single image that shows the full process:

© Dr. Jonathan Cazalas Chapter 6: Methods page 58


void Method Example
 The previous example (max method) was a
value-returning method
– meaning, it returned a value (the max) to the caller
 Some methods do not return anything at all
 This type of method is called a void method
 The following program defines a method named
printGrade and invokes (calls) it to print the
grade based on a given score

© Dr. Jonathan Cazalas Chapter 6: Methods page 59


Program 3: TestVoidMethod

© Dr. Jonathan Cazalas Chapter 6: Methods page 60


Program 3: TestVoidMethod
 Run the Program:

– The printGrade method is void


 It does not return any value at all.
– A call to a void method must be a statement
– You can see it is invoked as a statement in line 4
– And like any Java statement, it ends with a semicolon

Click here to view and trace code


© Dr. Jonathan Cazalas Chapter 6: Methods page 61
Program 4: TestReturnGradeMethod
 Redesign the printGrade method to return a
value. The new method, getGrade, should return
the letter grade as a char value.
 Remember:
– Step 1: Problem-solving Phase
– Step 2: Implementation Phase

© Dr. Jonathan Cazalas Chapter 6: Methods page 62


Program 4: TestReturnGradeMethod
 Step 1: Problem-solving Phase
– Algorithm:
 Same algorithm as the previous example.
 We will call the method and we will send over the numeric
grade as a parameter
 But instead of directly printing the value inside the
method
 We will return the value as a char!

© Dr. Jonathan Cazalas Chapter 6: Methods page 63


Program 4: TestReturnGradeMethod
 Step 2: Implementation

© Dr. Jonathan Cazalas Chapter 6: Methods page 64


Program 4: TestReturnGradeMethod
 Step 2: Implementation Details

– notice the return type for


the getGrade method
 char
– On line 3 and 4, we call the
getGrade method
– The answer is computed
inside the method, and then
returned and printed
© Dr. Jonathan Cazalas Chapter 6: Methods page 65
Program 4: TestReturnGradeMethod
 Run the Program:

Click here to view and trace code


© Dr. Jonathan Cazalas Chapter 6: Methods page 66
void Method Example
 Note:
– the return statement is not needed for void method
– However, it can be useful for terminating the method
and returning to the method's caller
– Syntax:
return;
– This is not too common
 However, it is useful for exiting the normal flow of control in
a void method
– Consider the following code, which uses a void
method to terminate if the score is invalid
© Dr. Jonathan Cazalas Chapter 6: Methods page 67
void Method Example
 void Method with return statement:
public static void printGrade(double score) {
if (score < 0 || score > 100) {
System.out.println("Invalid score");
return;
}
if (score >= 90.0) {
System.out.println('A');
}
else if (score >= 80.0) {
System.out.println('B');
}
else if (score >= 70.0) {
System.out.println('C');
}
else if (score >= 60.0) {
System.out.println('D');
}
else {
System.out.println('F');
}
}

© Dr. Jonathan Cazalas Chapter 6: Methods page 68


Check Point
 What are the benefits of using a method?

 Can a call to a value-returning method be a


statement by itself?

 Can you have a return statement in a void


method?

© Dr. Jonathan Cazalas Chapter 6: Methods page 69


Passing Arguments by Values
 Power of a method is in its ability to work with
parameters
 When you call a method, you need to provide
the arguments (parameters)
– And these parameters MUST be given in the same
order as their respective parameters in the method
signature
– This is known as parameter order association

© Dr. Jonathan Cazalas Chapter 6: Methods page 70


Passing Arguments by Values
 Example:
– We know the println() method works by taking one
String parameter
 Then it prints that String to the console
– What if we wanted to make a new println() method
– But this method will take two parameters
 The String itself
 And an integer, n, representing the number of times the
method should print the String

© Dr. Jonathan Cazalas Chapter 6: Methods page 71


Passing Arguments by Values
 Example:
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}

– What happens if we call nPrintn("Hello", 3)


 Answer: we will print the world "Hello" three times
– The String parameter, "Hello" is passed into the formal
parameter, String message
– And the value 3 is passed to the formal parameter, n

© Dr. Jonathan Cazalas Chapter 6: Methods page 72


Passing Arguments by Values
 Example:
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}

– How would we print the specialty "Computer Science"


100 times?
nPrintn("Computer Science", 100);
– Note, the following statement would be wrong:
nPrintn(100, "Computer Science");
– Why?

© Dr. Jonathan Cazalas data types of the actual/formal
Chapter 6: Methods parameters do not match page 73
Passing Arguments by Values
 Caution:
– Arguments send from the caller MUST match the
formal parameter with respect to:
 The number of parameters
 The order of parameters
 The compatible type of parameters
– Here, compatible simply means that you can pass an argument to a
parameter without explicit casting
– Such as passing an int to a double
• This is allowed
– But of course, we cannot pass a double to an int
• Unless there was explicit casting

© Dr. Jonathan Cazalas Chapter 6: Methods page 74


Passing Arguments by Values
 Remember:
– When you invoke a method with an argument, the
value of the argument is passed/sent to the formal
parameter inside the method
– This is referred to as pass-by-value
– Even if the argument is a variable, the value of the
variable is passed to the formal parameter
– The variable, therefore, is not affected regardless of
any changes made to the parameter inside the method
– Consider the following example…

© Dr. Jonathan Cazalas Chapter 6: Methods page 75


Passing Arguments by Values
 Remember:

Click here to
view and trace
code

© Dr. Jonathan Cazalas Chapter 6: Methods page 76


Passing Arguments by Values
 And another example:
– We have seen that swapping the values of two
variables is a common practice
 So let us write a method to do this!
– Consider the following program that creates a method
for swapping the values of two variables
 So we will make a custom swap method
– We invoke the swap method by passing 2 arguments
– Interesting:
 The values of the arguments are NOT changed after the
method is invoked
© Dr. Jonathan Cazalas Chapter 6: Methods page 77
Passing Arguments by Values
 And another example:

© Dr. Jonathan Cazalas Chapter 6: Methods page 78


Passing Arguments by Values
 And another example:

© Dr. Jonathan Cazalas Chapter 6: Methods page 79


Passing Arguments by Values
 And another example:
– Output:

Click here to view and trace code


© Dr. Jonathan Cazalas Chapter 6: Methods page 80
Passing Arguments by Values
 swap Method Explanation:
– Before swap method is invoked (line 12) num1 is 1
and num2 is 2
– After the swap method is invoked, num1 is still 1 and
num2 is still 2.
 Their values have NOT been swapped!
– Why?
 Values in a method have their own memory locations
 Therefore, any changes made inside the method do NOT
affect the original variables outside the method

© Dr. Jonathan Cazalas Chapter 6: Methods page 81


Passing Arguments by Values
 swap Method Explanation:
– Common question:
 "In this example, the variables names were different when
we look at the formal and actual parameters. Would it make a
difference if the names were the same?
– Answer:
 No. Nothing will change.
 The parameter is a variable in the method with its own
memory space.
– Consider the following Activation Record for swap

© Dr. Jonathan Cazalas Chapter 6: Methods page 82


Passing Arguments by Values
 Activation Record for swap:

© Dr. Jonathan Cazalas Chapter 6: Methods page 83


Check Point
 What is the output of the following programs:

© Dr. Jonathan Cazalas Chapter 6: Methods page 84


Check Point
 What is the output of the following programs:

© Dr. Jonathan Cazalas Chapter 6: Methods page 85


Modularizing Code
 What is the idea of modularizing code?
– To answer this, let us ask another question:
What is a module?
– Answer: a sub-group of a larger entity
– For example, you have a Chapter in your book, and
then inside the chapter, maybe you have 8 modules
– These are small, independent sections of the Chapter
 Imagine if the chapter did not have modules, and
you were told to “modularize the chapter”.
– This means, divide the chapter into modules!
© Dr. Jonathan Cazalas Chapter 6: Methods page 86
Modularizing Code
 What is the idea of modularizing code?
– This same idea applies to code
– New programmers often write long un-modularized
code, which is very difficult to read
– So we tell them: modularize the code!
– This makes the code easier:
 To maintain
 To read
 To debug
 and a best of all, it makes the code reusable!

© Dr. Jonathan Cazalas Chapter 6: Methods page 87


Modularizing Code
 Use of methods:
– We already learned that methods can be used to reduce
redundant code and they facilitate reuse of code
– Methods are also used to modularize code and to help
improve the overall quality of the program
 GCD (modularized)
– In Chapter 5, we wrote a program to find the GCD of
two integers
– We can now re-write the program in a modularized
fashion by using a method to compute the GCD
© Dr. Jonathan Cazalas Chapter 6: Methods page 88
Modularizing Code (GCD)
 GCD (modularized)

© Dr. Jonathan Cazalas Chapter 6: Methods page 89


Modularizing Code (GCD)
 GCD (modularized) Click here to view and trace code

© Dr. Jonathan Cazalas Chapter 6: Methods page 90


Modularizing Code (GCD)
 Run the Program: Click here to view and trace code

– We encapsulated the GCD code inside a method


– Benefits:
 Isolates the GCD computation from the rest of the program
 Possible errors on GCD are limited to GCD method
– makes debugging easier
 GCD method can now be reused by other programs
© Dr. Jonathan Cazalas Chapter 6: Methods page 91
Program 5: PrimeNumberMethod
 Write a modularized program, which should
print the first 50 prime numbers, with ten
numbers printed per line
 Remember:
– Step 1: Problem-solving Phase
– Step 2: Implementation Phase

© Dr. Jonathan Cazalas Chapter 6: Methods page 92


Program 5: PrimeNumberMethod
 Step 1: Problem-solving Phase
– Algorithm:
 We really have two things to consider for this program:
1. We need to determine if a number is prime
2. We need to print 10 prime numbers per line
 And we can do both of these steps with methods
 We can make a method, isPrime, to determine prime
 And we can make another method that is used specifically
to print the numbers, printPrimeNumbers

© Dr. Jonathan Cazalas Chapter 6: Methods page 93


Program 5: PrimeNumberMethod
 Step 1: Problem-solving Phase
– Algorithm:
 In Chapter 5, we showed how to determine if a # is prime:

// Use a boolean variable isPrime and set initially to true


boolean isPrime = true;

for (int divisor = 2; divisor <= number/2; divisor++) {


// IF divisor evenly divides into number, number is NOT prime
if (number % divisor == 0) {
isPrime = false;
break; // Exit/break out of loop!
}
}

© Dr. Jonathan Cazalas Chapter 6: Methods page 94


Program 5: PrimeNumberMethod
 Step 1: Problem-solving Phase
– Algorithm:
 Method printPrimeNumbers
– We can keep a final variable: NUMBER_OF_PRIMES_PER_LINE
 We keep a counter to count the number of primes found
 We use the same while loop from Chapter 5
while (count < numberOfPrimes)
 We start with the number 2, and check if it is prime
 If so, we increment count
 Of course, we increment the tested value
 And we continue until we find the desired # of primes

© Dr. Jonathan Cazalas Chapter 6: Methods page 95


Program 5: PrimeNumberMethod
 Step 2: Implementation

© Dr. Jonathan Cazalas Chapter 6: Methods page 96


Program 5: PrimeNumberMethod
 Step 2: Implementation

© Dr. Jonathan Cazalas Chapter 6: Methods page 97


Program 5: PrimeNumberMethod
 Run the Program:

Click here to view and trace code


© Dr. Jonathan Cazalas Chapter 6: Methods page 98
Overloading Methods
 What is method overloading?
– Method overloading is when you have multiple
methods with the SAME method name
– However, the method signature is different
– This means that the number of parameters will be
different or the data types of the parameters will be
different

© Dr. Jonathan Cazalas Chapter 6: Methods page 99


Overloading Methods
 Example max method:
– Previously, we made a max method to find the max
value of two integers
– What if the two values were doubles?
– Solution:
 Create another method with the same name
 The only difference is that the data type of the parameters
will be double
– So now your program has two max methods
 One that works with integers and one that works for doubles

© Dr. Jonathan Cazalas Chapter 6: Methods page 100


Overloading Methods
 Example max method:
– So now if you call the max method with two integers,
the specific method that expects two integers will be
invoked
– And if you call the max method with two doubles, the
specific method that expects two doubles will be
invoked
– This is referred to as method overloading
– The Java compiler determines which method to use
based on the method signature

© Dr. Jonathan Cazalas Chapter 6: Methods page 101


Program 6: TestMethodOverloading
 Write a program that finds the max of two
integers, the max of two doubles, and the max of
three doubles
 Remember:
– Step 1: Problem-solving Phase
– Step 2: Implementation Phase

© Dr. Jonathan Cazalas Chapter 6: Methods page 102


Program 6: TestMethodOverloading
 Step 1: Problem-solving Phase
– Algorithm:
 We need three methods
 And all of them will be called max!
 One will compute max of two integers
 One will compute max of two doubles
 One will compute max of three doubles

© Dr. Jonathan Cazalas Chapter 6: Methods page 103


Program 6: TestMethodOverloading
 Step 2: Implementation

© Dr. Jonathan Cazalas Chapter 6: Methods page 104


Program 6: TestMethodOverloading
 Step 2: Implementation

© Dr. Jonathan Cazalas Chapter 6: Methods page 105


Program 6: TestMethodOverloading
 Run the Program:

Click here to view and trace code


© Dr. Jonathan Cazalas Chapter 6: Methods page 106
Ambiguous Invocation
 What is Ambiguous Invocation?
– Sometimes there are two (or more) possible methods
that match the invocation (the method call)
– The result: the compiler cannot determine which
method should be used
– This is referred to as ambiguous invocation
 ambiguous means “not clear”
– Ambiguous invocations will cause a compile error

© Dr. Jonathan Cazalas Chapter 6: Methods page 107


Ambiguous Invocation
 Example:
public 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;
}
}

© Dr. Jonathan Cazalas Chapter 6: Methods page 108


Ambiguous Invocation
 Example:
– So in this Class, we have two max methods
– Both have two parameters:
 The 1st has: int and double
 The 2nd method has: double and int
– Neither method is better than the other
– In summary: the compiler cannot choose a “best”
option
– Result: compiler error

© Dr. Jonathan Cazalas Chapter 6: Methods page 109


Check Point
 What is wrong in the following program:
public class Test {
public static void someMethod(int x) {

public static int someMethod(int y) {


return y;
}
}

– Signatures MUST be different


– Here, they are the same!
© Dr. Jonathan Cazalas Chapter 6: Methods page 110
Check Point
 Given two method definitions:
public static double m(double x, double y)

public static double m(int x, double y)

tell which of the two methods is invoked for:


a) double z = m(4, 5);
b) double z = m(4, 5.4);
c) double z = m(4.5, 5.4);

© Dr. Jonathan Cazalas Chapter 6: Methods page 111


Scope of Local Variables
 Reminder from Chapter 2:
– The scope of a variable is the part of the program
where the variable is understood
 While we discussed “scope” previously, we now discuss it in
more detail!
 A variable declared inside a method is referred to as a local
variable
 The scope of a local variable begins from the declaration and
continues until the end of the block that contains the variable
 A local variable must be declared and assigned a value
before it can be used

© Dr. Jonathan Cazalas Chapter 6: Methods page 112


Scope of Local Variables
 Scope details:
– A parameter is a local variable
– And a parameter is “declared” inside the method
signature
 This means the scope of parameters are for the entire
method!
– A variable declared in the initial-action part of a for
loop has its scope in the entire loop
– However, a variable declared inside a for-loop body
has its scope limited inside the loop body
 from the declaration to the end of the for-loop block
© Dr. Jonathan Cazalas Chapter 6: Methods page 113
Scope of Local Variables
 Scope details:

© Dr. Jonathan Cazalas Chapter 6: Methods page 114


Scope of Local Variables
 Scope details:
– You can declare a local variable with the same name in
different blocks in a method.
 So even though the name is the same, you can do this with
the condition IF it is in different blocks in the method
– You cannot declare a local variable twice within the
same block or in nested blocks

– Consider the following picture…

© Dr. Jonathan Cazalas Chapter 6: Methods page 115


Scope of Local Variables
 Scope details:

© Dr. Jonathan Cazalas Chapter 6: Methods page 116


Program 7: RandomCharacter
 Write a class, which has methods to generate a
random character, a random lowercase letter, a
random uppercase letter, and a random digit
character. Then write a program to print 175
random lowercase letters.
 Remember:
– Step 1: Problem-solving Phase
– Step 2: Implementation Phase

© Dr. Jonathan Cazalas Chapter 6: Methods page 117


Program 7: RandomCharacter
 Step 1: Problem-solving Phase
– Reminder:
 A character is coded using an integer
 So generating a random character really means generating
a random integer!
 Remember: every possible character has a Unicode value
between 0 and FFFF in hexadecimal (65535 in decimal)
 So generating a random character really means generating
a random decimal value between 0 and 65535 inclusive
(int) (Math.random() * (65535 + 1))

© Dr. Jonathan Cazalas Chapter 6: Methods page 118


Program 7: RandomCharacter
 Step 1: Problem-solving Phase
– Details:
 So how do we generate a random lowercase letter?
 Well, you can either remember the exact decimal values for
each character (hard to remember)
 OR you can just cast the character values as ints
(int) ‘a’
– For example, the line above will give us the integer value of ‘a’
 So we want a random integer between (int) ‘a’ and (int) ‘z’
 Solution:
(int)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1))

© Dr. Jonathan Cazalas Chapter 6: Methods page 119


Program 7: RandomCharacter
 Step 1: Problem-solving Phase
– Details:
 It is actually even easier than this though!
 All numeric operators can be applied to char operands
 The char operand will be implicitly cast to an int if the other
operand is an int or a char
 Therefore, the previous expression can be simplified to:
'a' + Math.random() * ('z' - 'a' + 1)
 And a random lowercase letter is:
(char)('a' + Math.random() * ('z' - 'a' + 1))

© Dr. Jonathan Cazalas Chapter 6: Methods page 120


Program 7: RandomCharacter
 Step 1: Problem-solving Phase
– Details:
 This allows us to realize a very simply but useful discovery:
 A random character between any two characters, ch1 and ch2
(with ch1 < ch2) can be generated as follows:
(char)(ch1 + Math.random() * (ch2 – ch1 + 1))
 So now we can make a generic method, which will have two
characters as parameters
 And this generic method will generate the random character
between those two character parameters
 We now make a class with five overloaded methods to get a
certain type of character randomly
© Dr. Jonathan Cazalas Chapter 6: Methods page 121
Program 7: RandomCharacter
 Step 2: Implementation

© Dr. Jonathan Cazalas Chapter 6: Methods page 122


Program 7: RandomCharacter
 Step 2: Implementation

© Dr. Jonathan Cazalas Chapter 6: Methods page 123


Program 7: RandomCharacter
 Step 1: Problem-solving Phase
– Algorithm:
 So now we need to solve the original problem:
Print 175 random lowercase letters
– Only 25 letters per line
 This is easy!
 We will have a loop, and inside the loop, we will simply call
our method each time, of course with ‘a’ and ‘z’ as
parameters

© Dr. Jonathan Cazalas Chapter 6: Methods page 124


Program 7: RandomCharacter
 Step 2: Implementation

© Dr. Jonathan Cazalas Chapter 6: Methods page 125


Program 7: RandomCharacter
 Run the Program:

Click here to view and trace code


© Dr. Jonathan Cazalas Chapter 6: Methods page 126
Method Abstraction
 Main idea for developing software!
– To develop quality software, programmers must fully
understand and be comfortable with the idea of method
abstraction
 What is method abstraction?
– We separate the implementation of a method from the
actual use of the method
– The client/customer can use a method without knowing
how to actually code it
– The details of the method are hidden from the client
© Dr. Jonathan Cazalas Chapter 6: Methods page 127
Method Abstraction
 Information Hiding (Encapsulation)
– Again, the details of the implementation are
encapsulated inside the method
– And they are hidden from the client
– This is called Information Hiding or encapsulation
– The client has access to the method header
 They can call the method with certain parameters
 And they hope to get a return value from the method
– But what is inside the method is hidden from them
– In fact, they don’t care…they just want it to work!
© Dr. Jonathan Cazalas Chapter 6: Methods page 128
Method Abstraction
 Information Hiding (Encapsulation)
– So think of the method as a “BLACK BOX” that
contains the implementation…but it is hidden

© Dr. Jonathan Cazalas Chapter 6: Methods page 129


Stepwise Refinement
 Method Abstraction helps makes programs easier
– because the implementation of a specific idea is
removed from the main body of the program
– So the program is easier to read and understand
 This idea is part of Stepwise Refinement
 What is stepwise refinement?
– The idea of solving a larger problem/program in
smaller steps
– Certainly, solving something small is easier than
solving something larger
© Dr. Jonathan Cazalas Chapter 6: Methods page 130
Stepwise Refinement
 Method Abstraction helps makes programs easier
– because the implementation of a specific idea is
removed from the main body of the program
– So the program is easier to read and understand
 This idea is part of Stepwise Refinement
 What is stepwise refinement?
– The idea of solving a larger problem/program in
smaller steps
– Certainly, solving something small is easier than
solving something larger
© Dr. Jonathan Cazalas Chapter 6: Methods page 131
Program 8: PrintCalendar
 Write a program that prompts the user to enter
the calendar year and month and then displays
the exact calendar for that input.

 Remember:
– Step 1: Problem-solving Phase
– Step 2: Implementation Phase

© Dr. Jonathan Cazalas Chapter 6: Methods page 132


Program 8: PrintCalendar
 Step 1: Problem-solving Phase
– Expected output:

© Dr. Jonathan Cazalas Chapter 6: Methods page 133


Program 8: PrintCalendar
 Step 1: Problem-solving Phase
– Requirements:
 First requirement: do NOT START CODING!!!
 New programmers want to start code right away
 And they also care about the DETAILS of the program
 Yes, details are important…but not at the beginning
– The main requirement is to truly understand what the
programming is asking of you
– So for this problem, let us use method abstraction to
isolate the details from the actual program design

© Dr. Jonathan Cazalas Chapter 6: Methods page 134


Program 8: PrintCalendar
 Step 1: Problem-solving Phase
– Problem Components:
 We can start by breaking the program into two main
components:
– Get input from user
– Print the calendar

 Clearly, getting input from the user is easy and can be left for
later discussion
 The main work is in printing the calendar
© Dr. Jonathan Cazalas Chapter 6: Methods page 135
Program 8: PrintCalendar
 Step 1: Problem-solving Phase
– Problem Components:
 And printing the calendar can also be broken down into two
components:
– Print the month title
– Print the month body

 Printing the month title is easy


– It consists of three lines, month and year, a long dashed line, and
then the names of the week
– The only “calculation” here is determining the name of the month
© Dr. Jonathan Cazalas Chapter 6: Methods page 136
Program 8: PrintCalendar
 Step 1: Problem-solving Phase
– Problem Components:
 Printing the month body will take some thought
 There are two main things we must compute
– Starting day of month
– # of days in month

 So how can you get the starting day of the month?


– This problem on its own can be complicated and requires its own
thought and strategy

© Dr. Jonathan Cazalas Chapter 6: Methods page 137


Program 8: PrintCalendar
 Step 1: Problem-solving Phase
– So how can you get the starting day of the month?
 Assume we know that the start day for January 1, 1800 was a
Wednesday
START_DAY_FOR_JAN_1_1800 = 3
 You could compute the total number of days between
January 1, 1800 and the first date of the calendar month
 The start day of the calendar month is:
(totalNumberOfDays + START_DAY_FOR_JAN_1_1800) % 7
 Summary: the problem of getting the starting day can be
further broken down into the problem of getting the total
number of days since January 1, 1800
© Dr. Jonathan Cazalas Chapter 6: Methods page 138
Program 8: PrintCalendar
 Step 1: Problem-solving Phase
– Okay. So how can we get the total number of days?
 Simple, each year is 365 days.
 And then for the last year, you must count the number of
days before that specific month
 This means you need to save the number of days in each
month
– And you can write a separate method for this
 But wait! There is something else to consider!
 LEAP YEAR!
 So you must also test for a leap year

© Dr. Jonathan Cazalas Chapter 6: Methods page 139


Program 8: PrintCalendar
 Step 1: Problem-solving Phase
– Method getNumberOfDaysInMonth():
public static int getNumberOfDaysInMonth(int year, int month) {
if (month == 1 || month == 3 || month == 5 || month == 7 ||
month == 8 || month == 10 || month == 12)
return 31;

if (month == 4 || month == 6 || month == 9 || month == 11)


return 30;

if (month == 2)
return isLeapYear(year) ? 29 : 28;
return 0; // If month is incorrect
}

/** Determine if it is a leap year */


public static boolean isLeapYear(int year) {
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}

© Dr. Jonathan Cazalas Chapter 6: Methods page 140


Program 8: PrintCalendar
 Step 1: Problem-solving Phase
– So you can see that many components are needed to
solve this problem
– You cannot just start coding immediately
– Instead, you must identify, step-by-step, or component-
by-component, what is needed for your program
– What we just did was called the “Top-Down
Approach”
– The design diagram is shown on the next pages

© Dr. Jonathan Cazalas Chapter 6: Methods page 141


Design Diagram
printCalendar
(main)

readInput printMonth

printMonthTitle printMonthBody

getMonthName getStartDay

getTotalNumOfDays

getNumOfDaysInMonth

isLeapYear

© Dr. Jonathan Cazalas Chapter 6: Methods page 142


Design Diagram
printCalendar
(main)

readInput printMonth

printMonthTitle printMonthBody

getMonthName getStartDay

getTotalNumOfDays

getNumOfDaysInMonth

isLeapYear

© Dr. Jonathan Cazalas Chapter 6: Methods page 143


Design Diagram
printCalendar
(main)

readInput printMonth

printMonthTitle printMonthBody

getMonthName getStartDay

getTotalNumOfDays

getNumOfDaysInMonth

isLeapYear

© Dr. Jonathan Cazalas Chapter 6: Methods page 144


Design Diagram
printCalendar
(main)

readInput printMonth

printMonthTitle printMonthBody

getMonthName getStartDay

getTotalNumOfDays

getNumOfDaysInMonth

isLeapYear

© Dr. Jonathan Cazalas Chapter 6: Methods page 145


Design Diagram
printCalendar
(main)

readInput printMonth

printMonthTitle printMonthBody

getMonthName getStartDay

getTotalNumOfDays

getNumOfDaysInMonth

isLeapYear

© Dr. Jonathan Cazalas Chapter 6: Methods page 146


Design Diagram
printCalendar
(main)

readInput printMonth

printMonthTitle printMonthBody

getMonthName getStartDay

getTotalNumOfDays

getNumOfDaysInMonth

isLeapYear

© Dr. Jonathan Cazalas Chapter 6: Methods page 147


Design Diagram
printCalendar
(main)

readInput printMonth

printMonthTitle printMonthBody

getMonthName getStartDay

getTotalNumOfDays

getNumOfDaysInMonth

isLeapYear

© Dr. Jonathan Cazalas Chapter 6: Methods page 148


Implementation: Top-Down
 Step 1: Problem-solving Phase
– Top-down approach is to implement one method in the
structure chart at a time from the top to the bottom.
 Stubs can be used for the methods waiting to be
implemented.
 A stub is a simple but incomplete version of a method.
 The use of stubs enables you to test invoking the method
from a caller.
 Implement the main method first and then use a stub for the
printMonth method and so on

Click here to view a skeleton of the code


© Dr. Jonathan Cazalas Chapter 6: Methods page 149
Program 8: PrintCalendar
 Run the Program:

Click here to view and trace code


© Dr. Jonathan Cazalas Chapter 6: Methods page 150
Benefits of Stepwise Refinement
 Some programs can be very long
– This last program was only 100 lines, but it had several
logically independent components
 Stepwise refinement breaks the larger problem
down into smaller, more manageable subproblems
 Each subproblem can be implemented using a
method
 This approach makes the program easier to:
– write, reuse, debug, test, modify, and maintain

© Dr. Jonathan Cazalas Chapter 6: Methods page 151


Benefits of Stepwise Refinement
 Reusing methods:
– Stepwise refinement encourages code reuse
– The isLeapYear method is defined once
– However, it is used twice:
 Inside the getTotalNumberOfDays
 Inside the getNumberOfDayInMonth

© Dr. Jonathan Cazalas Chapter 6: Methods page 152


Benefits of Stepwise Refinement
 Easier developing, debugging, and testing
– Each subproblem is developed in a method
– This means each subproblem can be developed,
debugged, and tested independently of other
components of the problem
– This isolates errors
– Whenever you develop large programs, use this
stepwise refinement approach
– It may seem to take longer at first
– But it saves time and makes debugging much easier!
© Dr. Jonathan Cazalas Chapter 6: Methods page 153
Chapter 6:
Methods

You might also like