Chapter 7: User-Defined Methods

Slides:



Advertisements
Similar presentations
Chapter 6: User-Defined Functions I
Advertisements

C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 7: User-Defined Functions II.
Chapter 6: User-Defined Functions I
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.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Chapter 6: User-Defined Functions I
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Chapter 5: METHODS USER-DEFINED METHODS. user-defined  We learned that a Java application program is a collection of classes, and that a class is a collection.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 7 User-Defined Methods.
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.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
The Java Programming Language
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 5 Loops.
CHAPTER 5 FUNCTIONS I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Procedural programming in Java Methods, parameters and return values.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
COSC236 Modularity1 Top-Down Design Design before code most programs so far have been simple, less than one page in length most problems are not so simple.
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.
CiS 260: App Dev I. 2 Introduction to Methods n A method (or ________) is a segment of code that performs a specific task. n Advantages of modular program.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
CHAPTER 6 USER-DEFINED FUNCTIONS Made By- Kartik Belwal.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Chapter 7: User-Defined Methods J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Third Edition Third.
Functions + Overloading + Scope
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Reference: COS240 Syllabus
Chapter 6: User-Defined Functions I
Chapter 7: User-Defined Functions II
Java Programming: Guided Learning with Early Objects
Chapter 4: Writing Classes
User-Defined Functions
Chapter 6 Methods: A Deeper Look
Group Status Project Status.
CHAPTER 6 GENERAL-PURPOSE METHODS
Chapter 7: User-Defined Functions II
Chapter 6: User-Defined Functions I
Corresponds with Chapter 5
Presentation transcript:

Chapter 7: User-Defined Methods Java Programming: From Problem Analysis to Program Design, Second Edition

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. Java Programming: From Problem Analysis to Program Design, Second Edition

Chapter Objectives Explore how to construct and use a value-returning, 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. Java Programming: From Problem Analysis to Program Design, Second Edition

Predefined Classes Methods already written and provided by Java. Organized as a collection of classes (class libraries). To use, import package. Method type: The data type of the value returned by the method. Java Programming: From Problem Analysis to Program Design, Second Edition

Predefined Classes Java Programming: From Problem Analysis to Program Design, Second Edition

Predefined Classes Java Programming: From Problem Analysis to Program Design, Second Edition

Predefined Classes Java Programming: From Problem Analysis to Program Design, Second Edition

class Character (Package: java.lang) Java Programming: From Problem Analysis to Program Design, Second Edition

class Character (Package: java.lang) Java Programming: From Problem Analysis to Program Design, Second Edition

Syntax of Value-Returning Method modifier(s) returnType methodName (formal parameter list) { statements } Java Programming: From Problem Analysis to Program Design, Second Edition

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. Java Programming: From Problem Analysis to Program Design, Second Edition

Syntax Syntax of formal parameter list: dataType identifier, dataType identifier,... Syntax to call a value-returning method: methodName(actual parameter list) Java Programming: From Problem Analysis to Program Design, Second Edition

Syntax Syntax of the actual parameter list: expression or variable, expression or variable, ... Syntax of the return statement: return expr; Java Programming: From Problem Analysis to Program Design, Second Edition

Equivalent Method Definitions public static double larger(double x, double y) { double max; if (x >= y) max = x; else max = y; return max; } Java Programming: From Problem Analysis to Program Design, Second Edition

Equivalent Method Definitions public static double larger(double x, double y) { if (x >= y) return x; else return y; } Java Programming: From Problem Analysis to Program Design, Second Edition

Equivalent Method Definitions public static double larger(double x, double y) { if (x >= y) return x; return y; } Java Programming: From Problem Analysis to Program Design, Second Edition

Programming Example: Palindrome Number Palindrome: An integer or string that reads the same forwards and backwards. Input: Integer or string. Output: Boolean message indicating whether integer string is a palindrome. Java Programming: From Problem Analysis to Program Design, Second Edition

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; Java Programming: From Problem Analysis to Program Design, Second Edition

Sample Runs: Palindrome Number Java Programming: From Problem Analysis to Program Design, Second Edition

Sample Runs: Palindrome Number Java Programming: From Problem Analysis to Program Design, Second Edition

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 the method call statement, specify only actual parameters, not data type or method type. Control goes back to caller when method exits. Java Programming: From Problem Analysis to Program Design, Second Edition

