Week 4 Lecture-2 Chapter 6 (Methods).

Slides:



Advertisements
Similar presentations
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Advertisements

Chapter 5 Functions.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 5 Function Basics.
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Introduction to Java Programming, 4E Y. Daniel Liang.
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
1 Chapter 5 Methods. 2 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
1 Topic 04 Methods Programming II/A CMC2522 / CIM2561 Bavy Li.
Building Java Programs Chapter 5 Program Logic and Indefinite Loops Copyright (c) Pearson All rights reserved.
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
Slides by Donald W. Smith
Chapter 6 Functions 1. Opening Problem 2 Find the sum of integers from 1 to 10, from 20 to 37, and from 35 to 49, respectively.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
Liang, Introduction to C++ Programming, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Advanced Function Features.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 6 Functions.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 6 Methods Dr. Musab Zghoul.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 6 Methods.
INF120 Basics in JAVA Programming AUBG, COS dept Lecture 07 Title: Methods, part 1 Reference: MalikFarrell, chap 1, Liang Ch 5.
Reference: COS240 Syllabus
Suppose we want to print out the word MISSISSIPPI in big letters.
Suppose we want to print out the word MISSISSIPPI in big letters.
Chapter 5 Methods.
Chapter 6: Methods CS1: Java Programming Colorado State University
Chapter 6 Functions.
Chapter 5 Functions DDC 2133 Programming II.
Chapter 5 Function Basics
Chapter 6 Methods 1.
Functions CIS 40 – Introduction to Programming in Python
Data types, Expressions and assignment, Input from User
TK1114 Computer Programming
Something about Java Introduction to Problem Solving and Programming 1.
2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park
Starting Out with Java: From Control Structures through Objects
Chapter 6 Methods.
Chapter 5 – Part 2 Methods Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 5 Function Basics
Lecture Notes – Week 3 Lecture-2
METHODS (FUNCTIONS) By: Lohani Adeeb khan.
Group Status Project Status.
Java Programming Function Introduction
CS2011 Introduction to Programming I Methods (II)
Chapter 6 Methods.
Chapter 5 Methods.
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Lecture Notes – Week 4 Chapter 5 (Loops).
Lecture Notes – Week 2 Lecture-2
Introduction to Java Brief history of Java Sample Java Program
Lecture Notes - Week 2 Lecture-1. Lecture Notes - Week 2 Lecture-1.
Chapter 5 Methods Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
IPC144 Introduction to Programming Using C Week 4 – Lesson 2
Building Java Programs
Building Java Programs
Java Programming Function Introduction
2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

Week 4 Lecture-2 Chapter 6 (Methods)

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

Outline Introduction How to define and invoke methods Top-down design with methods Program structure charts Case studies To do list

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

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

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

Tracing Method Invocations 7 7 7 7 7 7

Tracing Method Invocations i is now 5 8 8 8 8 8 8 8

Tracing Method Invocations j is now 2 9 9 9 9 9 9 9 9

Tracing Method Invocations Invoke max(i, j) 10 10 10 10 10 10 10 10 10

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

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

Tracing Method Invocations result is 5. 13 13 13 13 13 13 13 13 13 13 13 13 13

Tracing Method Invocations Return the value of result, 5. 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14

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

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

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

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

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;

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

Scope of a Local Variable 21 21 21 21

Scope of a Local Variable 22 22 22 22 22

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

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

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

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

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

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

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

How Would We Do it? Design refinement (2.1. Find larger salary) is refined by 2.1.1. If (salary1 > salary2) Then 2.1.2 largerSalary = salary1 Else 2.1.3 largerSalary = salary2 30 30 30 30 30 30 30

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

How Would We Do it? Design refinement (3.1. Find smaller salary) is refined by 3.1.1. If (salary1 > salary2) Then 3.1.2 smallerSalary = salary2 Else 3.1.3 smallerSalary = salary1 32 32 32 32 32 32 32 32

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

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

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

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

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

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

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

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

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.

Next Lecture Advance Concepts Methods with and Access Modifiers 42 42

Questions?