Benefits of Methods
Chapter 5 Methods
• Write a method once and reuse it anywhere.
• Information hiding: hide the implementation
from the user
• Reduce complexity
1
4
Motivating Example
Often we need to find the maximum between two
numbers
int result;
if (num1 > num2)
result = num1;
else
result = num2;
Defining and Using Methods
Define a method – give a definition of what the method is to do
modifier returnType methodName(list of parameters) {
collection of statements;
}
Call or invoke a method – use a method
methodName(list of parameters)
A method is a construct for grouping statements
together to perform a function.
A method is defined and implemented once but can be
used repeatedly
A method can be used as a blackbox
5
Method Abstraction
Method abstraction a black box that contains the detailed
implementation for the method.
Return Value Type
A method may return a value (int, double, char, String,
…) – value-returning method
A method may perform desired operations without
returning a value (void) – void method
3
6
Method Signature
main method
Method signature
The combination of the method name and the parameter list
The main method is a method that’s invoked by JVM
The main method’s header is always the same
public static void main(String[] args) {
//method body
}
The statements in main method may invoke other
methods that are defined in the class or in other classes
System.out.println(“Hello World!”);
int number = (int) (Math.random()*100);
7
Parameters
Example
The variables defined in the method header are known as formal parameters
When invoking a method, a value is passed to the parameter and this value is
referred to as actual parameter or argument.
The arguments must match the parameters in order, number, and compatible
type
Parameters are optional
A program that defines and uses a method max to
return the larger of the two int values
TestMax.java
8
11
Method Body
Calling Methods
The method body contains a collection of statements
A return statement is required for a value-returning
method
pass the value of i
pass the value of j
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
return result;
}
9
12
Trace Method Invocation
Trace Method Invocation
i is now 5
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
return result;
}
}
return result;
}
13
16
Trace Method Invocation
Trace Method Invocation
j is now 2
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
return result;
declare variable result
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
return result;
}
}
14
17
Trace Method Invocation
Trace Method Invocation
invoke max(i, j)
(num1 > num2) is true since
num1 is 5 and num2 is 2
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
return result;
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
}
return result;
}
15
18
Trace Method Invocation
Trace Method Invocation
result is now 5
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
Execute the print statement
public static int max(int num1, int num2) {
int result;
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
if (num1 > num2)
result = num1;
else
result = num2;
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;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
return result;
}
}
return result;
}
19
22
Trace Method Invocation
Call Stacks
return result, which is 5
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
return result;
Each time a method is invoked, the system stores
parameters and variables in an area of memory, known as
a stack
When a method calls another method, the caller's stack
space is kept intact
}
20
New space is created to handle the new method call
When a method finishes, its associated space is
released.
23
Trace Method Invocation
Trace Call Stack
return max(i, j) and assign the
return value to k
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
return result;
}
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;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
21
24
Trace Call Stack
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);
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);
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
}
public static int max(int num1, int num2) {
int result;
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
return result;
}
}
25
28
Trace Call Stack
Trace Call Stack
Declare k
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
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);
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
}
public static int max(int num1, int num2) {
int result;
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
return result;
}
}
26
29
Trace Call Stack
Trace Call Stack
Invoke max(i, j)
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
(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 +
" and " + j + " is " + k);
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
}
public static int max(int num1, int num2) {
int result;
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
return result;
}
27
30
Trace Call Stack
CAUTION
Assign num1 to result
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
A return statement is required for a value-returning
method
Compiler error when it is possible that a method does
not return a value
public static int sign(int x) {
if (x < 0) {
return -1;
}
}
public static int sign(int x) {
if (x < 0) {
return -1;
} else {
return 1;
}
}
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;
}
31
34
Trace Call Stack
Reuse Methods from Other Classes
Return result and assign it to k
A method can be invoked from other classes
Invoking a static method defined in other classes
Example
ClassName.methodName (list of parameters)
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
int number = (int) (Math.random()*100);
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
public static int max(int num1, int num2) {
int result;
If you create a new class Test, you can invoke the max
method using
int number = TestMax.max(3,5);
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
32
35
Trace Call Stack
void Method Example
Execute print statement
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
If a method does not return any value, it is said to return
void type. The method is called a void method
The main method is a void method
public static void main(String[] args) {
System.out.println(“Hello world!”);
}
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;
Program example – defines and uses a method which
prints the grade for a given score
TestVoidMethod.java
}
33
36
Passing Parameters
Pass by Value
When calling a method, the arguments must match the
parameters in order, number, and compatible type
someMethod
stack
x: 4
main
x: 3
stack
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
public static void main(String[] args) {
nPrintln(“Hello!”, 3);
nPrintln(“So that’s how the methods work”, 10);
}
When invoking a method, the value of the argument is
passed to the parameter. The variable itself is not
affected. This is referred to as pass-by-value.
37
40
Pass by Value – Trace call stack
main
stack
Pass by Value
someMethod
stack
x: 4
main
x: 3
stack
x: 3
38
41
Pass by Value
Pass by Value
someMethod
stack
x: 3
main
x: 3
stack
39
main
stack
42
x: 3
Program Example - Pass by Value
The program demonstrates the effect of pass-by-value
It creates a method for swapping two variables
The values of the arguments are not changed after the
method is invoked
What if we change the method to
Displaying Prime Numbers - Algorithm
Set an initial count to 0 (to track the number of prime numbers)
Set an initial number to 2
while (count < 50) {
test whether number is prime;
if number is prime {
print the number;
update count;
}
swap(int num1, int num2)
}
TestPassByValue.java
Define a method to test whether a number is prime - check
whether it is divisible by 2, 3, 4, up to number/2.
PrimeNumberMethod.java
43
Modulizing code
Overloading methods
Write a method once and reuse it anywhere.
Methods can be used to reduce redundant code
and enable code reuse
Methods can also be used to modularize code
and reduce complexity of the program
Method overloading: multiple methods can have the same
name but different parameter lists
Compiler determines which method is used based on the
method signature (method name and parameters)
44
Problem Revisited: Displaying Prime Numbers
Problem: Write a program that displays the first 50 prime numbers in
five lines, each of which contains 10 numbers. An integer greater
than 1 is prime if its only positive divisor is 1 or itself. For example,
2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not.
Solution: The problem can be broken into the following tasks:
• Start with number 1
• Determine whether the number is prime.
• Print the number if it is prime
• Count the prime numbers so far.
• If count < 50, repeat the above steps
Overloading Methods
public static int max(int num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
max(1, 3);
max(1.0, 3.0);
max(1.0, 3);
45
48
Scope of Local Variables
Scope of Local Variables
A 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.
49
52
Scope of Local Variables
Scope of a
Scope of x
Scope of a
Scope of x
50
public static void main(String[] args) {
int a = 0;
. . .
if (a == 1) {
int x = 0;
...
}
System.out.println(“x=” + x);
}
public static void main(String[] args) {
int a = 0;
. . .
if (a == 1) {
int x = 0;
//do some calculations on x
}
int x = 2;
}
Scope of Local Variables
Scope of Local Variables, cont.
What does the following method print?
public static void method() {
int sum = 0;
for (int i = 0; i < 5; i++) {
int sum = 0;
sum += i;
}
System.out.println(“sum: ” + sum);
}
Error
Okay
53
The Math Class
Class constants:
Class methods:
51
PI
E
54
Trigonometric Methods
Exponent Methods
Rounding Methods
min, max, abs, and random Methods
Trigonometric Methods
sin(double a)
cos(double a)
tan(double a)
acos(double a)
asin(double a)
atan(double a)
toRadians(double
degree)
toDegrees(double
radians)
min, max, and abs
Examples:
max(a, b)and min(a, b)
abs(a)
The max, min, and abs methods are overloaded so they work for
int, long, float or double
Returns the maximum or minimum of two parameters.
Math.sin(0) //returns
Math.sin(Math.PI / 6)
Math.sin(Math.PI / 2)
Math.cos(0) //returns
Math.cos(Math.PI / 6)
Math.cos(Math.PI / 2)
0.0
//returns
//returns
1.0
//returns
//returns
0.5
1.0
0.866
0
Returns the absolute value of the parameter.
55
58
Exponent Methods
exp(double a)
Returns e raised to the power of a.
log(double a)
Returns the natural logarithm of a.
log10(double a)
Returns the 10-based 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.
The random Method
Generates a random double value greater than or equal to 0.0 and less
than 1.0 (0 <= Math.random() < 1.0).
Examples:
In general,
56
59
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 round(double x)
x is rounded to its nearest integer. Returns (int)Math.floor(x+0.5)
Generating Random Characters
57
random()
How do you generate random capital character?
Solution: generate random number in range 65 - 90
60
The RandomCharacter Class
Enter full year (e.g., 2001): 2009
Enter month in number between 1 and 12: 2
February 2009
----------------------------Sun Mon Tue Wed Thu Fri Sat
1
2 3 4
5 6 7
8
9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Design Diagram
Generalization
We want to generate character from range ch1 to ch2
Remember: characters can be treated as integers
(char)(ch1 + Math.random() * (ch2 – ch1 + 1))
RandomCharacter.java
TestRandomCharacter.java
61
Stepwise Refinement
64
Enter full year (e.g., 2001): 2009
Enter month in number between 1 and 12: 2
February 2009
----------------------------Sun Mon Tue Wed Thu Fri Sat
1
2 3 4
5 6 7
8
9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Design Diagram
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 to decompose it into subproblems
The subproblems can be further decomposed into
smaller, more manageable problems
printCalendar
(main)
printMonth
readInput
printMonthTitle
getMonthName
printMonthBody
getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
62
PrintCalender Case Study
65
Write a program that reads year and month and prints
out a calendar.
printCalendar
(main)
Enter full year (e.g., 2001): 2009
Enter month in number between 1 and 12: 2
February 2009
----------------------------Sun Mon Tue Wed Thu Fri Sat
1 2
3
4
5 6
7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
printMonth
readInput
printMonthTitle
getMonthName
printMonthBody
getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
PrintCalendar.java
63
Enter full year (e.g., 2001): 2009
Enter month in number between 1 and 12: 2
February 2009
----------------------------Sun Mon Tue Wed Thu Fri Sat
1
2 3 4
5 6 7
8
9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Design Diagram
isLeapYear
66
Enter full year (e.g., 2001): 2009
Enter month in number between 1 and 12: 2
February 2009
----------------------------Sun Mon Tue Wed Thu Fri Sat
1
2 3 4
5 6 7
8
9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Design Diagram
printCalendar
(main)
printMonth
readInput
printMonthTitle
printMonthBody
getStartDay
getMonthName
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
67
Enter full year (e.g., 2001): 2009
Enter month in number between 1 and 12: 2
February 2009
----------------------------Sun Mon Tue Wed Thu Fri Sat
1
2 3 4
5 6 7
8
9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Design Diagram
printCalendar
(main)
printMonth
readInput
printMonthTitle
getMonthName
How to get the start day for the first
date in a month, assuming we know
that Jan 1, 1800, was Wednesday?
printMonthBody
getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
68
Implementation
Top-down
Implement one method in the structure chart at a time from the top to
bottom
Stubs can be used for the methods waiting to be implemented
Bottom-up
69
Implement one method in the structure chart at a time from the
bottom to the top
For each method implemented, write a test program to test it
© Copyright 2026 Paperzz