1 Fall 2009ACS-1903 Methods – Ch 5 A design technique referred to as stepwise refinement (or divide and conquer, or functional decomposition) is used to.

Slides:



Advertisements
Similar presentations
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Starting Out with Java: From Control Structures through Objects Fourth.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
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.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
CS 201 Functions Debzani Deb.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Copyright © 2012 Pearson Education, Inc. Chapter 6 Modularizing Your Code with Methods.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Chapter 7: User-Defined Methods
11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.
Introduction to Methods
Chapter 6: Functions.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
11 Chapter 5 METHODS CONT’D. 22 MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method Objects are passed by reference.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Functions.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: Functions Starting Out with C++ Early Objects
Chapter 5, Methods Java How to Program, Late Objects Version, 10/e
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
Procedural programming in Java Methods, parameters and return values.
Methods Chapter Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer.
Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter 5: Methods.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-1 Why Write Methods? Methods are commonly used to break a problem down.
Methods CSCI 1301 What is a method? A method is a collection of statements that performs a specific task. Pre-Defined methods: available in Java library.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Chapter 5 : Methods. Why Write Methods?  Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer.
Chapter 5 : Methods Part 2. Returning a Value from a Method  Data can be passed into a method by way of the parameter variables. Data may also be returned.
Exam Review 10/01/2014 Happy October. The Exam  Will be in Canvas  Two parts  Part A is recall – closed book, closed notes ◦Quizzes, in class activity.
Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 5.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Chapter 5 Methods. 2 Contents 1. Introduction to Methods 2. Passing Arguments to a Method 3. More about Local Variables 4. Returning a Value from a Method.
Chapter 7 User-Defined Methods.
Chapter 7 Top-Down Development
by Tony Gaddis and Godfrey Muganda
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Methods.
Chapter Topics Chapter 5 discusses the following main topics:
Starting Out with Java: From Control Structures through Objects
Starting Out with Java: From Control Structures through Objects
Chapter 4 void Functions
6 Chapter Functions.
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 6 – Methods Topics are:
Starting Out with Java: From Control Structures through Objects
Lecture 5- Classes, Objects and Methods
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Starting Out with Java: From Control Structures through Objects
Happy October Exam Review 10/01/2014.
Standard Version of Starting Out with C++, 4th Edition
Presentation transcript:

1 Fall 2009ACS-1903 Methods – Ch 5 A design technique referred to as stepwise refinement (or divide and conquer, or functional decomposition) is used to break a problem down into smaller more manageable pieces. In OO programming these pieces are typically classes and methods. If a specific task is performed in several places in the program, a method can be written once to perform that task, and then be executed anytime it is needed. This is known as code reuse.

2 Fall 2009ACS-1903 Method Types Methods can be Void, or Value-returning A void method is one that simply performs a task and then terminates. For example println() is a method that does not return anything to its caller. System.out.println(“Hi!”); A value-returning method not only performs a task, but also sends a value back to the code that called it. For example, parseInt() returns an integer value found in the string passed to as an argument. int number = Integer.parseInt(“700”);

3 Fall 2009ACS-1903 Void methods Recall the BlueJ shapes project: Each class has several methods these methods happen to be void methods – they do something and then return to the point after they were called.

4 Fall 2009ACS-1903 Defining a method A method has a header and a body. The method header lists important things about the method The method body is a collection of statements that are performed when the method is executed. public void changeColor (String newColor) { color = newColor; draw(); }

5 Fall 2009ACS-1903 Methods Method modifiers public —method is publicly available to code outside the class static —method belongs to a class, not a specific object. E.g. the main() methods we have used. Return type—void or the data type from a value-returning method Method name—a name that is descriptive of what the method does Parentheses—contain parameter specifications - a list of variable declarations.

6 Fall 2009ACS-1903 Using methods A method executes when it is called. The main method is automatically called when a program starts, but other methods are executed by method call statements. displayMessage(); System.out.println(“enter a student number”): Name of method Name of an object An argument

7 Fall 2009ACS-1903 Method documentation A method should always be documented by writing comments that appear just before the method’s definition. The comments should provide a brief explanation of the method’s purpose. The documentation comments begin with /** and end with */. Parameters Return value Let’s examine shapes and the generated documentation

8 Fall 2009ACS-1903 Passing Arguments to a Method Values that are sent into a method are called arguments. System.out.println(“Hello”); number = Integer.parseInt(str); The data type of an argument in a method call must correspond to the variable declaration in the parentheses of the method declaration. The parameter is the variable that holds the value being passed into a method. By using parameter variables in your method declarations, you can design your own methods to accept data passed to them. Arguments must be passed to a method in the same order they are declared

9 Fall 2009ACS-1903 Arguments are Passed by Value In Java, all arguments of the primitive data types are passed by value. This means that only a copy of an argument’s value is passed into a parameter variable. If a parameter variable corresponding to a primitive data type is changed inside a method, it has no affect on the original argument.

