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.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
11 Chapter 8 ARRAYS Continued. 22 AN ARRAY OF STRINGS We can create arrays of strings or other types of objects.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Starting Out with Java: From Control Structures through Objects Fourth.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
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.
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.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
VBA Modules, Functions, Variables, and Constants
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Introduction to Computers and Programming Strings Professor: Evan Korth New York University.
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
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.
1 Chapter 2 JAVA FUNDAMENTALS CONT’D. 2 PRIMITIVE DATA TYPES Computer programs operate on data values. Values in Java are classified according to their.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
3.1 Documentation & Java Language Elements Purpose of documentation Assist the programmer with developing the program Assist other programers who.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
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.
Passing Other Objects Strings are called immutable which means that once a String object stores a value, it never changes –recall when we passed a message.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
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.
Methods We write methods in our programs for many reasons:
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
An Introduction to Programming with C++ Sixth Edition Chapter 10 Void Functions.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-1 Why Write Methods? Methods are commonly used to break a problem down.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING String and Scanner Objects.
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.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
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.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
Yanal Alahmad Java Workshop Yanal Alahmad
2.5 Another Java Application: Adding Integers
Chapter 7 Top-Down Development
by Tony Gaddis and Godfrey Muganda
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
INPUT STATEMENTS GC 201.
Chapter Topics Chapter 5 discusses the following main topics:
Type Conversion, Constants, and the String Object
Topics Introduction to File Input and Output
Starting Out with Java: From Control Structures through Objects
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chap 1 Chap 2 Chap 3 Chap 5 Surprise Me
Chapter 6 – Methods Topics are:
Starting Out with Java: From Control Structures through Objects
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.
Topics Introduction to File Input and Output
Standard Version of Starting Out with C++, 4th Edition
Presentation transcript:

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 in Java. This means that when you pass an argument of a non- primitive type (a class type) it is actually the address of the object that is passed. The parameter variable that receives this address/reference will reference the object that was the argument. A copy of the object is not created. The method that receives the reference to the object has access to the original object.

33 MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method /** A void method that displays a student's letter grade along with a name The name of the grade The character representing the student's letter grade */ public static void displayGrade(String name, char grade) { System.out.println("\nThe grade assigned for " + name + " is " + grade + "."); if (grade == 'A') { System.out.println("Fantastic!"); } else if (grade == 'B') { System.out.println("Great job!"); } return; }

44 MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method Example: The statement highlighted below calls the method displayGrade passing the address of the object that contains the name of the student as the first argument and the value stored in the variable letterGrade as the second argument. We say that the parameter variable name references the object that contains the name of the student, because it has the address of the object, just like studentName does in the calling method. displayGrade(studentName, letterGrade); public static void displayGrade(String name, char grade) address studentName address name Heap A String object copy of argument grade The local variables of the methods are stored on the stack. letterGrade actual data item

55 MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method If the object passed as an argument is a String, you do not need to be concerned that the method will change the String. In Java, strings are immutable, which means they cannot be changed.

66 MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method

77 Note: the original String is not changed.

88 MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method The method changeString depicted in the previous slides creates a new String object to hold the string Go Ducks! The address of this String object is assigned to the reference variable named anotherString.

99 MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method Remember that the concatenation operator, the nextLine method of a Scanner object, the showInputDialog method of the JOptionPane class, and the toUpperCase and toLowerCase methods of the String class all create String objects. The assignment operator copies the address of the String object when it is used on strings. It does not copy a String.

10 MORE ON PASSING ARGUMENTS TO A METHOD Using Tag in a Documentation Comment for a Method that Accepts Arguments When you use tag in a documentation comment describing a method, the description of the parameter variable that follows this tag is included in the documentation created by the javadoc utility program. The description of the parameter variables must appear after the general description of the method.

11 MORE ABOUT LOCAL VARIABLES The Lifetime of Local Variables A method's local variables and parameters exist only when the method is executing. This is often called the lifetime of these variables. When the method begins executing, its local and parameter variables are created in memory, and when the method's execution ends these variables are destroyed.

12 MORE ON VALUE-RETURNING METHODS Methods can return a value of any data type. For example, in the program DemoMethods.java the method named getGrade returned a value of type int to the code that called it and the method named assignLettGrade returns a value of type char.

