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

Slides:



Advertisements
Similar presentations
Chapter 6: User-Defined Functions I
Advertisements

Procedural programming in Java
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Starting Out with Java: From Control Structures through Objects Fourth.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 7: User-Defined Functions II.
Chapter 6: User-Defined Functions I
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Chapter 6: User-Defined Functions I
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Chapter 7: User-Defined Methods
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.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
CHAPTER 5 FUNCTIONS I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Procedural programming in Java Methods, parameters and return values.
Chapter 5: Control Structures II
Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter 5: Methods.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
CHAPTER 6 USER-DEFINED FUNCTIONS Made By- Kartik Belwal.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Chapter 7: User-Defined Methods J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Third Edition Third.
Functions + Overloading + Scope
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Reference: COS240 Syllabus
Chapter 6: User-Defined Functions I
Chapter 7: User-Defined Functions II
Java Programming: Guided Learning with Early Objects
Chapter 5: Control Structures II
User-Defined Functions
Chapter 6 Methods: A Deeper Look
Group Status Project Status.
CHAPTER 6 GENERAL-PURPOSE METHODS
Chapter 7: User-Defined Functions II
Chapter 6: User-Defined Functions I
Classes, Objects and Methods
Presentation transcript:

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

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

3Java Programming: From Problem Analysis to Program Design, 5e Chapter Objectives (continued) 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

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

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

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

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

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

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

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

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

12Java Programming: From Problem Analysis to Program Design, 5e To simplify the use of (public) static methods of a class, Java 5.0 introduces the following import statements: These are called static import statements. After including such statements in your program, when you use a (public) static method (or any other public static member) of a class, you can omit the name of the class and the dot operator.

13Java Programming: From Problem Analysis to Program Design, 5e

14Java Programming: From Problem Analysis to Program Design, 5e

15Java Programming: From Problem Analysis to Program Design, 5e

16Java Programming: From Problem Analysis to Program Design, 5e

17Java Programming: From Problem Analysis to Program Design, 5e Syntax: Value-Returning Method

18Java Programming: From Problem Analysis to Program Design, 5e User-Defined Methods Value-returning methods –Used in expressions –Calculate and return a value –Can save value for later calculation or print value 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

19Java Programming: From Problem Analysis to Program Design, 5e Syntax Syntax: formal parameter list -The syntax of the formal parameter list is: Method call -The syntax to call a value-returning method is:

20Java Programming: From Problem Analysis to Program Design, 5e Syntax (continued) Syntax: return statement -The return statement has the following syntax: return expr; Syntax: actual parameter list -The syntax of the actual parameter list is:

21Java Programming: From Problem Analysis to Program Design, 5e Equivalent Method Definitions public static double larger(double x, double y) { double max; if (x >= y) max = x; else max = y; return max; }

22Java Programming: From Problem Analysis to Program Design, 5e

23Java Programming: From Problem Analysis to Program Design, 5e

24Java Programming: From Problem Analysis to Program Design, 5e Equivalent Method Definitions (continued) public static double larger(double x, double y) { if (x >= y) return x; else return y; }

25Java Programming: From Problem Analysis to Program Design, 5e Equivalent Method Definitions (continued) public static double larger(double x, double y) { if (x >= y) return x; return y; }

26Java Programming: From Problem Analysis to Program Design, 5e The int variable num contains the desired sum to be rolled

27Java Programming: From Problem Analysis to Program Design, 5e Palindrome Number Palindrome: integer or string that reads the same forward and backward The method isPalindrome takes a string as a parameter and returns true if the string is a palindrome, false otherwise

28Java Programming: From Problem Analysis to Program Design, 5e 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; }

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

30Java Programming: From Problem Analysis to Program Design, 5e 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 two numbers –For loop: calls method largest number on each number received and compares to current largest number

31Java Programming: From Problem Analysis to Program Design, 5e 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); }

32Java Programming: From Problem Analysis to Program Design, 5e Sample Run: Largest Number Sample Run Enter 10 numbers: The largest number is 88.55

33Java Programming: From Problem Analysis to Program Design, 5e Void Methods Similar in structure to value-returning methods Call to method is always stand-alone statement Can use return statement to exit method early

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

35Java Programming: From Problem Analysis to Program Design, 5e Void Methods with Parameters: Syntax (continued)

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

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

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

39Java Programming: From Problem Analysis to Program Design, 5e Reference Variables as Parameters: type String

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

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

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

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

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

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

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

47Java Programming: From Problem Analysis to Program Design, 5e The class StringBuffer contains the method append, which allows you to append a string to an existing string, and the method delete, which allows you to delete all the characters of the string The assignment operator cannot be used with StringBuffer variables; you must use the operator new (initially) to allocate memory space for a string