10 Fall 2009ACS-1903 Passing String Object References to a Method Recall that a class type variable does not hold the actual data item that is associated with it, but holds the memory address of the object. A variable associated with an object is called a reference variable. When an object, such as a String is passed as an argument, it is actually a reference to the object that is passed.

11 Fall 2009ACS-1903 Passing a Reference as an Argument public static void showLength(String str) { System.out.println(str + “ is “ + str.length() + “characters long.”); str = “Joe”; //see next slide } “Warren” The address of the object known as name is copied into the str parameter. Both variables refer to the same object … the same location in memory showLength(name);

12 Fall 2009ACS-1903 Strings are Immutable Objects Strings are immutable objects, which means that they cannot be changed. When the line str = “Joe”; is executed, it cannot change an immutable object, so new object is created to hold “Joe” PassString.java

13 Fall Tag in Documentation Comments You can provide a description of each parameter in your documentation comments by using tag. General parameterName Description

14 Fall 2009ACS-1903 More About Local Variables A local variable is declared inside a method and is not accessible to statements outside the method. Different methods can have local variables with the same names because the methods cannot see each other’s local variables. A method’s local variables exist only while the method is executing. When the method ends, the local variables and parameter variables are destroyed and any values stored are lost. Local variables are not automatically initialized with a default value and must be given a value before they can be used. Example: LocalVars.javaLocalVars.java

15 Fall 2009ACS-1903 Value-Returning Methods Data can be passed into a method by way of the parameter variables. Data may also be returned from a method, back to the statement that called it. int num = Integer.parseInt(“700”); The string “700” is passed into the parseInt method. The int value 700 is returned from the method and stored into the num variable.

16 Fall 2009ACS-1903 Defining a Value-Returning Method public static int sum(int num1, int num2) { int result; result = num1 + num2; return result; } Return type This expression must be of the same data type as the return type The return statement causes the method to end execution and it returns a value back to the statement that called the method.

17 Fall Tag in Documentation Comments You can provide a description of the return value in your documentation comments by using tag. General Description Example: ValueReturn.javaValueReturn.java tag in a method’s documentation comment must appear after the general description.The description can span several lines.

18 Fall 2009ACS-1903 Returning a booleanValue Frequently, we need to write methods to test arguments for validity and return true or false Public static boolean isValid(int number) { boolean status; If(number >= 1 && number <= 100) status = true; else status = false; Return status; } Calling code: int value = 20; If(isValid(value)) System.out.println(“The value is within range”); else System.out.println(“The value is out of range”);

19 Fall 2009ACS-1903 Returning a Reference to a String Object customername = fullName(“John”, “Martin”); “John Martin” The return statement sends a copy of the reference back to the call statement and because of the assignment statement, that reference is stored in customername. References to the strings are passed to first and last. The name “John Martin” is stored in memory and a reference to it is in variable name Example: ReturnString.javaReturnString.java “John”“Martin” public static String fullName(String first, String last) { String name; name = first + “ “ + last; return name; }

20 Fall 2009ACS-1903 Problem Solving with Methods A large, complex problem can be solved a piece at a time by methods.

21 Fall 2009ACS-1903 Problem Solving with Methods Problem: We want to report the average daily sales for the sales amounts recorded in a file. The name of the file is supplied by the user. Outline of Solution: Get name of file from user Read the file calculating the total sales for a known number of days Calculate and report the average Methods getFileName() getTotalSales() displayResults() SalesReportWithScanner.java

22 Fall 2009ACS-1903 Problem Solving with Methods main() getFileName()displayResults()getTotalSales() Our main() method will call the other 3 methods The above diagram shows that main() uses each of getFileName(), getTotalSales(), and displayResults()

23 Fall 2009ACS-1903 a UML sequence diagram showing methods calls SalesReport main() filename=getFileName() totalSales=getTotalSales() displayResults() main() begins execution. When main() calls getFileName(), main() is suspended and waits till getFileName() completes. When getFileName() returns, a value is assigned to filename. main() resumes execution. main() calls getTotalSales() and main() is suspended again. getTotalSales() executes. When it finishes, a value is assigned to totalSales. main() resumes execution. main() calls displayResults(). main() is suspended until displayResults finishes. main() resumes execution at the statement following the call. main() ends and the program stops. These are called activation boxes representing a period of time a method is active (executing or suspended) A class or an object’s lifeline Activation box indicates when displayResults() is active. i.e. the period of time that its local variables exist Activation box indicates when getTotalSales() is active. i.e. the period of time that its local variables exist Activation box indicates when getFileName() is active. i.e. the period of time that its local variables exist

24 Fall 2009ACS-1903 Calling Methods that Throw Exceptions Note that the main() and getTotalSales() methods in SalesReport.java have a throws IOException clause. exceptions are covered in Chapter 12.