Chapter 7 User-Defined Methods. Chapter Objectives

Similar documents
Programming: Java. Chapter Objectives. Chapter Objectives (continued) Program Design Including Data Structures. Chapter 7: User-Defined Methods


C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Full file at

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Functions. Lecture 6 COP 3014 Spring February 11, 2018

CS212 Midterm. 1. Read the following code fragments and answer the questions.

Chapter 4: Writing Classes

EECS168 Exam 3 Review

Array. Prepared By - Rifat Shahriyar

Introduction to Programming Using Java (98-388)

Anatomy of a Class Encapsulation Anatomy of a Method

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Lecture 5: Methods CS2301

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

CMPT 125: Lecture 4 Conditionals and Loops

CS313D: ADVANCED PROGRAMMING LANGUAGE

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

Computer Science is...

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

COMP 202 Java in one week

Controls Structure for Repetition

CS-201 Introduction to Programming with Java

Chapter 4: Control Structures I

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Methods. CSE 114, Computer Science 1 Stony Brook University

Example: Monte Carlo Simulation 1

Question: Total Points: Score:

Methods and Functions

Static Methods. Why use methods?

Java Bytecode (binary file)

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Introduction to Programming (Java) 4/12

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

Chapter 4 Defining Classes I

COMP 202. Java in one week

Introduction to Software Development (ISD) Week 3

Programming with Java

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Chapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Programming II (CS300)

1 Lexical Considerations

Lexical Considerations

The Basic Parts of Java

Chapter Goals. Contents LOOPS

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

