1 / 89

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

Java Programming: From Problem Analysis to Program Design, 4e. Chapter 7 User-Defined Methods. Chapter Objectives. Learn about user-defined methods Learn how to construct and use user-defined void methods in a program Actual and formal parameters

Download Presentation

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

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods

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

  5. Syntax: Method • There 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.

  6. 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

  7. 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

  8. 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

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

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

  11. Void method: Example (2) public static voiddrawRectangle ( ) { 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(); } }

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

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

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

  15. Formal parameters • 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); • } Method name Formal parameters Modifiers Method heading Formal parameters list Method body Java Programming: From Problem Analysis to Program Design, 4e

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

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

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

  19. 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. Execution begins with the 1st statement in main Flow of Execution – Example(parameters) Public static void main( String args[]) { System.out.println(“Before call”); method(“csc111”); System.out.println(“Aftere call”); } Public static void method( String str) { System.out.println(str); } 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 Before call csc111 After call Java Programming: From Problem Analysis to Program Design, 4e

  21. 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

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

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

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

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

  26. Return Statment • 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 Java Programming: From Problem Analysis to Program Design, 4e

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

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

  29. Return Statement – Equivalent Examples public static double larger(double x, double y) { doublemax; if(x >= y) max = x; else max = y; returnmax; } public static doublelarger(doublex, doubley) { if(x >= y) returnx; else returny; } public static doublelarger(doublex, doubley) { if(x >= y) returnx; returny; } Java Programming: From Problem Analysis to Program Design, 4e

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

  31. 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

  32. Examples (2) - Cont 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, 4e

  33. 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

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

  35. Examples (3) - cont 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, 4e

  36. 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 1100 arr 1100

  37. 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

  38. 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

  39. 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

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

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

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

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

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

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

  46. 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

  47. Relational Operators and Arrays (example) booleanareEqualArrays(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)) ... Java Programming: From Problem Analysis to Program Design, 4e

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

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

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

More Related