48Java Programming: From Problem Analysis to Program Design, 5e

49Java Programming: From Problem Analysis to Program Design, 5e

50Java Programming: From Problem Analysis to Program Design, 5e

51Java Programming: From Problem Analysis to Program Design, 5e

52Java Programming: From Problem Analysis to Program Design, 5e

53Java Programming: From Problem Analysis to Program Design, 5e Primitive Type Wrapper Classes as Parameters If a formal parameter is of the primitive data type and the corresponding actual parameter is a variable, then the formal parameter cannot change the value of the actual parameter Only reference variables can pass values outside the method (except, of course, for the return value) Corresponding to each primitive data type, Java provides a class so that the values of primitive data types can be wrapped in objects The class Integer does not provide a method to change the value of an existing Integer object The same is true of other wrapper classes

54Java Programming: From Problem Analysis to Program Design, 5e Primitive Type Wrapper Classes as Parameters (continued) If we want to pass a String object as a parameter and also change that object, we can use the class StringBuffer Java does not provide any class that wraps primitive type values in objects and when passed as parameters changes their values If a method returns only one value of a primitive type, then you can write a value-returning method If you encounter a situation that requires you to write a method that needs to pass more than one value of a primitive type, then you should design your own classes Appendix D provides the definitions of such classes and shows how to use them in a program

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

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

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

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

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

Scope Rules (continued) 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 Java Programming: From Problem Analysis to Program Design, 5e60

61Java Programming: From Problem Analysis to Program Design, 5e 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) { //... } Scope Rules (continued)

62Java Programming: From Problem Analysis to Program Design, 5e 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 (continued)

63Java Programming: From Problem Analysis to Program Design, 5e Scope Rules: Demonstrated

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

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

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

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

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

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

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

71Java Programming: From Problem Analysis to Program Design, 5e Programming Example: Data Comparison Input: data from two 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 ( calculateAverage and printResult ) –Parameter passing

72Java Programming: From Problem Analysis to Program Design, 5e Sample Output Course No Group No Course Average CSC ENG HIS MTH PHY Avg for group 1: Avg for group 2: Programming Example: Data Comparison (continued)

73Java Programming: From Problem Analysis to Program Design, 5e Programming Example: Data Comparison (continued)

74Java Programming: From Problem Analysis to Program Design, 5e A program may contain a number of methods. In a complex program, usually, when a method is written, it is tested and debugged alone. You can write a separate program to test the method. The program that tests a method is called a driver program. Before writing the complete program, you could write separate driver programs to make sure that each method is working properly.

75Java Programming: From Problem Analysis to Program Design, 5e Sometimes the results calculated by one method are needed in another method. In that case, the method that depends on another method cannot be tested alone. A method stub is a method that is not fully coded. For a void method, a method stub might consist of only a method header and a set of empty braces, {}. For a value-returning method it might contain only a return statement with a plausible return value.

76Java Programming: From Problem Analysis to Program Design, 5e If the problem is large and complex, it must be broken into subproblems, and if a subproblem is still complex, it must further be divided into subproblems. The subdivision of a problem should continue to the point where the solution is clear and obvious. Once a subproblem is solved, we can continue with the solution of another subproblem and if all the subproblems of a problem are solved, we can continue with the next level. Eventually, the overall solution of the problem must be assembled and tested to ensure that the programming code accomplishes the required task.

77Java Programming: From Problem Analysis to Program Design, 5e A Java program is a collection of classes, and a class is a collection of data members and methods. Each class and each method must work properly. To accomplish this, as explained in the previous section, once a method is written, it can be tested using stubs and drivers. Since a method can be tested in isolation, it is not necessary to code all the methods in order. Once all the methods are written, the overall program must be tested.

78Java Programming: From Problem Analysis to Program Design, 5e The technique to solve a problem by subdividing into smaller problems is known as divide and conquer and top-down design approach. These techniques are suitable and work for many kinds of problems, including most of the problems given in this book and the problems you will encounter as a beginning programmer. To simplify the overall solution of a problem that consists of many subproblems, we write and test the code one piece at a time. Typically, once a subproblem is solved and the code is tested, it is saved as the first version or a version of the program. We continue to add and save the program one piece at a time. Keep in mind that a working program with fewer features is better than a nonworking one with many features.

79Java Programming: From Problem Analysis to Program Design, 5e Chapter Summary Predefined methods User-defined methods –Value-returning methods –Void methods –Formal parameters –Actual parameters Flow of execution

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

81Java Programming: From Problem Analysis to Program Design, 5e Chapter Summary (continued) Debugging: using drivers and stubs Avoiding bugs: one-piece-at-a-time coding