CS-201 Introduction to Programming with Java

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Example Program. public class ComputeArea {

x++ vs. ++x x=y++ x=++y x=0; a=++x; b=x++; What are the values of a, b, and x?

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

PROGRAMMING FUNDAMENTALS

Section 003 Fall CS 170 Exam 1. Name (print): Instructions:

Top-down programming design

C++ Programming: From Problem Analysis to Program Design, Third Edition

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

Oct Decision Structures cont d

Chapter 2: Basic Elements of Java

COP 3330 Final Exam Review

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Chapter 6: Methods. Objectives 9/21/18. Opening Problem. Problem. Problem. Solution. CS1: Java Programming Colorado State University

STUDENT LESSON A12 Iterations

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Selected Questions from by Nageshwara Rao

Fundamentals of Programming Data Types & Methods

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Conditional Execution

Lexical Considerations

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Chapter 4 Computer Science with C++ Name: Review Worksheet A Mr. Ferwerda

( &% class MyClass { }

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

The data in the table are arranged into 12 rows and 12 columns. The process of printing them out can be expressed in a pseudocode algorithm as

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

Chapter 11 Introduction to Programming in C

CS171:Introduction to Computer Science II

Objects and Classes -- Introduction

Java Basic Programming Constructs

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

Chapter 6 Introduction to Defining Classes

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Programming II (CS300)

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

Midterm Examination (MTA)

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Repetition CSC 121 Fall 2014 Howard Rosenthal

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Advanced Object Concepts

Transcription:

Chapter 7 User-Defined Methods Chapter Objectives Understand how methods are used in Java programming Learn about standard (predefined) methods and discover how to use them in a program Learn about user-defined methods Examine value-returning methods, including actual and formal parameters 2 1

Chapter Objectives (continued) Explore how to construct and use a valuereturning, user-defined method in a program Learn how to construct and use user-defined void methods in a program Explore variables as parameters Learn about the scope of an identifier Become aware of method overloading 3 Predefined Classes Methods already written and provided by Java Organized as a collection of classes (class libraries) To use: import package Method type: data type of value returned by method 4 2

Predefined Classes (continued) 5 Predefined Classes (continued) 6 3

Predefined Classes (continued) 7 Predefined Classes (continued) 8 4

class Character (Package: java.lang) 9 class Character (Package: java.lang) (continued) 10 5

class Character (Package: java.lang) (continued) 11 To simplify the use of (public) static methods of a class, Java 5.0 introduces the following import statements: These are called static import statements. After including such statements in your program, when you use a (public) static method (or any other public static member) of a class, you can omit the name of the class and the dot operator. 12 6

13 14 7

15 16 8

Syntax: Value-Returning Method 17 User-Defined Methods Value-returning methods Used in expressions Calculate and return a value Can save value for later calculation or print value modifiers: public, private, protected, static, abstract, final returntype: type of the value that the method calculates and returns (using return statement) methodname: Java identifier; name of method 18 9

Syntax Syntax: formal parameter list -The syntax of the formal parameter list is: Method call -The syntax to call a value-returning method is: 19 Syntax (continued) Syntax: actual parameter list -The syntax of the actual parameter list is: Syntax: return statement -The return statement has the following syntax: return expr; 20 10

Equivalent Method Definitions public static double larger(double x, double y) { double max; if (x >= y) max = x; else max = y; } return max; 21 22 11

23 Equivalent Method Definitions (continued) public static double larger(double x, double y) { if (x >= y) return x; else return y; } 24 12

Equivalent Method Definitions (continued) public static double larger(double x, double y) { if (x >= y) return x; } return y; 25 The int variable num contains the desired sum to be rolled 26 13

Palindrome Number Palindrome: integer or string that reads the same forward and backward The method ispalindrome takes a string as a parameter and returns true if the string is a palindrome, false otherwise 27 Solution: ispalindrome Method public static boolean ispalindrome(string str) { int len = str.length(); int i, j; j = len - 1; } for (i = 0; i <= (len - 1) / 2; i++) { if (str.charat(i)!= str.charat(j)) return false; j--; } return true; 28 14

Flow of Execution Execution always begins with the first statement in the method main User-defined methods execute only when called Call to method transfers control from caller to called method In method call statement, specify only actual parameters, not data type or method type Control goes back to caller when method exits 29 Programming Example: Largest Number Input: set of 10 numbers Output: largest of 10 numbers Solution Get numbers one at a time Method largest number: returns the larger of two numbers For loop: calls method largest number on each number received and compares to current largest number 30 15

Solution: Largest Number static Scanner console = new Scanner(System.in); public static void main(string[] args) { double num; double max; int count; System.out.println("Enter 10 numbers."); num = console.nextdouble(); max = num; for (count = 1; count < 10; count++) { num = console.nextdouble(); max = larger(max, num); } System.out.println("The largest number is " + max); } 31 Sample Run: Largest Number Sample Run Enter 10 numbers: 10.5 56.34 73.3 42 22 67 88.55 26 62 11 The largest number is 88.55 32 16

Void Methods Similar in structure to value-returning methods Call to method is always stand-alone statement Can use return statement to exit method early 33 Void Methods with Parameters: Syntax 34 17

Void Methods with Parameters: Syntax (continued) 35 Primitive Data Type Variables as Parameters A formal parameter receives a copy of its corresponding actual parameter If a formal parameter is a variable of a primitive data type: Value of actual parameter is directly stored Cannot pass information outside the method Provides only a one-way link between actual parameters and formal parameters 36 18

Reference Variables as Parameters If a formal parameter is a reference variable: Copies value of corresponding actual parameter Value of actual parameter is address of the object where actual data is stored Both formal and actual parameter refer to same object 37 Uses of Reference Variables as Parameters Can return more than one value from a method Can change the value of the actual object When passing address, would save memory space and time, relative to copying large amount of data 38 19

Reference Variables as Parameters: type String 39 Reference Variables as Parameters: type String (continued) 40 20

Reference Variables as Parameters: type String (continued) 41 Reference Variables as Parameters: type String (continued) 42 21

Reference Variables as Parameters: type String (continued) String str = "Hello"; //Line 5 43 Reference Variables as Parameters: type String (continued) stringparameter(str); //Line 7 44 22

Reference Variables as Parameters: type String (continued) pstr = "Sunny Day"; //Line 14 45 Reference Variables as Parameters: type String (continued) Variables before the statement in Line 8 executes 46 23

The classstringbuffer contains the method append, which allows you to append a string to an existing string, and the method delete, which allows you to delete all the characters of the string The assignment operator cannot be used with StringBuffer variables; you must use the operator new (initially) to allocate memory space for a string 47 48 24

49 50 25

51 52 26

Primitive Type Wrapper Classes as Parameters If a formal parameter is of the primitive data type and the corresponding actual parameter is a variable, then the formal parameter cannot change the value of the actual parameter Only reference variables can pass values outside the method (except, of course, for the return value) Corresponding to each primitive data type, Java provides a class so that the values of primitive data types can be wrapped in objects The class Integer does not provide a method to change the value of an existing Integer object The same is true of other wrapper classes 53 Primitive Type Wrapper Classes as Parameters (continued) If we want to pass a String object as a parameter and also change that object, we can use the class StringBuffer Java does not provide any class that wraps primitive type values in objects and when passed as parameters changes their values If a method returns only one value of a primitive type, then you can write a value-returning method If you encounter a situation that requires you to write a method that needs to pass more than one value of a primitive type, then you should design your own classes Appendix D provides the definitions of such classes and shows how to use them in a program 54 27

Scope of an Identifier within a Class Local identifier: identifier declared within a method or block, which is visible only within that method or block Java does not allow the nesting of methods; you cannot include the definition of one method in the body of another method Within a method or a block, an identifier must be declared before it can be used; a block is a set of statements enclosed within braces 55 Scope of an Identifier within a Class (continued) A method s definition can contain several blocks The body of a loop or an if statement also form a block Within a class, outside of every method definition (and every block), an identifier can be declared anywhere 56 28

Scope of an Identifier within a Class (continued) Within a method, an identifier used to name a variable in the outer block of the method cannot be used to name any other variable in an inner block of the method For example, in the method definition on the next slide, the second declaration of the variable x is illegal 57 Scope of an Identifier within a Class (continued) public static void illegalidentifierdeclaration() { int x; } //block { double x; }... //illegal declaration, //x is already declared 58 29

Scope Rules Scope rules of an identifier declared within a class and accessed within a method (block) of the class An identifier, say x, declared within a method (block) is accessible: Only within the block from the point at which it is declared until the end of the block By those blocks that are nested within that block 59 Scope Rules (continued) Suppose x is an identifier declared within a class and outside of every method s definition (block) If x is declared without the reserved word static (such as a named constant or a method name), then it cannot be accessed in a static method If x is declared with the reserved word static (such as a named constant or a method name), then it can be accessed within a method (block), provided the method (block) does not have any other identifier named x 60 30

Scope Rules (continued) Example 7-11 public class ScopeRules { static final double rate = 10.50; static int z; static double t; public static void main(string[] args) { int num; double x, z; char ch; //... } public static void one(int x, char y) { //... } 61 Scope Rules (continued) public static int w; public static void two(int one, int z) { char ch; int a; } } //block three { int x = 12; //... } //end block three //... 62 31

Scope Rules: Demonstrated 63 Scope Rules: Demonstrated (continued) 64 32

Method Overloading: An Introduction Method overloading: more than one method can have the same name Two methods are said to have different formal parameter lists if both methods have: A different number of formal parameters, or If the number of formal parameters is the same, then the data type of the formal parameters, in the order you list, must differ in at least one position 65 Method Overloading public void methodone(int x) public void methodtwo(int x, double y) public void methodthree(double y, int x) public int methodfour(char ch, int x, double y) public int methodfive(char ch, int x, String name) These methods all have different formal parameter lists 66 33

Method Overloading (continued) public void methodsix(int x, double y, char ch) public void methodseven(int one, double u, char firstch) The methods methodsix and methodseven both have three formal parameters, and the data type of the corresponding parameters is the same These methods all have the same formal parameter lists 67 Method Overloading (continued) Method overloading: creating several methods, within a class, with the same name The signature of a method consists of the method name and its formal parameter list Two methods have different signatures if they have either different names or different formal parameter lists Note that the signature of a method does not include the return type of the method 68 34

Method Overloading (continued) The following method headings correctly overload the method methodxyz: public void methodxyz() public void methodxyz(int x, double y) public void methodxyz(double one, int y) public void methodxyz(int x, double y, char ch) 69 Method Overloading (continued) public void methodabc(int x, double y) public int methodabc(int x, double y) Both these method headings have the same name and same formal parameter list These method headings to overload the method methodabc are incorrect In this case, the compiler will generate a syntax error Notice that the return types of these method headings are different 70 35

Programming Example: Data Comparison Input: data from two different files Data format: course number followed by scores Output: course number, group number, course average Solution Read from more than one file, write output to file Generate bar graphs User-defined methods and re-use (calculateaverage and printresult) Parameter passing 71 Programming Example: Data Comparison (continued) Sample Output Course No Group No Course Average CSC 1 83.71 2 80.82 ENG 1 82.00 2 78.20 HIS 1 77.69 2 84.15 MTH 1 83.57 2 84.29 PHY 1 83.22 2 82.60 Avg for group 1: 82.04 Avg for group 2: 82.01 72 36

Programming Example: Data Comparison (continued) 73 A program may contain a number of methods. In a complex program, usually, when a method is written, it is tested and debugged alone. You can write a separate program to test the method. The program that tests a method is called a driver program. Before writing the complete program, you could write separate driver programs to make sure that each method is working properly. 74 37

Sometimes the results calculated by one method are needed in another method. In that case, the method that depends on another method cannot be tested alone. A method stub is a method that is not fully coded. For a void method, a method stub might consist of only a method header and a set of empty braces, {}. For a value-returning method it might contain only a return statement with a plausible return value. 75 If the problem is large and complex, it must be broken into subproblems, and if a subproblem is still complex, it must further be divided into subproblems. The subdivision of a problem should continue to the point where the solution is clear and obvious. Once a subproblem is solved, we can continue with the solution of another subproblem and if all the subproblems of a problem are solved, we can continue with the next level. Eventually, the overall solution of the problem must be assembled and tested to ensure that the programming code accomplishes the required task. 76 38

A Java program is a collection of classes, and a class is a collection of data members and methods. Each class and each method must work properly. To accomplish this, as explained in the previous section, once a method is written, it can be tested using stubs and drivers. Since a method can be tested in isolation, it is not necessary to code all the methods in order. Once all the methods are written, the overall program must be tested. 77 The technique to solve a problem by subdividing into smaller problems is known as divide and conquer and top-down design approach. These techniques are suitable and work for many kinds of problems, including most of the problems given in this book and the problems you will encounter as a beginning programmer. To simplify the overall solution of a problem that consists of many subproblems, we write and test the code one piece at a time. Typically, once a subproblem is solved and the code is tested, it is saved as the first version or a version of the program. We continue to add and save the program one piece at a time. Keep in mind that a working program with fewer features is better than a nonworking one with many features. 78 39

Chapter Summary Predefined methods User-defined methods Value-returning methods Void methods Formal parameters Actual parameters Flow of execution 79 Chapter Summary (continued) Primitive data type variables as parameters One-way link between actual parameters and formal parameters (limitations caused) Reference variables as parameters Can pass one or more variables from a method Can change value of actual parameter Scope of an identifier within a class Method overloading 80 40

Chapter Summary (continued) Debugging: using drivers and stubs Avoiding bugs: one-piece-at-a-time coding 81 41