Chapter 7 UserDefined Methods Chapter Objectives Understand how

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

Chapter Objectives Ø Explore how to construct and use a value- returning, user-defined method in a program Ø Learn how to construct and user-defined void methods in a program Ø Explore variables as parameters Ø Learn about the scope of an identifier Ø Become aware of method overloading

Advantages of using methods Ø Methods are the building blocks or modules of classes and of systems built from many classes Predefined methods are supplied within Java ] User defined methods originate from developers ] Allows the developer to write, debug, and integrate one module at a time in a larger system Ø Allows many developers to simultaneously develop different components of a larger system Ø Improves readability and ease of maintenance of the system Ø

Methods Ø The concept of a method is similar to the mathematical concept of a function Ø A function has ] A result or a value ] A series of arguments ] Functional form Ø A method either ] Evaluates to a result (value) of a particular type ] Modifies or manipulates its arguments (e. g. prints)

Syntax: Value-Returning Method modifier(s) return. Type method. Name(formal parameter list) { statements } Syntax: Void Method modifier(s) void method. Name(formal parameter list) { statements }

Predefined Classes and Methods Ø Methods already written and provided by Java Ø Organized as a collection of classes (class libraries) Ø To use: import package or class Ø Classname. methodname(argument list)

class Math (Package: java. lang)

class Math (Package: java. lang)

class Character (Package: java. lang)

class Character (Package: java. lang)

class Character (Package: java. lang)

Value-Returning Method modifier(s) return. Type method. Name(formal parameter list) { statements; return expr; } Ø The definition of the method has two components The body of the method, the statements between {}, the code required to implement the method and return the value ] The heading of the method, the line defining modifiers, return. Type, method. Name and formal parameters or arguments ]
![User-Defined Methods Ø Value-returning methods Used in expressions ] Calculate and return a value User-Defined Methods Ø Value-returning methods Used in expressions ] Calculate and return a value](http://slidetodoc.com/presentation_image_h2/7a7ab462a65bb7d095950c4e5b0d7931/image-14.jpg)
User-Defined Methods Ø Value-returning methods Used in expressions ] Calculate and return a value ] Can be used in the expression in an assignment statement to save value for later use ] Modifiers: public, private, protected, static, abstract, final Ø return. Type: Ø type of value that the method calculates and returns (using return statement) ] Type of expression formed by call of method ] Ø method. Name: Java identifier; name of method

Syntax: Formal Parameter List The syntax of the formal parameter list is: data. Type identifier, . . . Method Call The syntax to call a value-returning method is: method. Name(actual parameter list) Syntax: Actual Parameter List The syntax of the actual parameter list is: expression or variable, . . .

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

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

Programming Example: Palindrome Number Ø Palindrome: integer or string that reads the same forwards and backwards Ø Input: integer or string Ø Output: Boolean message indicating whether integer string is a palindrome

Solution: is. Palindrome Method

Flow of 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 Ø

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 2 numbers ] For loop: calls method largest number on each number received and compares to current largest number ]

Void Methods Ø Similar in structure to value-returning methods Ø No method type Ø Call to method is always stand-alone statement Ø Can use return statement to exit method early Ø Return statement does not return the value of an expression

Void Methods with no parameters: Syntax Ø Method Definition modifier(s) void method. Name( formal parameter list) { statements } Ø Method Call (Within the Class) method. Name();

Void Methods with Parameters: Syntax Method Definition of a void method with parameters modifier(s) void method. Name(formal parameter list) { statements } Formal Parameter List The formal parameter list has the following syntax: data. Type variable, . . .

Void Methods with Parameters: Syntax Method Call The method call has the following syntax: method. Name(actual parameter list); Actual Parameter List The actual parameter list has the following syntax: expression or variable, . . .

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
![Reference Variables as Parameters Ø If a formal parameter is a reference variable ] Reference Variables as Parameters Ø If a formal parameter is a reference variable ]](http://slidetodoc.com/presentation_image_h2/7a7ab462a65bb7d095950c4e5b0d7931/image-27.jpg)
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 object where actual data is stored ] Both formal and actual parameter refer to same object

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

Reference Variables as Parameters: type String

Scope of an Identifier Within a Class Ø Scope (of an identifier): refers to those parts of a program where the identifier is accessible Ø Local variables: variables declared within a method (or block) Ø Within a class ] Any method can call any other method ] Exception: static method cannot call a nonstatic method
![Scope Rules Ø Identifier declared within a block is accessible ] Only within the Scope Rules Ø Identifier declared within a block is accessible ] Only within the](http://slidetodoc.com/presentation_image_h2/7a7ab462a65bb7d095950c4e5b0d7931/image-31.jpg)
Scope Rules Ø Identifier declared within a block is accessible ] Only within the block from the point at which it is declared until the end of the block ] By those blocks nested within that block if the nested block does not have an identifier with the same name as the identifier in the outside block *Outside block: block that encloses nested block

Scope Rules: Demonstrated public class Scope. Rules { static final double rate = 10. 50; static int z; static double t; public static int w; public static void two(int one, int z) { char ch; int a; public static void main(String[] args) { int num; double x, z; char ch; //block three { int x = 12; //. . . }//end block three //. . . } public static void one(int x, char y) { //. . . } }

Scope Rules: Demonstrated

Method Overloading: An Introduction Method overloading: more than one method can have the same name Ø Overloading Rules Ø Every method must have a different number of formal parameters OR ] If the number of formal parameters is the same, then the data type of the formal parameter (in the order listed), must differ in at least one position ] Types of parameters determine which method executes ]

Programming Example: Data Comparison Input: Data from 2 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 (calculate. Average and print. Result) ] Parameter passing ]
![Chapter Summary Ø Predefined methods Ø User-defined methods ] Value-returning methods ] Void methods Chapter Summary Ø Predefined methods Ø User-defined methods ] Value-returning methods ] Void methods](http://slidetodoc.com/presentation_image_h2/7a7ab462a65bb7d095950c4e5b0d7931/image-36.jpg)
Chapter Summary Ø Predefined methods Ø User-defined methods ] Value-returning methods ] Void methods ] Formal parameters ] Actual parameters Ø Flow of Execution
![Chapter Summary Ø Primitive data type variables as parameters ] One-way link between actual Chapter Summary Ø Primitive data type variables as parameters ] One-way link between actual](http://slidetodoc.com/presentation_image_h2/7a7ab462a65bb7d095950c4e5b0d7931/image-37.jpg)
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
- Slides: 37