Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Chapter 5: METHODS USER-DEFINED METHODS

2 user-defined  We learned that a Java application program is a collection of classes, and that a class is a collection of methods and data members.  use only the method main; all the programming instructions are packed into one method.  For large programs, it is not practical to put the entire programming instructions into one method, You must learn to break the problem into manageable pieces. Java Programming: From Problem Analysis to Program Design, 4e 2

3 Chapter Objectives  Learn about user-defined methods  Learn how to construct and use user-defined void methods in a program  Actual and formal parameters  Explore how to construct and use a value-returning  Explore using variables as parameters  Explore using arrays as parameters. Java Programming: From Problem Analysis to Program Design, 4e 3

4 Chapter Objectives (continued)  Learn about standard (predefined) methods and discover how to use them in a program  Learn about the scope of an identifier  Become aware of method overloading Java Programming: From Problem Analysis to Program Design, 4e 4

5 Why use method Using methods has several advantages:  While working on one method, you can focus on just that part of the program and construct it, debug it, and perfect it.  Different people can work on different methods simultaneously.  If a method is needed in more than one place in a program, or in different programs, you can write it once and use it many times.  Using methods greatly enhances the program’s readability because it reduces the complexity of the method main. Java Programming: From Problem Analysis to Program Design, 4e 5

6 Syntax: Method Java Programming: From Problem Analysis to Program Design, 4e 6

7 Syntax: Method 7 There are 3 different criteria defining types of methods: Modifiers: this criteria is also composed of 3 sub-criteria: »Visibility: public or private (or protected in csc 113) »Shared between all instances or not: class member (static) or instance method. »Override able or not (final): to be discussed in CSC 113. Return type: method with or without (void) return value. Parameters: with or without parameters. Every method have two important elements : Method head: used to declare and define the method. Method call: used to invoke and employ this method.

8 User-Defined Methods 1-Method Head :  To declare a method, the user must specify the following :  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  formal parameter list: The syntax of the formal parameter list is: Java Programming: From Problem Analysis to Program Design, 4e 8

9 User-Defined Methods 2-Method call -The syntax to call a value-returning method is: - Actual parameter list are also called arguments - The syntax of the actual parameter list (arguments) is: Java Programming: From Problem Analysis to Program Design, 4e 9

10 User-Defined Methods Void Methods:  Defined by users.  Call to method is always stand-alone statement  Can use return statement to exit method early (optional) Java Programming: From Problem Analysis to Program Design, 4e 10

11 Void Methods without Parameters: Syntax Method Definition The definition of void method without parameters has the following syntax: modifier(s) void methodName( ) { statements } Method Call A method call has the following syntax: methodName( ) ; To call a method, you use its name.

12 Void method: Example (1) Public static void theMethod( ) { System.out.println(“3”+”+”+”4”+”=“+ (3+4)); }