13 MORE ON VALUE-RETURNING METHODS It is common to write methods that test an argument or arguments to see if some condition exists and return a boolean value to indicate whether the condition does or does not exist.

14 MORE ON VALUE-RETURNING METHODS /** A method that determines if the character that is passed in as its argument is a character The character to be true if the character is a digit, false otherwise */ public static boolean isDigit(char character) { boolean aDigit = false; if (character >= '0' && character <= '9') { aDigit = true; } return aDigit; }

15 MORE ON VALUE-RETURNING METHODS Using Tag in the Documentation Comment for a Value-Returning Method You can use tag in a documentation comment describing a method to provide a description of the value returned by the method. The javadoc utility program will create a section in the documentation for the method under a heading Returns: that includes the words following tag. The description of the return value must appear after the general description of the method.

16 MORE ON VALUE-RETURNING METHODS Returning a Reference to an Object A method can return a reference to an object.

17 MORE ON VALUE-RETURNING METHODS Returning a Reference to an Object For example, the method shown below from DemoMethodsWRefVar.java returns a reference to an object of the String class. public static String getName(Scanner keyboard) { String name; System.out.print("Enter the student's name "); name = keyboard.nextLine( ); while (name.length( ) == 0) // While the name is the empty string { System.out.println("\nError, invalid name entered."); System.out.print("Enter the student's name "); name = keyboard.nextLine( ); } return name; }

18 MORE ON VALUE-RETURNING METHODS Returning a Reference to an Object The Lifetime of an Object Objects are created in a part of memory known as the heap. They are not created on the stack like variables of primitive data types. Objects are not automatically destroyed when the method in which they were created terminates. The lifetime of a object is until the object is no longer referenced by an reference variable.

19 MORE ON VALUE-RETURNING METHODS Returning a Reference to an Object When the method getName ends its execution in DemoMethodsWRefVar.java, the local variable name is destroyed, but the String object that was created is not automatically destroyed. We can return the address of this object and this value can be stored in another reference variable that can be used to access the object.

20 MORE ON VALUE-RETURNING METHODS Returning a Reference to an Object *** See the program DemoMethodsWRefVar.java on webct

21 PROBLEM SOLVING WITH METHODS When we develop our code incrementally, we often write code that is used only during the development of the program and does not appear in the final program.

22 PROBLEM SOLVING WITH METHODS A driver is a dummy method that can be used to test a called method. The driver calls the method passing it arguments that are used to test the logic of the method. If the called method returns a value the driver usually displays this value on the screen. Quite often a driver uses a loop to call the method over and over. It might be a loop that lets the user repeatedly enter test cases or it might be some sort of count-controlled loop(s) that calls the method with arguments in a specific range.

23 PROBLEM SOLVING WITH METHODS To test a method that calls other methods, it is often useful to create stubs for the called methods. A stub is a dummy method that can be called by the method being tested. A stub usually displays a message indicating that it has been called, so that the programmer can verify that the method is called as expected. A stub for a method that accepts arguments usually displays the arguments on the computer screen so the programmer can ensure that the values are being passed properly. A stub for a value-returning method usually returns a test value so that the programmer can test the calling method's use of the return value.

24 PROBLEM SOLVING WITH METHODS Problem: Suppose we wanted to write a program that gets the social security number, first name, last name, and hourly pay rate of an unspecified number of employee's from the user and stores these in a file selected by the user. The data items should be stored in the file in the following order: social security number, last name, first name, and hourly pay rate. One newline character must separate the individual data items for an employee in the file and one newline character must separate one employee's hourly pay rate from the next employee's social security number in the file.

25 PROBLEM SOLVING WITH METHODS The program TestgetHourlyRate.java was written to test the method getHourlyRate. The main method is a driver. It calls the method getHourlyRate so that we can test the logic of this method. This main method is not the main method of our final program.

26 PROBLEM SOLVING WITH METHODS The program PartOfSaveEmployeeData.java was written to test the logic of the main method. Several of the methods that have not been completed at this point are represented by stubs.

27 PROBLEM SOLVING WITH METHODS ***See the program SaveEmployeeData.java on webct