1 / 40

CHAPTER 6 GENERAL-PURPOSE METHODS

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.

Download Presentation

CHAPTER 6 GENERAL-PURPOSE METHODS

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

  2. 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 Method and Parameter Declarations

  3. 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. Java Methods

  4. 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 General Purpose Methods

  5. Figure 6.1: Calling and Passing Data to a Method

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

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

  8. Figure 6.3: findMaximum() Receives Actual Values

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

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

  11. Figure 6.6: The Structure of a Method Body

  12. // 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 Structure of Method Body for findMaximum

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

  14. Figure 6.7: A Sample Display Produced by Program 6.2

  15. Point of Information: Isolation Testing

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

  17. 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 Method Stubs and Testing

  18. 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. Empty Parameter Lists and Overloading

  19. Figure 6.8: A Method Directly Returnsat Most One Value

  20. 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. Returning a Single Value

  21. 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) Void and Value Returning Methods

  22. // 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 } Another Maximum method

  23. 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 “); Calling a Value Returning Method

  24. 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 Passing a Reference Variable

  25. Figure 6.9: Passing a Reference Value

  26. 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. Passing a Reference Variable

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

  28. Exercises 6.2: Item 11

  29. Figure 6.10: A Method Can Be Considereda Closed Box

  30. 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 itsscope–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 Scope

  31. 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. Variable “Lifetime” and Duration

  32. Figure 6.11:The Three Storage Areas Created by Program 6.6

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

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

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

  36. 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. Inner and Outer Blocks

  37. 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. Common Programming Errors

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

  39. 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 More Random Numbers

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

More Related