13 Void method: Example (2) public static void drawRectangle ( ) { System.out.println(“Enter the dimensions of your rectangle ”); int x=read.nextInt(); int y=read.nextInt(); for( int i = 0 ; i < x ; i++ ) { for( int j = 0 ; j < y ; j++ ) System.out.print(“*”); System.out.println(); }

14 Void Methods with Parameters: Syntax Java Programming: From Problem Analysis to Program Design, 4e 14

15 Void Methods with Parameters: Syntax (continued) Java Programming: From Problem Analysis to Program Design, 4e 15 To call a method you use its name, with the actual parameters (if any) in parentheses.

16 Formal parameters Java Programming: From Problem Analysis to Program Design, 4e 16 public static void larger (double x, double y) { if ( x >= y ) System.out.print(“The max is ”+x); else System.out.print(“the max is ”+ y); } Formal parameters Formal parameters list Method name Modifiers Method heading Method body

17 Java Programming: From Problem Analysis to Program Design, 4e 17 Actual parameters larger ( 2.5, 5.4 ); larger ( num1, num2 ); larger ( num1, 33,2 ); Actual parametersMethod call Actual parameters Method call

18 Void method with parameters: Example public static void drawRectangle (int x, int y ) { for( int i = 0 ; i < x ; i++ ) { for( int j = 0 ; j < y ; j++ ) System.out.print(“*”); System.out.println(); }

19 Void method with parameters: Example (print area of a rectangle) public static void areaofRectangle (int l, int w ) { System.out.println( “the Area of the rectangle is” + (l*w)); }

20 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 Java Programming: From Problem Analysis to Program Design, 4e 20

21 Flow of Execution – Example (void) Java Programming: From Problem Analysis to Program Design, 4e 21 Public static void theMethod( ) { System.out.println(“in method “); } Public static void main( String args[]) { System.out.println(“Before call”); theMethod(); System.out.println(“Aftere call”); } Before call In method After call Execution begins with the 1st statement in main Call to method transfers control from caller to called method Control goes back to caller when method exits

22 Flow of Execution – Example (parameters) Java Programming: From Problem Analysis to Program Design, 4e 22 Public static void method( String str) { System.out.println(str); } Public static void main( String args[]) { System.out.println(“Before call”); method(“csc111”); System.out.println(“Aftere call”); } Before call csc111 After call Execution begins with the 1st statement in main Call to method transfers control from caller to called method and passing parameter from main to method Control goes back to caller when method exits

23 Value returning Methods Value-returning methods  Used in expressions  Calculate and return a value  Can save value for later calculation or print value Java Programming: From Problem Analysis to Program Design, 4e 23

24 Value returning Methods: Syntax Java Programming: From Problem Analysis to Program Design, 4e 24

25 Value returning Methods: Syntax Java Programming: From Problem Analysis to Program Design, 4e 25

26 26Java Programming: From Problem Analysis to Program Design, 4e Value returning Methods: Actual and formal parameters

27 27Java Programming: From Problem Analysis to Program Design, 4e Value returning Methods: Actual and formal parameters

28 Return Statment Java Programming: From Problem Analysis to Program Design, 4e 28 Syntax: return statement return statement will return the flow of the program from the method to the main method. It is also used to return the value resulting from the method to the main method to be used their. -The return statement has the following syntax: return expr/value/variable; Important note: 1-value returning methods must have a return statement 2- The value they return must be the same as the method data type

29 Flow of Execution – Example (no parameters) Java Programming: From Problem Analysis to Program Design, 4e 29 Public static int theMethod( ) { int x= 1000; return x; } Public static void main( String args[]) { System.out.println(“Before call”); System.out.println( theMethod()); System.out.println(“Aftere call”); } Before call 1000 After call Execution begins with the 1st statement in main Call to method transfers control from caller to called method Control goes back to caller when method exits

30 Flow of Execution – Example (with parameters) Java Programming: From Problem Analysis to Program Design, 4e 30 Public static int method(int num ) { return ++num; } Public static void main( String args[]) { System.out.println(“Before call”); System.out.println( method(6)); System.out.println(“Aftere call”); } Before call 7 After call Execution begins with the 1st statement in main Call to method transfers control from caller to called method Control goes back to caller when method exits (return in this e.g)

31 Return Statement – Equivalent Examples public static double larger(double x, double y) { double max; if (x >= y) max = x; else max = y; return max; } public static double larger(double x, double y) { if (x >= y) return x; else return y; } 31 Java Programming: From Problem Analysis to Program Design, 4e public static double larger(double x, double y) { if (x >= y) return x; return y; }

32 32Java Programming: From Problem Analysis to Program Design, 4e The int variable num contains the number that we want to compute the factorial Examples (1) public static int factorial ( int num ) { int fact=1; for ( int i=2;i<=num;i++) fact=fact*i; return fact; }

33 Examples (2): Palindrome Number  Palindrome: integer or string that reads the same forwards and backwards  The method isPalindrome takes a string as a parameter and returns true if the string is a palindrome, false otherwise Java Programming: From Problem Analysis to Program Design, 4e 33

34 Java Programming: From Problem Analysis to Program Design, 4e 34 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; } Examples (2) - Cont

35 Example (3):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 Java Programming: From Problem Analysis to Program Design, 4e 35

36 Java Programming: From Problem Analysis to Program Design, 4e 36 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); } Examples (3) - Cont

37 Sample Run: Largest Number Java Programming: From Problem Analysis to Program Design, 4e 37 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 Examples (3) - cont

38 Week 12 Primitive VS. Reference Variables 38 Java Programming: From Problem Analysis to Program Design, 4e

