Download presentation
Presentation is loading. Please wait.
Published byDaniella Flowers Modified over 8 years ago
1
Chapter 7: User-Defined Methods J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Third Edition Third Edition
2
2 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.
3
3 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.
4
4 Given that f(x) = 2x + 5 then: f(1) = 7 f(4) = 13 In Java, concept of methods is similar to function in algebra. Every method has a name, arguments and does some computations. Methods
5
5 We've already seen some methods: Math.pow(x,y) = x y Method name: power. Method type or return value: double. Method arguments or parameters: 2 x, y. Data type of parameters: both double. In this chapter we're going to introduce more java methods (predefined) and give you the information you need to write your own methods (user defined). Methods
6
6 Predefined Methods Methods already written and provided by Java like pow from class Math. Organized as a collection of classes (class libraries). To use, import package. Method type: The data type of the value returned by the method.
7
7 Math.sqrt(x) = √ x for x >= 0.0 Method name: square root. Method type or return value: double Method arguments or parameters: 1 x Data type of parameter: double Ex: Math.sqrt(2.25) = 1.5; Predefined Methods
8
8 Predefined Classes
9
9
10
10 Predefined Classes
11
11 class Character (Package: java.lang )
12
12 class Character (Package: java.lang )
13
13 Using Predefined Methods To use any public and static method in a class: import the class from the package. Call the method using the following syntax: className.methodName(parameters) Ex: Math.min(2,4); // 2 Character.isDigit(‘*’); //false Remember, java automatically imports classes from the package java.lang.
14
14 JDK 5.0 introduces the following import statement: import static packageName.ClassName.*; This is called static import statement. With it you have the choice when using public static method of a class: Ex: import static java.lang.Math.*; Math.pow(2,4); Or simply pow(2,4); Using Predefined Methods
15
15 Using Predefined Methods Example 7_1 import static java.lang.Math.*; import static java.lang.Character.*; public class Example7_1{ public static void main(String[] args) { int x; double u,v; System.out.println("Line 1: Uppercase a is " +toUpperCase('a') ); u = 4.2; v = 3.0; System.out.printf("Line 4: %.1f to the power of %.1f = %.2f%n", u,v, pow(u,v) ); System.out.printf("Line 5: 5 to the power of 4 = %.2f%n",pow(5,4) ); u = u + Math.pow(3,3) ; System.out.printf("Line 7: u = %.2f%n",u); x = -15; System.out.printf("Line 9: Absolute value of %d = %d%n", x,abs(x) ); } } Line 1: Uppercase a is A Line 4: 4.2 to the power of 3.0 = 74.09 Line 5: 5 to the power of 4 = 625.00 Line 7: u = 31.20 Line 9: Absolute value of -15 = 15
16
16 Java does not provide every method that you will ever need. So you must learn how to write your own methods! User-defined methods in java are classified into two categories: Value-returning methods: method that have a return type. Void methods: methods that do not have a return type. User-Defined Methods
17
17 Whether user or predefined it is used in either: An assignment statement. Or an output statement. Or a parameter in a method call. Ex: double x; x = Math.pow(2,4); //assignment stmt System.out.println(Math.pow(2,4)); //output stmt x= Math.pow(2,Math.pow(2,2)); //method call parm. Value-Returning Method
18
18 Every method has a heading and a body. Ex: Method abs (absolute) in class Math. public static int abs(int number) { if (number < 0 ) number = -number; return number; } number is called formal parameter. Value-Returning Method Heading Body
19
19 Suppose: heading of method pow in class Math : public static double pow(double base, double exponent) declaration: double x, u = 2.5, v = 3.0; Method call: x= Math.pow(u,v); // value of u & v are passed to method pow //value of u is copied into base //value of v is copied into exponent u & v are called actual parameter. base & exponent are called formal parameter. Formal parameter: variable decaled in method heading. Actual parameter : variable or expression listed in method call. Value-Returning Method
20
20 Syntax of Value-Returning Method modifier(s) returnType methodName(formalParameters) { statements } User-Defined Methods In this syntax: 1.modifiers : indicates the visibility of the method, that is, where in a program the method can be called. Some modifiers are: public, private, protected, static, abstract, and final. You can select one among public, private or protected. Similarly, you can select between static or abstract. Meanwhile, we will use public and/or static only.
21
21 2.returnType: Type of the value that the method calculates and returns (using return statement). 3.methodName: Java identifier; name of method. 4.statements enclosed between { } form the body of the method. modifier(s) returnType methodName(formalParameters) { statements } Syntax of Value-Returning Method User-Defined Methods
22
22 Syntax Syntax of formal parameter list: dataType identifier, dataType identifier,... Syntax to call a value-returning method: methodName(actual parameter list) Syntax of the actual parameter list: expression or variable, expression or variable,...
23
23 Notes Method's formal parameter can be empty. modifiers returnType methodName() If no formal parameter no actual parameter in method call. Method call: methodName(); In method call: number and data types of actual parameters MUST match formal parameters. Ex: Math.pow(4); // syntax error!!
24
24 Syntax return statement Syntax of the return statement: return expr ; expr data type should match return type of the method. expr can be: variable: return x; value: return 5; expression: return (x+5);
25
25 User defined Method - larger Method larger compares two numbers and returns the larger of the two. public static double larger(double x, double y) { double max; if (x >= y) max = x; else max = y; return max; }
26
26 Equivalent larger Method Definitions public static double larger(double x, double y) { if (x >= y) return x; else return y; }
27
27 Equivalent larger Method Definitions public static double larger(double x, double y) { if (x >= y) return x; return y; } Execution of return statement terminates the function. Thus, all subsequent statements are skipped.
28
28 compareThree uses method larger to determine the largest of three numbers. public static double compareThree(double x, double y, double z) { return larger(x, larger(y, z)); } User Defined Method - compareThree
29
29 import java.util.*; publicclass LargerNumber public class LargerNumber { public static void main(String[] args) { static Scanner console = new Scanner(System.in); public static void main(String[] args) { double num1, num2; System.out.println("Line 2: Larger of 5.6 and 10.8 is " + larger(5.6,10.8) ); System.out.print("Line 3: Enter two numbers: "); num1 = console.nextDouble(); num2 = console.nextDouble(); System.out.println(); System.out.println("Line 7: Larger of " + num1 + " and " + num2 + " is " larger(num1,num2) ); System.out.println("Line 8: Largest of 23.5, 34.6, " + "and 12 is " + compareThree(23.5,34.6,12) ); } // end main method User defined Method – final program
30
30 public static double larger(double x, double y) { if(x >= y) return x; else return y; } // end larger method public static double compareThree(double x, double y, double z) { return larger(x, larger(y, z)); } // end compareThree method } } // end LargerNumber class User defined Method – final program Line 2: Larger of 5.6 and 10.8 is 10.8 Line 3: Enter two numbers: 5 7 Line 7: Larger of 5.0 and 7.0 is 7.0 Line 10: Largest of 23.5, 34.6, and 12 is 34.6
31
31 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.
32
32 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; }
33
33 Sample Runs: Palindrome Number
34
34 Sample Runs: Palindrome Number
35
35 Flow of Execution Execution always begins with the first statement in the method main. You can put methods within a class in any order. A value returning method MUST return a value. 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.
36
36 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.
37
37 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); }
38
38 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
39
39 Void Methods Methods that do not have a return type. Similar in structure to value-returning methods. Call to method is always stand-alone statement. Can use return statement to exit method early.
40
40 Void Methods without Parameters 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();
41
41 Void Methods with Parameters Method definition: The definition of a void method with parameters has the following syntax: modifier(s) void methodName(formalParameterList) { statements } Formal parameter list: The formal parameter list has the following syntax: dataType variable, dataType variable,...
42
42 Void Methods with Parameters 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,...
43
43 public class Shapes { public static void main (String args[]) { square(3); System.out.println(); rect(2,4); } public static void rect(int x, int y) { for ( int i = 1 ; i <= x * y ; i++ ) { System.out.print("*"); if (i % y == 0) System.out.println(); } } public static void square(int x) { for (int i =1; i <= x * x; i++) { System.out.print("*"); if (i % x == 0) System.out.println(); } } *** *** ******* Void Methods with Parameters
44
44 Guidelines for Using Methods Pick meaningful names. celsiusToFahrenheitConverter is a much better name than ctfc. A method should have a primary purpose - it should do one thing well. If you're trying to do two or more things, think about breaking them up into their own methods. Use as many parameters as you need but, as a guide, more than six is hard to read and often unnecessary. Choose meaningful parameter names. celsiusValue means a lot more than n or x. Every parameter must have a type. If you have specified a value-return type for the method, you must use a return statement.
45
45 Recall that java has 2 categories of variables: Primitive type variables: directly store data into their memory space. Reference variables: cannot directly store data in its memory space. Instead, they stores the memory location, that is, the address of the memory space where the actual data is stored. Recall…
46
46 int x; x=45; String str; str = “java programming”; Recall…
47
47 In reality, str = “Java Progrmming” is equivalent to String str = new String("Java Programming"); In java new is an operator that causes the system to: 1.Allocate memory space of a specific type, 2.Store data in that space, 3.Return the address of that space. Recall…
48
48 String calss type str object of that class An object is an instance of a class and the operator new is used to instantiate an object. In java, any variable declared using a class is a reference variable. Recall…
49
49 Primitive Data Type Variables as Parameters When a method is called: The value of the actual parameter is copied into the corresponding formal 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.
50
50 Primitive Data Type Variables as Parameters Example7_7 Line 2: Before calling the method funcPrimFormalParam, number = 6 Line 5: In the methodfuncPrimFormalParam, beforechanging, num = 6 Line 7: In the method funcPrimFormalParam, after changing, num = 15 Line 4: After calling the method funcPrimFormalParam, number = 6
51
51 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.
52
52 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.
53
53 Reference Variables as Parameters: type String
54
54 Line 2: str before calling the method stringParameter: Hello Line 5: In the method stringParameter Line 6: pStr before changing its value: Hello Line 8: pStr after changing its value: Sunny Day Line 4: str after calling the method stringParameter: Hello
55
55 The preceding example shows that you should be careful when passing String variables as parameters. If you want to pass strings as parameters to methods and want to change the actual parameters, you can use the class StringBuffer. Reference Variables as Parameters: type String
56
56 Recall, identifier is the name of something in java such as variables or methods. Are we allowed to access (use) any identifier anywhere in the program? The answer is NO. Certain rules exist that we must follow to access an identifier. scope The scope of identifier refers to what other parts of the program can see an identifier, i.e., where it is accessible. Scope of an Identifier within a Class
57
57 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. Within a class Any method can call any other method Exception: static method cannot call a non-static method Java does not allow the nesting of methods. That is, you cannot include the definition of one method in the body of another method.
58
58 Scope of an Identifier within a Class 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.
59
59 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... } Scope of an Identifier within a Class
60
60 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.
61
61 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) { //... } Scope Rules
62
62 public static int w; public static void two(int one, int z) { char ch; int a; //block three { int x = 12; //... } //end block three //... } Scope Rules
63
63 Scope Rules: Demonstrated
64
64 More Examples int x = 6; int y = 2; if (x > 5) { int x = 5; y = y + x; } What will the values of x & y be after this code segment?
65
65 It is often useful to have multiple versions of the same method that differ in their parameters. This idea of several methods with the same name is called METHOD OVERLOADING. Method Overloading: An Introduction
66
66 The max(x,y) from class Math method is one example. It has many versions which take different arguments: static int max(int x, int y) or static double max(double x, double y ), etc. The Java compiler works out which version of a method with a given name is meant from the parameters passed in the call. The factors taken into account are: – The number of actual parameters. – The types of actual parameters. – The order in which actual parameters are passed. Method Overloading: An Introduction
67
67 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.
68
68 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.
69
69 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.
70
70 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.)
71
71 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)
72
72 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.)
73
73 Chapter Summary Pre-defined methods User-defined methods: Value-returning methods Void methods Formal parameters Actual parameters Flow of execution
74
74 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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.