Download presentation
Presentation is loading. Please wait.
1
Week 4 Lecture-2 Chapter 6 (Methods)
2
Learning Objectives By the End of the session, you will able to:
Describe the theory and concepts of Object Oriented Methods; Understanding scope of variables and passing values to Methods. Designing and implementing methods in Object Oriented programming Languages. Learning Objectives
3
Outline Introduction How to define and invoke methods
Top-down design with methods Program structure charts Case studies To do list
4
Introduction to Methods
Motivating example: Problem: Find the sums of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. How would we do it? Intuitive solution: Write three loops for the three sums? Better solution: Write a generalised program, called method, to do each of the three sums as specified? 4
5
Introduction to Methods
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 <= 30; i++) System.out.println("Sum from 20 to 30 is " + sum); for (int i = 35; i <= 45; i++) System.out.println("Sum from 35 to 45 is " + sum); 5 5
6
Defining and Invoking Methods
A method is a collection of statements that are grouped together to perform a task. 6 6 6 6 6 6
7
Tracing Method Invocations
7 7 7 7 7 7
8
Tracing Method Invocations
i is now 5 8 8 8 8 8 8 8
9
Tracing Method Invocations
j is now 2 9 9 9 9 9 9 9 9
10
Tracing Method Invocations
Invoke max(i, j) 10 10 10 10 10 10 10 10 10
11
Tracing Method Invocations
Invoke max(i, j) Pass the value of i to num1 and Pass the value of j to num2 11 11 11 11 11 11 11 11 11 11
12
Tracing Method Invocations
(num1 > num2) is true since num1 is 5 and num2 is 2 12 12 12 12 12 12 12 12 12 12 12
13
Tracing Method Invocations
result is 5. 13 13 13 13 13 13 13 13 13 13 13 13 13
14
Tracing Method Invocations
Return the value of result, 5. 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14
15
Tracing Method Invocations
Return the value of the method invocation, 5, and assign it to k. 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15 15
16
Tracing Method Invocations
Execute print statement “The maximum between 5 and 2 is 5” 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16
17
Pass by Value When a method is invoked with an argument, the value of the argument is passed to the parameter. This is referred to as pass-by-value. 17 17 17 17
18
Pass by Value – an Example
public class Increment { public static void main(String[] args) { int x = 1; System.out.println("Before the call, x is " + x); increment(x); System.out.println("After the call, x is " + x); } public static void increment(int n) { n++; System.out.println("n inside the method is " + n); 18 18 18 18 18
19
Individual Activity Total time: 5 Minutes
Task.1 Identify Errors in the following code and correct them. Using comments notation to write your comments in code, if required. public class ExampleMinNumber { public static int main(String[] args) { int a = 11; int b = 6; int c = minFunction(a, b); System.out.printn("Minimum Value = " + c); } /** returns the minimum of two numbers */ public static int minFuncton(int n1, int n2) { double min; if (n1 > n2) min = n2; else return min;
20
Scope of a Local Variable
Local variables: those defined within a method. Scope of a local variable – starting from its declaration and until the end of the program block that contains the variable. Local variables must be declared in a method before they are used in the method. 20 20 20
21
Scope of a Local Variable
21 21 21 21
22
Scope of a Local Variable
22 22 22 22 22
23
Scope of a Local Variable
// 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 y += i; 23 23 23 23 23 23
24
Scope of a Local Variable
// With errors public static void incorrectMethod() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { int x = 0; x += i; } 24 24 24 24 24 24 24
25
Benefits of Methods Reuse – a defined method can be repeatedly used.
Information hiding – think of a method as a black box of which you don’t need to know the implementation details. Complexity reduction – divide a complex problem into a set of simpler problems to be solved by a set of methods. 25 25
26
Case Study 1 – Calculate Mortgages
In this case study, we learn: how to design a solution for a given problem, how to divide a problem into a set of simpler problems to be solved by a set of methods, and how to write, compile, run and test a program to implement the designed solution. 26
27
Problem Specification
The problem is to design, implement, run and test a program that calculates the maximum size of mortgage that the bank will lead you and your partner. Suppose that this generally equates to 3 times of your salary plus 1 times the smaller salary. 27 27 27 27 27 27
28
How Would We Do it? Top-level design 1. Read in two salaries
2. Calculate 3 times of the larger salary and add it to mortgage 3. Calculate the smaller salary and add it to mortgage 4. Display mortgage 28 28 28 28 28
29
How Would We Do it? Design refinement
(2. Calculate 3 times of the larger salary and add it to mortgage) is refined by 2.1. Find larger salary 2.2. mortgage = larger salary x 3 Note that 2.1. needs to be done before 2.2. and also is part of 2.2. so we need a method for 2.1. 29 29 29 29 29 29
30
How Would We Do it? Design refinement
(2.1. Find larger salary) is refined by If (salary1 > salary2) Then largerSalary = salary1 Else largerSalary = salary2 30 30 30 30 30 30 30
31
How Would We Do it? Design refinement
(3. Calculate the smaller salary and add it to mortgage) is refined by 3.1. Find smaller salary 3.2. mortgage = mortgage + smaller salary Note that 3.1. needs to be done before 3.2. and also is part of 3.2. so we need a method for 3.1. 31 31 31 31 31 31 31
32
How Would We Do it? Design refinement
(3.1. Find smaller salary) is refined by If (salary1 > salary2) Then smallerSalary = salary2 Else smallerSalary = salary1 32 32 32 32 32 32 32 32
33
Program structure charts
calculateMortgage Read two salaries: s1,s2 mortgage = largerSalary(s1, s2) x 3 mortgage + = smallerSalary(s1, s2) Display result largerSalary(s1, s2) smallerSalary(s1, s2) 33 33 33 33 33 33 33 33 33
34
Implementation with methods
Implementation strategies: Given a program structure chart, how do we implement it? Top-down strategy – start with the top level program with method stubs and gradually replace these method stubs with complete ones level by level Bottom-up strategy – start with the methods on the bottom level and gradually move up to higher level methods and eventually top-level main method. 34 34 34 34 34 34 34 34 34 34
35
Top-down implementation – top level
/* This program calculates a mortgage. */ import java.util.Scanner; public class CalculateMortgage { public static void main(String[] args) { Scanner input = new Scanner(system.in); double salary1, salary2, mortgage; // Read in two salaries, salary 1, salary 2 System.out.print("Enter two salaries separated by a space: "); double salary1 = input.nextDouble(); double salary2 = input.nextDouble(); // Calculate mortgage mortgage = largerSalary(Salary1, Salary2) * 3; mortgage += smallerSalary(Salary1, Slary2); System.out.println(”The maximum size of mortgage is: ” + mortgage); public static double largerSalary(double salary1, double salary2) { return 1; // method stub } public static double smallerSalary(double salary1, double salary2) { 35 35
36
Top-down implementation – with method implementations
public static double largerSalary(double salary1, double salary2) { if (salary1 > salary2) return salary1; else return salary2; } public static double smallerSalary(double salary1, double salary2) { Note: Those method stubs will now need to be replaced by these complete method implementations. 36 36 36
37
Bottom-up implementation – with bottom-level implementations
/* This program calculates a mortgage. */ public class CalculateMortgage { public static void main(String[] args) { double larger = largerSalary(1,2); double smaller = smallerSalary(1,2); System.out.println(”The larger and smaller are: ” + larger + smaller); } public static double largerSalary(double salary1, double salary2) { if (salary1 > salary2) return salary1; else return salary2; public static double smallerSalary(double salary1, double salary2) { 37 37 37
38
Group Activity Be in the group of 3 students, Think about a case study in which you can use the following Java concepts together: Taking Input from User; Using Switch/IF statements Loops; Methods; 38 38
39
Group Activity You have to complete this task in 7 minutes.
You should able to explain how you can use them in your proposed scenario. 39 39
40
Summary Methods are used to avoid code repetition
Methods offers key features of Object Oriented Programing which include code efficiency and encapsulation. Variable scope can be define as per requirements. 40 40
41
To Do List Before Next Lectures
Implement group Activity task and show during next week practical session. Read Week 4 lecture slides. Read and run Week 4 program examples. Selectively read those sections in Chapter 6 that cover the topics in this lecture. Attend your practical session in Week 5. Glance through those sections in Chapters 7 and 8 that cover the topics in Week 5’s lecture.
42
Next Lecture Advance Concepts Methods with and Access Modifiers 42 42
43
Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.