CHAPTER 6 GENERAL-PURPOSE METHODS

Slides:



Advertisements
Similar presentations
Chapter 7: User-Defined Functions II
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
©2004 Brooks/Cole Chapter 6 Methods. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Using Methods We've already seen examples of using methods.
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
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.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Chapter 6: Functions.
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.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
C++ for Engineers and Scientists Third Edition
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
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.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
Chapter 10 Introduction to Classes
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
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.
Chapter 6: Repetition Continued. 2 Validity Checks What’s weak about the following code ? do { s1 = JOptionPane.showInputDialog (“Enter a number: ”);
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
A First Book of ANSI C Fourth Edition
CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Chapter 6 Modularity Using Functions
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Functions + Overloading + Scope
Chapter 9: Value-Returning Functions
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Chapter 6: User-Defined Functions I
Chapter 7: User-Defined Functions II
Java Programming: Guided Learning with Early Objects
Methods Chapter 6.
JavaScript: Functions
CSC113: Computer Programming (Theory = 03, Lab = 01)
JavaScript: Functions.
Methods.
User-Defined Functions
C++ for Engineers and Scientists Second Edition
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 6 Methods: A Deeper Look
Group Status Project Status.
A First Book of ANSI C Fourth Edition
Chapter 6 Methods.
Tonga Institute of Higher Education
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Chapter 6: User-Defined Functions I
Method of Classes Chapter 7, page 155 Lecture /4/6.
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Presentation transcript:

CHAPTER 6 GENERAL-PURPOSE METHODS This chapter in the book includes: 6.1 Method and Parameter Declarations 6.2 Returning a Single Value 6.3 Variable Scope 6.4 Common Programming Errors 6.5 Chapter Summary 6.6 Chapter Supplement: Generating Random Numbers Click the mouse to move to the next page. Use the ESC key to exit this chapter.

Method and Parameter Declarations Every Java method must be contained within a class just as the main( ) method is. There are different types of methods Static – which receives its data as arguments and manipulates a shared variable – it belongs to the class rather than to objects of the class – it is a class method Non-static – has access to both instance (without static) and static fields – most methods are non-static or instance methods The key word public mean that the method can be used outside its own class; private indicates that the method is used only within the class

Instance methods- are associated with individual objects Java Methods Instance methods- are associated with individual objects Class methods- ( static) methods are associated with a class (like main) Helper methods- are subprograms within a class that help other methods in the class; they are declared privately within a class Constructor methods- are used with the new operator to prepare an object for use.

General Purpose Methods We will be concerned with the method itself and how it interacts with other methods, such as main( ) Passing data to a general purpose method Having the method correctly receive, store and process the data A method is called by using its name and passing data (or arguments) in parenthesis

Figure 6.1: Calling and Passing Data to a Method

Figure 6.2: Calling and Passing Two Values to findMaximum()

import javax.swing.*; public class ShowTheCall { public static void main(String[] args) { String s1; double firstnum, secnum; s1 = JOptionPane.showInputDialog("Enter number:"); firstnum = Double.parseDouble(s1); s1 = JOptionPane.showInputDialog("Great! Please enter a second number: "); secnum = Double.parseDouble(s1); findMaximum(firstnum, secnum); // the method is called here System.exit(0); } // end of method } // end of class

Figure 6.3: findMaximum() Receives Actual Values

Figure 6.4: General Format of a Method Method signature Header – specifies access privileges (where method can be called), data type of returned value, gives method a name and specifies number, order and type of its arguments

Figure 6.5: The Structure of a General Purpose Method’s Header For example: public static void main (String [] args)

Figure 6.6: The Structure of a Method Body

Structure of Method Body for findMaximum // following is the findMaximum() method public static void findMaximum(double x, double y) // no semicolon here! { // start of method body double maxnum; // variable declaration if (x >= y) // find the maximum number maxnum = x; else maxnum = y; JOptionPane.showMessageDialog(null, "The maximum of " + x + " and " + y + " is " + maxnum, "Maximum Value", JOptionPane.INFORMATION_MESSAGE); } // end of method body and end of method

secnum = Double.parseDouble(s1); import javax.swing.*; public class CompleteTheCall { public static void main(String[] args) String s1; double firstnum, secnum; s1 = JOptionPane.showInputDialog("Enter a number:"); firstnum = Double.parseDouble(s1); s1 = JOptionPane.showInputDialog("Great! Please enter a second number:"); secnum = Double.parseDouble(s1); findMaximum(firstnum, secnum); // the method is called here System.exit(0); } // end of main() method // following is the findMaximum() method public static void findMaximum(double x, double y) { // start of method body double maxnum; // variable declaration if (x >= y) // find the maximum number maxnum = x; else maxnum = y; JOptionPane.showMessageDialog(null, "The maximum of " + x + " and " + y + " is " + maxnum, "Maximum Value", JOptionPane.INFORMATION_MESSAGE); } // end of method body and end of method } // end of class

Figure 6.7: A Sample Display Produced by Program 6.2

Point of Information: Isolation Testing

Calling a Method The findMaximum( ) method is the called method, because it is called by its reference in main( ) The method that does the calling (in this case main( ) ) is the calling method The items within parenthesis are the arguments or parameters: Formal-the list of values and their data types(or form), that the method expects to receive ( in parenthesis in the method header) Actual - the actual data values supplied when the call is made ( in the calling method)

Method Stubs and Testing Usually write the main method and add other methods as they are developed Problem – can’t be run without the methods Solution – design “empty methods” or stubs, which just contain the header ( and perhaps some comment or print statement to aid in debugging) Stub is used as a placeholder until the method is written Calling program is called a “driver” and is used to test each method

Empty Parameter Lists and Overloading Rarely, but sometimes, no parameters are needed – just include empty parenthesis public static int display ( ) //returns an integer To call this method use x = display( ); Using the same method name for more than one method is called overlaoding. The compiler must be able to determine which method to use based on the data types of the parameters. ( eg. square(5); for ints and square (2.5); for doubles) Method signatures must be unique.

Figure 6.8: A Method Directly Returns at Most One Value

Returning a Single Value Pass by value or call by value – copies of the data values contained in the arguments when the method is called are passed to the method. Method may change the values in its copy as well as any local variables declared in the method A method returns at most one single value.

Void and Value Returning Methods Void methods are those which manipulate the data within the method. They often contain input or output statements. ( Name with an action word like displayMenu). Value returning methods ( like mathematical functions) – just compute and return a single value. They DO NOT include input or output statements. They must be part of an expression or assigned to a variable in the calling program. (Usually name with a noun such as square or cube)

Another Maximum method // this one returns the maximum value public double Maximum(double x, double y) { // start of method body double maxnum; // variable declaration if (x >= y) // find the maximum number maxnum = x; else maxnum = y; return maxnum; // return statement }

Calling a Value Returning Method Void methods can stand alone- so they are called just by using the method name: findMaximum( 5, 8); Value returning methods must return their value to a variable or be used within an expression (anywhere that data type can be used) larger = Maximum(5,8); or if (Maximum(5,8) <10) … or ….2* Maximum(5,8)… or System.out.println( Maximum(5,8) + “ is the larger number “);

Passing a Reference Variable Java passes both primitive and reference variables in the same way: ( by value) a copy is passed to the method and stored in one of the formal parameters. Advantages: Methods can use any variable name without interfering with other methods that might use the same name Changing the value in the method will not affect the value of that variable in other methods (called a side effect) Passing a reference variable does have some other implications that passing a primitive does not

Figure 6.9: Passing a Reference Value

Passing a Reference Variable Since a reference value gives direct access to the object, any change made within the method is made to the original object’s value. The ability to alter a referenced object within a method is useful where a method must return more than one value. Primitive types must first be converted to wrapper types( see p.105-106). Then the reference to this object is passed to the called method. This will not work with String objects, because they are immutable.

Exercises 6.2: Item 9.a. For Practice: Write a method named distance that accepts the coordinates of two points (x1,y1) and (x2, y2) and calculates and returns the distance between them according to this formula:

Exercises 6.2: Item 11

Figure 6.10: A Method Can Be Considered a Closed Box

What goes on inside the method are “hidden” from other methods. Variable Scope What goes on inside the method are “hidden” from other methods. Variables declared inside a method are available only to that method and are called local variables. The section of the program where an identifier is “known” or is visible is its scope – usually the block in which it is declared ( block scope). A Class variable is any variable declared within a class, but outside a method.

Variable “Lifetime” and Duration Identifiers within the class scope come into being when the class is loaded into memory and remain until the program finishes executing. Static variables have the same duration as their defining class. Variables with block scope exist only which the block in which they are defined is in scope, then they are released. If the block comes back into scope later, new storage areas are reserved.

Figure 6.11: The Three Storage Areas Created by Program 6.6

The local variable takes precedence. Scope Resolution Whe a local ( block) variable has the same name as a variable with class scope, all references within the scope of the local variable refer to that local variable. The local variable takes precedence. The class variable can be accessed by prefacing it with its class name as shown in the next example.

The value of number is 26.4 public class ScopeCover { private static double number = 42.8; // this variable has class scope public static void main(String[] args) double number = 26.4; // this variable has local scope System.out.println("The value of number is " + number); } } // end of class What is the output of this code? The value of number is 26.4

The value of number is 42.5 public class ScopeResolution { private static double number = 42.8; // this is a static (class scope) variable public static void main(String[] args) double number = 26.4; // this is a local variable System.out.println("The value of number is " + ScopeResolution.number); } } // end of class What is the output of this code? The value of number is 42.5

Inner and Outer Blocks Variables declared in an inner block cannot be acced in any enclosing outside block. This includes variables declared within the parenthesis of a for statement ( the value of i cannot be accessed once the loop terminates). The same variable name can be declared and used again after the inner block is out of scope.

Common Programming Errors Attempting to pass incorrect data types Declaring the same variable locally within both the calling and called methods and assuming that changing one value affects the other. Ending a method header with a semicolon Forgetting to include the data type of the method’s parameters within the header.

Pseudorandom numbers – sufficiently random. Random numbers – a series of numbers whose order cannot be predicted, where each has the same likelyhood of occurring. Pseudorandom numbers – sufficiently random. General purpos method in the Math class random( ) – produces double precision numbers from 0.0 up to, but not including 1.0

To produce integers use scaling: More Random Numbers To produce integers use scaling: (int)(Math.random( ) * n) // for 0 to n-1 To produce a random integer between 1 and n use 1+ (int)(Math.random( ) * n) // for 1 to n Example: 1+ (int)(Math.random( ) * 6) // for 1 to 6 (dice game) or in general use a+ (int)(Math.random( ) * b+1-a) // for a to b

public class RandomNumbers { // prints 10 random numbers public static void main(String[] args) { final int NUMBERS = 10; double randValue; int I, randInt; for (i = 1; i <= 10; i++) randValue = Math.random( ); randInt = (int)( Math.random( ) * 100) //integers between 0 and 99 System.out.println(randValue, randInt); } // end for loop } // end main } // end of class