Programming Example: Largest Number Input: Set of 10 numbers Output: Largest of 10 numbers Solution: Get numbers one at a time. Method larger number: Returns the larger of 2 numbers. For loop: Calls method larger number on each number received and compares to current largest number. Java Programming: From Problem Analysis to Program Design, Second Edition

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++) max = larger(max, num); } System.out.println("The largest number is " + max); Java Programming: From Problem Analysis to Program Design, Second Edition

Sample Run: Largest Number Enter 10 numbers: 10.5 56.34 73.3 42 22 67 88.55 26 62 11 The largest number is 88.55 Java Programming: From Problem Analysis to Program Design, Second Edition

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. Java Programming: From Problem Analysis to Program Design, Second Edition

Void Methods: Syntax Method definition: The general form (syntax) of a void method without parameters is as follows: modifier(s) void methodName() { statements } Method call (within the class): The method call has the following syntax: methodName(); Java Programming: From Problem Analysis to Program Design, Second Edition

Void Methods with Parameters: Syntax Method definition: The definition of a void method with parameters has the following syntax: modifier(s) void methodName (formal parameter list) { statements } Formal parameter list: The formal parameter list has the following syntax: dataType variable, dataType variable, ... Java Programming: From Problem Analysis to Program Design, Second Edition

Void Methods with Parameters: Syntax Method call: The method call has the following syntax: methodName(actual parameter list); Actual parameter list: The actual parameter list has the following syntax: expression or variable, expression or variable, ... Java Programming: From Problem Analysis to Program Design, Second Edition

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. Java Programming: From Problem Analysis to Program Design, Second Edition

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 parameters refer to same object. Java Programming: From Problem Analysis to Program Design, Second Edition

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 an address, saves memory space and time, relative to copying large amount of data. Java Programming: From Problem Analysis to Program Design, Second Edition

Reference Variables as Parameters: type String Java Programming: From Problem Analysis to Program Design, Second Edition

Scope of an Identifier within a Class Local identifier: An identifier that is declared within a method or block and that is visible only within that method or block. Java does not allow the nesting of methods. That is, 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. Note that a block is a set of statements enclosed within braces. A method’s definition can contain several blocks. The body of a loop or an if statement also forms a block. Within a class, outside of every method definition (and block), an identifier can be declared anywhere. Java Programming: From Problem Analysis to Program Design, Second Edition

Scope of an Identifier within a Class Within a method, an identifier that is 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 following method definition, the second declaration of the variable x is illegal: public static void illegalIdentifierDeclaration() { int x; //block double x; //illegal declaration, //x is already declared ... } Java Programming: From Problem Analysis to Program Design, Second Edition

Scope Rules Scope rules of an identifier that is declared within a class and accessed within a method (block) of the class. An identifier, say X, that is 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. Suppose X is an identifier that is 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. Java Programming: From Problem Analysis to Program Design, Second Edition

Scope Rules Example 7-12 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) Java Programming: From Problem Analysis to Program Design, Second Edition

Scope Rules public static int w; public static void two(int one, int z) { char ch; int a; //block three int x = 12; //... } //end block three } Java Programming: From Problem Analysis to Program Design, Second Edition

Scope Rules: Demonstrated Java Programming: From Problem Analysis to Program Design, Second Edition

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. If the number of formal parameters is the same in both methods, the data type of the formal parameters in the order you list must differ in at least one position. Java Programming: From Problem Analysis to Program Design, Second Edition

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. Java Programming: From Problem Analysis to Program Design, Second Edition

Method Overloading 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. Java Programming: From Problem Analysis to Program Design, Second Edition

Method Overloading 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.) Java Programming: From Problem Analysis to Program Design, Second Edition

Method Overloading 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) Java Programming: From Problem Analysis to Program Design, Second Edition

Method Overloading 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.) Java Programming: From Problem Analysis to Program Design, Second Edition

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. Java Programming: From Problem Analysis to Program Design, Second Edition

Programming Example: Data Comparison 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 Java Programming: From Problem Analysis to Program Design, Second Edition

Programming Example: Data Comparison Java Programming: From Problem Analysis to Program Design, Second Edition

Chapter Summary Pre-defined methods User-defined methods: Value-returning methods Void methods Formal parameters Actual parameters Flow of execution Java Programming: From Problem Analysis to Program Design, Second Edition

Chapter Summary 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 Java Programming: From Problem Analysis to Program Design, Second Edition