39 39 Primitive VS. Reference Variables Primitive variables hold values of primitive data types. Example: int x = 5; x is primitive variable Instance variables hold references of objects: the location (memory address) of objects in memory. Example: int [] arr = {1,2,3,4,5}; arr is reference variable, it carries the address of the location of the array x 1 1 1100 12345 arr 1100

40 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, 4e 40

41 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 Java Programming: From Problem Analysis to Program Design, 4e 41

42 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 Java Programming: From Problem Analysis to Program Design, 4e 42

43 Declaring Arrays as Formal Parameters to Methods Java Programming: From Problem Analysis to Program Design, 4e 43  A general syntax to declare an array as a formal parameter public static void arraysAsFormalParameter(int[] listA, double[] listB, int num) { //... } int[] intList = new int[10]; double[] doubleNumList = new double[15]; int number; arraysAsFormalParameter(intList, doubleNumList, number);

44 Arrays as Parameter to Methods 44 Java Programming: From Problem Analysis to Program Design, 4e

45 Methods for Array Processing 45 Java Programming: From Problem Analysis to Program Design, 4e

46 Methods for Array Processing (continued) 46

47 Methods for Array Processing (continued) Java Programming: From Problem Analysis to Program Design, 4e 47

48 Methods for Array Processing (elements of array as par.) Java Programming: From Problem Analysis to Program Design, 4e 48

49 49 Methods for Array Processing (search) public static int seqSearch(int[] list, int listLength, int searchItem) { int loc; boolean found = false; loc = 0; while (loc < listLength && !found) if (list[loc] == searchItem) found = true; else loc++; if (found) return loc; else return -1; } Java Programming: From Problem Analysis to Program Design, 4e 49

50 Relational Operators and Arrays (example) Java Programming: From Problem Analysis to Program Design, 4e 50 boolean areEqualArrays (int[] firstArray, int[] secondArray) { if (firstArray.length != secondArray.length) return false; for (int index = 0; index < firstArray.length; index++) if (firstArray[index] != secondArray[index]) return false; return true; } if (areEqualArrays(listA, listB))...

51 Arrays and Variable Length Parameter List Java Programming: From Problem Analysis to Program Design, 4e 51  The syntax to declare a variable length formal parameter (list) is: dataType... identifier

52 Arrays and Variable Length Parameter List (continued) Java Programming: From Problem Analysis to Program Design, 4e 52

53 Arrays and Variable Length Parameter List (continued) Java Programming: From Problem Analysis to Program Design, 4e 53

54 Arrays and Variable Length Parameter List (continued) Java Programming: From Problem Analysis to Program Design, 4e 54 A method can have both a variable length formal parameter and other formal parameters; consider the following method heading: public static void myMethod(String name, double num, int... intList) The formal parameter name is of type String, the formal parameter num is of type double, and the formal parameter intList is of variable length The actual parameter corresponding to intList can be an int array or any number of int variables and/or int values

55 Arrays and Variable Length Parameter List (continued) Java Programming: From Problem Analysis to Program Design, 4e 55  A method can have at most one variable length formal parameter  If a method has both a variable length formal parameter and other types of formal parameters, then the variable length formal parameter must be the last formal parameter of the formal parameter list

56 Reference Variables as Parameters: type String (special case) Java Programming: From Problem Analysis to Program Design, 4e 56

57 Reference Variables as Parameters: type String (continued) Java Programming: From Problem Analysis to Program Design, 4e 57

58 Reference Variables as Parameters: type String (continued) Java Programming: From Problem Analysis to Program Design, 4e 58

59 Reference Variables as Parameters: type String (continued) Java Programming: From Problem Analysis to Program Design, 4e 59

60 60Java Programming: From Problem Analysis to Program Design, 4e Reference Variables as Parameters: type String (continued) String str = "Hello"; //Line 5

61 61Java Programming: From Problem Analysis to Program Design, 4e Reference Variables as Parameters: type String (continued) stringParameter(str); //Line 7

62 62Java Programming: From Problem Analysis to Program Design, 4e Reference Variables as Parameters: type String (continued) pStr = "Sunny Day"; //Line 14

63 Reference Variables as Parameters: type String (continued) Java Programming: From Problem Analysis to Program Design, 4e 63 Variables before the statement in Line 8 executes

64 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 Java Programming: From Problem Analysis to Program Design, 4e 64

65 Predefined Classes (continued) 65 Java Programming: From Problem Analysis to Program Design, 4e

66 66 Predefined Classes (continued)

67 Java Programming: From Problem Analysis to Program Design, 4e 67

68 Java Programming: From Problem Analysis to Program Design, 4e 68 Predefined Classes (continued)

69 Java Programming: From Problem Analysis to Program Design, 4e 69 random()return a value of type double greater than or equal to 0.0 and less than 1.0.

70 Example Java Programming: From Problem Analysis to Program Design, 4e 70 double x = Math.pow(3,2); double area = Math.PI*radius*radius; - If you use the static import statement, you can omit the name of class import static java.lang.Math.*; double x = pow(3,2);

71 Generating random variable in range Java Programming: From Problem Analysis to Program Design, 4e 71  General form randomNum = (int) (Math.random()*range عدد الالمنت)+minimum ;  Rollin dice int dice2 = (int) (Math.random() * 6) + 1;

72 class Character (Package: java.lang ) Java Programming: From Problem Analysis to Program Design, 4e 72

73 Java Programming: From Problem Analysis to Program Design, 4e 73 class Character (Package: java.lang ) (continued)

74 Java Programming: From Problem Analysis to Program Design, 4e 74 class Character (Package: java.lang ) (continued)

75 Week 13 Scope and overloading 75 Java Programming: From Problem Analysis to Program Design, 4e

76 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 Java Programming: From Problem Analysis to Program Design, 4e 76

77 Scope of an Identifier within a Class (continued) Java Programming: From Problem Analysis to Program Design, 4e 77  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

78 Scope of an Identifier within a Class (continued) Java Programming: From Problem Analysis to Program Design, 4e 78  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

79 Scope of an Identifier within a Class (continued) public static void illegalIdentifierDeclaration() { int x; //block { double x; //illegal declaration, //x is already declared... } Java Programming: From Problem Analysis to Program Design, 4e 79

80 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 Java Programming: From Problem Analysis to Program Design, 4e 80

81 Scope Rules (continued) Example 7-11 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, 4e 81

82 Scope Rules (continued) Java Programming: From Problem Analysis to Program Design, 4e 82  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

83 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) { //... } Java Programming: From Problem Analysis to Program Design, 4e 83

84 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) { //... } public static int w; public static void two(int one, int z) { char ch; int a; { int x = 12; } //... } Java Programming: From Problem Analysis to Program Design, 4e 84 static final double rate static int z; static double t; main int num; double x, z;char ch; Method one one(int x, char y) public static int w; Method two two(int one, int z) char ch; int a; int x = 12;

85 Scope Rules: Demonstrated (continued) Java Programming: From Problem Analysis to Program Design, 4e 85

86 Scope Rules: Demonstrated Java Programming: From Problem Analysis to Program Design, 4e 86

87 Scope Rules – Scanner Example Java Programming: From Problem Analysis to Program Design, 4e 87 public class ScopeRules { static Scanner read=new Scanner (System.in); public static void main(String[] args){ int number = read.nextInt(); //… } } public class ScopeRules { public static void main(String[] args){ Scanner read=new Scanner (System.in); int number = read.nextInt(); //… } } Can be accessed from any method (static & non-static) including main, ‘Local ‘ accessed from main only public class ScopeRules { Scanner read=new Scanner (System.in); public static void main(String[] args){ int number = read.nextInt(); //… } } Can be accessed from non-static method only

88 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 Java Programming: From Problem Analysis to Program Design, 4e 88

89 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, 4e 89

90 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 Java Programming: From Problem Analysis to Program Design, 4e 90

91 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 Java Programming: From Problem Analysis to Program Design, 4e 91

92 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) Java Programming: From Problem Analysis to Program Design, 4e 92

93 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 Java Programming: From Problem Analysis to Program Design, 4e 93

94 Chapter Summary  Predefined methods  User-defined methods  Value-returning methods  Void methods  Formal parameters  Actual parameters  Flow of Execution Java Programming: From Problem Analysis to Program Design, 4e 94

95 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 Java Programming: From Problem Analysis to Program Design, 4e 95


Download ppt "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."

Similar presentations


Ads by Google