Methods. 2 A sequence of statements can be packaged together as a unit and re-used. A method is a named unit of re-usable code. modifier returnType methodName(

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

Road Map Introduction to object oriented programming. Classes
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
Introduction to Java Programming, 4E Y. Daniel Liang.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
26-Jun-15 Methods. About methods A method is a named group of declarations and statements You execute those declarations and statements by calling the.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
30-Jun-15 Static Methods. About methods A method is a named group of declarations and statements You execute those declarations and statements by calling.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Understanding class definitions Looking inside classes.
1 Topic 04 Methods Programming II/A CMC2522 / CIM2561 Bavy Li.
Introduction to Methods
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
©Silberschatz, Korth and Sudarshan1 Methods Method Basics Parameters Void vs. Non-void Methods Recursion.
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.
Objective You will be able to define and identify the basic components of a java program by taking notes, seeing examples, and completing a lab. Construction.
Methods F Hello World! F Java program compilation F Introducing Methods F Declaring Methods F Calling Methods F Passing Parameters by value F Overloading.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Functions.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 5.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Chapter 8: Arrays and Functions Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Methods We write methods in our programs for many reasons:
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
Sections 5.1 – 5.4 © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
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.
24-Dec-15 Class Structure. 2 Classes A class describes a set of objects The objects are called instances of the class A class describes: Fields (instance.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Functions Functions, locals, parameters, and separate compilation.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
C# Programming Methods.
Classes - Intermediate
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Computer Programming II Lecture 4. Functions - In C++ we use modules to divide the program into smaller and manageable code. These modules are called.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
1 Sections 6.4 – 6.5 Methods and Variables Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
INF120 Basics in JAVA Programming AUBG, COS dept Lecture 07 Title: Methods, part 1 Reference: MalikFarrell, chap 1, Liang Ch 5.
Information and Computer Sciences University of Hawaii, Manoa
Functions + Overloading + Scope
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Some Eclipse shortcuts
Methods Chapter 6.
Chapter 5 Functions DDC 2133 Programming II.
Chapter 6 Methods 1.
User-Defined Functions
Chapter 5 Function Basics
Chapter 6 Methods: A Deeper Look
Group Status Project Status.
IFS410 Advanced Analysis and Design
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Classes, Objects and Methods
Introduction to Object-Oriented Concepts in Java
Lab6 PROGRAMMING 1 metheds chapter5.
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Corresponds with Chapter 5
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

Methods

2 A sequence of statements can be packaged together as a unit and re-used. A method is a named unit of re-usable code. modifier returnType methodName( listOfParameters ) { sequenceOfStatements } modifier returnType methodName( listOfParameters ) { sequenceOfStatements } modifier: either “public”, “private” or “protected” returnType: a type name methodName: a valid identifier listOfParameters: a comma separated list of type declarations

3 Methods A method may produce (return) data If a method doesn’t produce data ▫the return type is “void” If a method does produce data ▫the type of the data is given by the return type ▫The last statement executed must be a “return”. Return statement ▫Syntax: return expression; ▫Semantics: The method is done. Value sent to the ‘caller’

4 Example Write a method that computes the largest of two integer numbers. public int max(int n1, int n2) { if(n1 > n2) { return n1; } else { return n2; } public int max(int n1, int n2) { if(n1 > n2) { return n1; } else { return n2; } I’m the max No, I’m the max

5 Example When the method is ‘called’ (i.e. when it is used) ▫The method is invoked by name ▫The ‘caller’ gives values for the formal parameters ▫The code body executes ▫The returned value (if any) is handed back to the caller. The returned value "is" the method call. public int max(int n1, int n2) { if(n1 > n2) { return n1; } else { return n2; } public int max(int n1, int n2) { if(n1 > n2) { return n1; } else { return n2; } int a = max(3, 5); int b = max(10, -1); int c = max(a, b); int d = max(a, max(b, c)); int a = max(3, 5); int b = max(10, -1); int c = max(a, b); int d = max(a, max(b, c));

6 Void and Non-Void methods A void method doesn’t return data – but it does something. ▫Use as a command A non-void method ‘is’ the data it returns. ▫Use as data; typically in the context of assignment  int z = max(a,max(b,c));

7 Formal/Actual The method is defined by ▫Writing the body ▫Giving it a name ▫Defining the number and type of input (FORMAL PARAMETERS) ▫Defining the type of the output The method is used by ▫Referencing the name ▫Providing actual values to be used for the input (ACTUAL ARGUMENTS) ▫Making use of any output public int max(int n1, int n2) { if(n1 > n2) { return n1; } else { return n2; } public int max(int n1, int n2) { if(n1 > n2) { return n1; } else { return n2; } int a = max(3, 5); int b = max(10, -1); int c = max(a, b); int d = max(a, max(b, c)); int a = max(3, 5); int b = max(10, -1); int c = max(a, b); int d = max(a, max(b, c));

8 Methods and Classes A method is always associated with a class ▫A class is a collection of variables and methods ▫So far, our classes have contained exactly one method and no variables. public class ClassName { } Methods Declarations

9 Scope The SCOPE of a variable is the region of code in which the variable name can be used. Variables declared in a block ▫Scope begins at declaration ▫Scope ends at the end of the enclosing block Variables declared in a method ▫See above since method bodies are blocks Formal parameters ▫Scope begins at declaration ▫Scope ends at the end of the method Variables declared in a class ▫Scope extends throughout the class Variables are known as ▫LOCAL if declared in a method ▫INSTANCE variables if declared in a class

10 Scope Example public class SomeProgram { private int x; private int y; public static void main(String[] args) { int z = max(3, 12); … } public static int max(int a, int b) { … } public class SomeProgram { private int x; private int y; public static void main(String[] args) { int z = max(3, 12); … } public static int max(int a, int b) { … }

11 Method Example Write a method to compute the average of two integer numbers public double average(int n1, int n2) { return (n1 + n2) / 2.0; } public double average(int n1, int n2) { return (n1 + n2) / 2.0; } Write a method to compute whether a student passes a course. The syllabus states that a student passes if they receive at least a 60% average on 3 quizzes (10 points each) and a 65% average on three exams (100 points each). In addition, if any single exam is less than 35% they do not pass.

12 Consider…. Write a code fragment that reads information for a group of students and prints out for each one whether they pass or not. public boolean passes(int q1, int q2, int q3, int e1, int e2, int e3) { double quizAverage = (q1 + q2 + q3) / 30.0; double examAverage = (e1 + e2 + e3) / 300.0; int minExam = min(e1, min(e2, e3)); return quizAverage >=.6 && examAverage >=.65 && minExam >=.35; } public boolean passes(int q1, int q2, int q3, int e1, int e2, int e3) { double quizAverage = (q1 + q2 + q3) / 30.0; double examAverage = (e1 + e2 + e3) / 300.0; int minExam = min(e1, min(e2, e3)); return quizAverage >=.6 && examAverage >=.65 && minExam >=.35; } char c = Keyboard.readChar(); while(c != ‘Q’) { int q1 = Keyboard.readInt(); int q2 = Keyboard.readInt(); int q3 = Keyboard.readInt(); int e1 = Keyboard.readInt(); int e2 = Keyboard.readInt(); int e3 = Keyboard.readInt(); System.out.println(“passes?: “ + passes(q1,q2,q3,e1,e2,e3)); c = Keyboard.readChar(); } char c = Keyboard.readChar(); while(c != ‘Q’) { int q1 = Keyboard.readInt(); int q2 = Keyboard.readInt(); int q3 = Keyboard.readInt(); int e1 = Keyboard.readInt(); int e2 = Keyboard.readInt(); int e3 = Keyboard.readInt(); System.out.println(“passes?: “ + passes(q1,q2,q3,e1,e2,e3)); c = Keyboard.readChar(); }

13 Method Example Write a method to compute the amount of money (in cents) in a bank account at the end of some term. The starting balance is given (in cents) along with the annual interest rate (a double given in percent) and the number of years. public int getBalance(int balance, double rate, int yrs) { for(int yr=1; yr <= yrs; yr++){ balance += (int)((balance)*(1+rate/100)); } return balance; } public int getBalance(int balance, double rate, int yrs) { for(int yr=1; yr <= yrs; yr++){ balance += (int)((balance)*(1+rate/100)); } return balance; }

14 Top-Down Design Often need to break large problems into parts. Each part can be broken into sub-parts Similar to a book outline

15 Case Study Write a program to print a table of expected return on some stock investment. The stock is purchased prior to retirement – what is the value of the stock at retirement? Factors: ▫The age when the stock is purchased ▫The age at retirement ▫The amount of stock purchased Input: ▫Age at time of purchase (min / max ) ▫Age at retirement (min / max ) ▫Amount purchased

16 Example Output Assume 10 years between ages at purchase and 5 years between ages at retirement.

17 Details Interest is compounded annually Formula is ▫A = P((1 + r)^t) ▫P is principle / r is annual rate / t is number of years Anticipated rate is determined by age and principle ▫Let B = 10% / Y = years to retirement ▫Rate = B + (Y / 10) + (P – 25000)/100000

18 How should we ‘decompose’? Print Table Read Input Print Header Print Data Print row Compute Rate Compute Balance