Chapter 7 UserDefined Methods Java Programming From Problem
Chapter 7: User-Defined Methods Java Programming: From Problem Analysis to Program Design, Second Edition Java Programming: From Problem Analysis to Program Design,
Chapter Objectives s Understand how methods are used in Java programming. s Learn about standard (predefined) methods and discover how to use them in a program. s Learn about user-defined methods. s Examine value-returning methods, including actual and formal parameters. Java Programming: From Problem Analysis to Program Design, Second Edition 2
Chapter Objectives s Explore how to construct and use a valuereturning, user-defined method in a program. s Learn how to construct and user-defined void methods in a program. s Explore variables as parameters. s Learn about the scope of an identifier. s Become aware of method overloading. Java Programming: From Problem Analysis to Program Design, Second Edition 3
Predefined Classes s Methods already written and provided by Java. s Organized as a collection of classes (class libraries). s To use, import package. s Method type: The data type of the value returned by the method. Java Programming: From Problem Analysis to Program Design, Second Edition 4
Predefined Classes Java Programming: From Problem Analysis to Program Design, Second Edition 5
Predefined Classes Java Programming: From Problem Analysis to Program Design, Second Edition 6
Predefined Classes Java Programming: From Problem Analysis to Program Design, Second Edition 7
class Character (Package: java. lang) Java Programming: From Problem Analysis to Program Design, Second Edition 8
class Character (Package: java. lang) Java Programming: From Problem Analysis to Program Design, Second Edition 9
Syntax of Value-Returning Method modifier(s) return. Type method. Name (formal parameter list) { statements } Java Programming: From Problem Analysis to Program Design, Second Edition 10
User-Defined Methods s Value-returning methods: s Used in expressions. s Calculate and return a value. s Can save value for later calculation or print value. s modifiers: public, private, protected, static, abstract, final. s return. Type: Type of the value that the method calculates and returns (using return statement). s method. Name: Java identifier; name of method. Java Programming: From Problem Analysis to Program Design, Second Edition 11
Syntax s Syntax of formal parameter list: data. Type identifier, . . . s Syntax to call a value-returning method: method. Name(actual parameter list) Java Programming: From Problem Analysis to Program Design, Second Edition 12
Syntax s Syntax of the actual parameter list: expression or variable, . . . s Syntax of the return statement: return expr; Java Programming: From Problem Analysis to Program Design, Second Edition 13
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 14
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 15
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 16
Programming Example: Palindrome Number s Palindrome: An integer or string that reads the same forwards and backwards. s Input: Integer or string. s Output: Boolean message indicating whether integer string is a palindrome. Java Programming: From Problem Analysis to Program Design, Second Edition 17
Solution: is. Palindrome Method public static boolean is. Palindrome(String str) { int len = str. length(); int i, j; j = len - 1; for (i = 0; i <= (len - 1) / 2; i++) { if (str. char. At(i) != str. char. At(j)) return false; j--; } return true; } Java Programming: From Problem Analysis to Program Design, Second Edition 18
Sample Runs: Palindrome Number Java Programming: From Problem Analysis to Program Design, Second Edition 19
Sample Runs: Palindrome Number Java Programming: From Problem Analysis to Program Design, Second Edition 20
Flow of Execution s Execution always begins with the first statement in the method main. s User-defined methods execute only when called. s Call to method transfers control from caller to called method. s In the method call statement, specify only actual parameters, not data type or method type. s Control goes back to caller when method exits. Java Programming: From Problem Analysis to Program Design, Second Edition 21
Programming Example: Largest Number s Input: Set of 10 numbers s Output: Largest of 10 numbers s Solution: s Get numbers one at a time. s Method larger number: Returns the larger of 2 numbers. s 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 22
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. next. Double(); max = num; for (count = 1; count < 10; count++) { num = console. next. Double(); max = larger(max, num); } System. out. println("The largest number is " + max); } Java Programming: From Problem Analysis to Program Design, Second Edition 23
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 Java Programming: From Problem Analysis to Program Design, Second Edition 24
Void Methods s Similar in structure to value-returning methods. s Call to method is always stand-alone statement. s Can use return statement to exit method early. Java Programming: From Problem Analysis to Program Design, Second Edition 25
Void Methods: Syntax Method definition: The general form (syntax) of a void method without parameters is as follows: modifier(s) void method. Name() { statements } Method call (within the class): The method call has the following syntax: method. Name(); Java Programming: From Problem Analysis to Program Design, Second Edition 26
Void Methods with Parameters: Syntax Method definition: The definition of a void method with parameters has the following syntax: modifier(s) void method. Name (formal parameter list) { statements } Formal parameter list: The formal parameter list has the following syntax: data. Type variable, . . . Java Programming: From Problem Analysis to Program Design, Second Edition 27
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, . . . Java Programming: From Problem Analysis to Program Design, Second Edition 28
Primitive Data Type Variables as Parameters s A formal parameter receives a copy of its corresponding actual parameter. s If a formal parameter is a variable of a primitive data type: s Value of actual parameter is directly stored. s Cannot pass information outside the method. s Provides only a one-way link between actual parameters and formal parameters. Java Programming: From Problem Analysis to Program Design, Second Edition 29
Reference Variables as Parameters If a formal parameter is a reference variable: s Copies value of corresponding actual parameter. s Value of actual parameter is address of the object where actual data is stored. s Both formal and actual parameters refer to same object. Java Programming: From Problem Analysis to Program Design, Second Edition 30
Uses of Reference Variables as Parameters s Can return more than one value from a method. s Can change the value of the actual object. s 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 31
Reference Variables as Parameters: type String Java Programming: From Problem Analysis to Program Design, Second Edition 32
Scope of an Identifier within a Class s Local identifier: An identifier that is declared within a method or block and that is visible only within that method or block. s Java does not allow the nesting of methods. That is, you cannot include the definition of one method in the body of another method. s 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. s A method’s definition can contain several blocks. The body of a loop or an if statement also forms a block. s 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 33
Scope of an Identifier within a Class s 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 illegal. Identifier. Declaration() { int x; //block { double x; //illegal declaration, //x is already declared . . . } } Java Programming: From Problem Analysis to Program Design, Second Edition 34
Scope Rules s Scope rules of an identifier that is declared within a class and accessed within a method (block) of the class. s An identifier, say X, that is declared within a method (block) is accessible: s Only within the block from the point at which it is declared until the end of the block. s By those blocks that are nested within that block. s Suppose X is an identifier that is declared within a class and outside of every method’s definition (block). s 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. s 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 35
Scope Rules Example 7 -12 public class Scope. Rules { 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 36
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 37
Scope Rules: Demonstrated Java Programming: From Problem Analysis to Program Design, Second Edition 38
Method Overloading: An Introduction s Method overloading: More than one method can have the same name. s Two methods are said to have different formal parameter lists: s If both methods have a different number of formal parameters. s 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 39
Method Overloading public void method. One(int x) void method. Two(int x, double y) void method. Three(double y, int x) int method. Four(char ch, int x, double y) public int method. Five(char ch, int x, String name) These methods all have different formal parameter lists. Java Programming: From Problem Analysis to Program Design, Second Edition 40
Method Overloading public void method. Six(int x, double y, char ch) public void method. Seven(int one, double u, char first. Ch) s The methods method. Six and method. Seven both have three formal parameters, and the data type of the corresponding parameters is the same. s These methods all have the same formal parameter lists. Java Programming: From Problem Analysis to Program Design, Second Edition 41
Method Overloading s Method overloading: Creating several methods within a class with the same name. s 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 42
Method Overloading s The following method headings correctly overload the method. XYZ: public void method. XYZ() method. XYZ(int x, double y) method. XYZ(double one, int y) method. XYZ(int x, double y, char ch) Java Programming: From Problem Analysis to Program Design, Second Edition 43
Method Overloading public void method. ABC(int x, double y) public int method. ABC(int x, double y) s Both these method headings have the same name and same formal parameter list. s These method headings to overload the method. ABC are incorrect. s 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 44
Programming Example: Data Comparison s Input: Data from two different files. s Data format: Course number followed by scores. s Output: Course number, group number, course average. s Solution: s Read from more than one file; write output to file. s Generate bar graphs. s User-defined methods and re-use (calculate. Average and print. Result). s Parameter passing. Java Programming: From Problem Analysis to Program Design, Second Edition 45
Programming Example: Data Comparison Sample Output Course No CSC Group No 1 2 Course Average 83. 71 80. 82 ENG 1 2 82. 00 78. 20 HIS 1 2 77. 69 84. 15 MTH 1 2 83. 57 84. 29 PHY 1 2 83. 22 82. 60 Avg for group 1: 82. 04 Avg for group 2: 82. 01 Java Programming: From Problem Analysis to Program Design, Second Edition 46
Programming Example: Data Comparison Java Programming: From Problem Analysis to Program Design, Second Edition 47
Chapter Summary s Pre-defined methods s User-defined methods: s s Value-returning methods Void methods Formal parameters Actual parameters s Flow of execution Java Programming: From Problem Analysis to Program Design, Second Edition 48
Chapter Summary s Primitive data type variables as parameters: s One-way link between actual parameters and formal parameters (limitations caused). s Reference variables as parameters: s Can pass one or more variables from a method. s Can change value of actual parameter. s Scope of an identifier within a class s Method overloading Java Programming: From Problem Analysis to Program Design, Second Edition 49
- Slides: 49