Chapter 06
Chapter 06
Spring 2026
Chapter 6 Methods
1
Opening Problem
Find the sum of integers from 1 to 10, from 20 to 30, and
from 35 to 45, respectively.
2
Problem
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
[Link]("Sum from 1 to 10 is " + sum);
sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
[Link]("Sum from 20 to 30 is " + sum);
sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
[Link]("Sum from 35 to 45 is " + sum);
3
Problem
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
[Link]("Sum from 1 to 10 is " + sum);
sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
[Link]("Sum from 20 to 30 is " + sum);
sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
[Link]("Sum from 35 to 45 is " + sum);
4
Solution
public static int sum(int i1, int i2) {
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i;
return sum;
MethodDemo
MethodDemo
}
5
Defining Methods
return result;
}
6
Defining Methods
7
Method Signature
8
Formal Parameters
9
Actual Parameters
10
Return Value Type
A method may return a value. The returnValueType is the data type
of the value the method returns. If the method does not return a
value, the returnValueType is the keyword void. For example, the
returnValueType in the main method is void.
Define a method Invoke a method
11
Calling Methods
Testing the max method
This program demonstrates calling a method max
to return the largest of the int values
TestMax
TestMax
12
animation
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;
[Link]( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
13
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;
[Link]( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
14
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;
[Link]( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
15
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;
[Link]( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
16
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;
[Link]( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
17
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;
[Link]( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
18
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;
[Link]( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
19
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;
[Link]( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
20
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;
[Link]( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
21
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;
[Link]( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
22
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;
[Link]( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
23
CAUTION
A return statement is required for a value-returning method. The
method shown below in (a) is logically correct, but it has a
compilation error because the Java compiler thinks it possible that
this method does not return any value.
To fix this problem, delete if (n < 0) in (a), so that the compiler will
see a return statement to be reached regardless of how the if
statement is evaluated.
24
Reuse Methods from Other Classes
25
Call Stacks
26
animation
return result;
}
27
animation
return result;
}
28
animation
Declare k
return result;
}
29
animation
Invoke max(i, j)
return result;
}
30
animation
31
animation
Trace Call Stack
Declare result
32
animation
Trace Call Stack
33
animation
Trace Call Stack
34
animation
Trace Call Stack
35
animation
return result;
}
36
void Method Example
TestVoidMethod
TestVoidMethod
TestReturnGradeMethod
TestReturnGradeMethod
37
Passing Parameters
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
[Link](message);
}
Increment
Increment
39
Pass by Value
TestPassByValue
TestPassByValue
40
Pass by Value, cont.
41
Modularizing Code
Methods can be used to reduce redundant coding and enable code reuse.
Methods can also be used to modularize code and improve the quality of the
program.
GreatestCommonDivisorMethod
GreatestCommonDivisorMethod
PrimeNumberMethod
PrimeNumberMethod
42
Case Study: Converting Hexadecimals to
Decimals
Hex2Dec
43
Overloading Methods
Overloading the max Method
TestMethodOverloading
TestMethodOverloading
44
Ambiguous Invocation
45
Ambiguous Invocation
public class AmbiguousOverloading {
public static void main(String[] args) {
[Link](max(1, 2));
}
46
Scope of Local Variables
48
Scope of Local Variables, cont.
A variable declared in the initial action part of a for loop
header has its scope in the entire loop. But a variable
declared inside a for loop body has its scope limited in the
loop body from its declaration and to the end of the block
that contains the variable.
49
Scope of Local Variables, cont.
50
Scope of Local Variables, cont.
// Fine with no errors
public 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;
}
}
51
Scope of Local Variables, cont.
// With errors
public static void incorrectMethod() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
int x = 0;
x += i;
}
}
52
Method Abstraction
You can think of the method body as a black box that contains the detailed
implementation for the method.
Method Header
Black Box
Method body
53
Benefits of Methods
54
Case Study: Generating Random Characters
55
Case Study: Generating Random Characters,
cont.
Now let us consider how to generate a random lowercase letter. The Unicode
for lowercase letters are consecutive integers starting from the Unicode for
'a', then for 'b', 'c', ..., and 'z'. The Unicode for 'a' is
(int)'a'
So, a random integer between (int)'a' and (int)'z' is
(int)((int)'a' + [Link]() * ((int)'z' - (int)'a' + 1)
56
Case Study: Generating Random Characters,
cont.
Now let us consider how to generate a random lowercase letter. The Unicode
for lowercase letters are consecutive integers starting from the Unicode for
'a', then for 'b', 'c', ..., and 'z'. The Unicode for 'a' is
(int)'a'
So, a random integer between (int)'a' and (int)'z' is
(int)((int)'a' + [Link]() * ((int)'z' - (int)'a' + 1)
57
Case Study: Generating Random Characters,
cont.
As discussed in Chapter 2, all numeric operators can be applied to the char
operands. The char operand is cast into a number if the other operand is a
number or a character. So, the preceding expression can be simplified as
follows:
'a' + [Link]() * ('z' - 'a' + 1)
58
Case Study: Generating Random Characters,
cont.
59
The RandomCharacter Class
// [Link]: Generate random characters
public class RandomCharacter {
/** Generate a random character between ch1 and ch2 */
public static char getRandomCharacter(char ch1, char ch2) {
return (char)(ch1 + [Link]() * (ch2 - ch1 + 1));
}
} TestRandomCharacter
/** Generate a random character */
public static char getRandomCharacter() {
return getRandomCharacter('\u0000', '\uFFFF');
}
}
60
Stepwise Refinement (Optional)
The concept of method abstraction can be applied to the process of
developing programs. When writing a large program, you can use the
“divide and conquer” strategy, also known as stepwise refinement, to
decompose it into subproblems. The subproblems can be further
decomposed into smaller, more manageable problems.
61
PrintCalender Case Study
Let us use the PrintCalendar example to demonstrate the
stepwise refinement approach.
PrintCalendar
PrintCalendar
62
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
63
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
64
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
65
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
66
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
67
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
68
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
69
Implementation: Top-Down
70
Implementation: Bottom-Up
71
Benefits of Stepwise Refinement
Simpler Program
Reusing Methods
72