Presentation is loading. Please wait.

Presentation is loading. Please wait.

4 th Week Spring 2011 Methods 1. Outline Introduction Why method ? Static methods vs. non-static methods Example: Math class Declare a method Signature.

Similar presentations


Presentation on theme: "4 th Week Spring 2011 Methods 1. Outline Introduction Why method ? Static methods vs. non-static methods Example: Math class Declare a method Signature."— Presentation transcript:

1 4 th Week Spring 2011 Methods 1

2 Outline Introduction Why method ? Static methods vs. non-static methods Example: Math class Declare a method Signature Method overloading Call/invoke/use a method Calling stack Argument passing Java API Packages 2

3 Introduction Best way to develop and maintain a large program is to construct it from small, simple pieces, i.e., divide and conquer Methods facilitate design, implementation, operation and maintenance of large programs. Dividing a program into meaningful methods makes the program easier to debug and maintain. Normally, methods are called on specific objects static methods can be called without the need for an object of the class to exist 3

4 Program Modules in Java Java programs development involves: Design and implement new methods and classes Statements in method bodies are written only once, are hidden from other methods and can be reused from several locations in a program. Use predefined methods and classes available in the Java Application Programming Interface and other class libraries Java API provides a rich collection of predefined classes Related classes are typically grouped into packages so that they can be imported into programs and reused import java.util.*; Software reusability: use existing methods as building blocks to create new programs 4

5 Method (function) Call A method is invoked by a method call When the called method completes its task, it either returns a result or simply returns control to the caller Flow chart representation Similar to hierarchical form of management A boss (the caller) asks a worker (the called method) to perform a task and report back (return) the results after completing the task The boss method does not know how the worker method performs its designated tasks The worker may also call other worker methods, unbeknown to the boss Hiding of implementation details promotes good software engineering 5

6 static Methods, static Fields and Class Math Sometimes a method performs a task that does not depend on the contents of any object Method applies to the class in which it’s declared Known as a static method or a class method Place the keyword static before the return type in the declaration You can call any static method by specifying its class name, followed by a dot (.) and the method name All Math class methods are static Each is called by preceding the name of the method with the class name Math and the dot (.) separator Method arguments may be constants, variables or expressions 6

7 7

8 8

9 static Methods, static Fields and Class Math Class Math declares commonly used mathematical constants Math.PI (3.141592653589793) : ratio of a circle’s circumference to its diameter Math.E (2.718281828459045) : base value for natural logarithms (calculated with static Math method log) declared in class Math as public, final and static public allows you to use these fields in your own classes final indicates a constant—value cannot change static allows them to be accessed via the class name Math and a dot (.) separator static fields are also known as class variables 9

10 static Methods, static Fields and Class Math Why must main be declared static? When you execute the Java Virtual Machine (JVM) with the java command, the JVM attempts to invoke the main method of the class you specify Declaring main as static allows the JVM to invoke main without creating an object of the class 10

11 Outline Introduction Why method ? Static methods vs. non-static methods Example: Math class Declare a method Signature Method overloading Call/invoke/use a method Calling stack Argument passing Java API Packages 11

12 Example of static method Class MaximumFinder (Fig. 5.3) has two methods—main (lines 8–25) and maximum (lines 28–41) The maximum method determines and returns the largest of three double values Most methods do not get called automatically You must call method maximum explicitly to tell it to perform its task 12

13 13

14 14

15 15

16 Methods declaration public static double maximum(double x, double y, double z) { … } Method header modifiers: public, private, static return type: the data type of the value returned by the method, or void if the method does not return a value. method name: the rules for field names apply to method names as well, but the convention is a little different. parameter list in parenthesis: a comma-delimited list of input parameters, preceded by their data types 16

17 Methods declaration public static double maximum(double x, double y, double z) { double maximumValue=x; if (y > maximumValue) maximumValue = y; if (z > maximumValue) maximumValue = z; return maximumValue; } Method body: enclosed between braces—the method's code, including the declaration of local variables, goes here. 17

18 Methods Signature public static double maximum(double x, double y, double z) { … } Definition: Two of the components of a method declaration comprise the method signature—the method's name and the parameter types. The signature of the method declared above is: maximum(double, double, double) 18

19 Modifiers public static double maximum(double x, double y, double z) { … } public method is “available to the public” Can be called from methods of other classes static method in the same class can call each other directly Any other class that uses a static method must qualify method name with class name, e.g., Math.abs (-20.0); For now, we begin every method declaration with public and static You’ll learn about non-public and non-static methods later. 19

20 Return type and Parameter list Method name follows return type By convention, method names begin with a lowercase first letter and subsequent words in the name begin with a capital letter (e.g., nextInt) Parameter list: Empty parenthesis: the method does not require additional information to perform its task Otherwise, a comma-separated parameter-list: specify one or more parameters represent additional information needed by the method Each parameter must specify a type and an identifier A method’s parameters are considered to be local variables of that method and can be used only in that method’s body 20

21 Calling Methods double result = maximum (number1, number2, number3); A method call supplies arguments for each parameter There must be one argument for each parameter Each argument must be “consistent with” the corresponding parameter’s type Arguments are evaluated to determine their values If an argument is a method call, the method call must be performed to determine its return value A return statement returns a value (or just control) to the point in the program from which the method was called 21

22 Return control to caller After “returning from a method”, control resumes at the next statement in the caller … Ways to return (from method body): When executing return statement: return [expression]; With argument: expression is evaluate and the result is returned to the caller without argument : in the method body is executed. When program flow reaches right brace of the method body. Syntax error: if void function returns a value, or non-void function does not return a value. 22

23 Scope of Declarations Declarations introduce names that can be used to refer to classes, methods, variables and parameters Any block may contain variable declarations Cannot declare a method outside a class declaration, or inside another method declaration Scope of a declaration: the portion of the program that can refer to the declared entity by its name Such an entity is said to be “in scope” for that portion of the program 23

24 Scope Rules Scope of a parameter declaration: the body of the method in which the declaration appears. Scope of a local-variable declaration: from the point at which the declaration appears to the end of that block. Scope of a local-variable declared in initialization section of a for statement’s header: the body of the for statement and the other expressions in the header. A method or field’s scope: the entire body of the class. 24

25 Scope Rules (cont’d) Shadowing: If a local variable or parameter in a method has the same name as a field of the class, the field is “hidden” until the block terminates execution Avoid shadowing by use different names ! Declaring a local variable for multiple times leads to compilation error 25

26 26

27 27

28 28

29 Outline Introduction Why method ? Static methods vs. non-static methods Example: Math class Declare a method Signature Method overloading Call/invoke/use a method Calling stack Argument passing Java API Packages 29

30 Method Overloading Method overloading: one can declare multiple methods of same name in a class, as long as they have different of parameter list Useful for creating several methods that perform similar tasks on different types or different numbers of arguments Compiler distinguishes overloaded methods by signatures A combination of the method’s name and the number, types and order of its parameters Method calls cannot be distinguished by return type Internally, compiler uses longer method names: include original method name, types of each parameter, and exact order of parameters, to determine whether methods in a class are unique 30

31 Method Overloading E.g., Math methods min and max are overloaded with four versions each: One with two double parameters double min (double x, double y) One with two float parameters float min (float x, float y); One with two int parameters One with two long parameters 31

32 32 Literal integer values are treated as type int Literal floating-point values are treated as type double

33 33 By default, floating-point values are displayed with six digits of precision if the precision is not specified in the format specifier.

34 34

35 Outline Introduction Why method ? Static methods vs. non-static methods Example: Math class Declare a method Signature Method overloading Call/invoke/use a method Calling stack Argument passing 35

36 Calling/Invoking Methods Within same class, use a method name by itself e.g., In main() System.out.printf (“Square of interger 7 is %d\n”,square(7)); To call a method on an object, use the object variable, followed by a dot (.) and method name x = input.nextInt (); To call a static method of a class: use class name and a dot (.), followed by method name Math.abs(-12.0) 36

37 Activation Records How does called method know where to return to ? i.e., what’s next statement to execute after method return ? For each method invocation, an activation record (stack frame) is used to keep: return address of the calling method contains the memory for the local variables used in the method When a program calls a method, the activation record (stack frame) is created and pushed onto program-execution stack When method returns to its caller, its activation record is popped off stack and those local variables are no longer known to program If a series of method calls occurs, successive activation records are pushed onto stack in last-in, first-out order 37

38 Stack data structure Analogous to a pile of dishes When a dish is placed on the pile, it’s normally placed at the top (referred to as pushing onto the stack) Similarly, when a dish is removed from the pile, it’s always removed from the top (referred to as popping off the stack) Last-in, first-out (LIFO) data structures—the last item pushed (inserted) on the stack is the first item popped (removed) from the stack 38

39 Argument Promotion and Casting Argument promotion: converting an argument’s value, if possible, to the type that the method expects to receive Promotion rules: specify which conversions are allowed—that is, which conversions can be performed without losing data Apply to expressions containing values of two or more primitive types and to primitive-type values passed as arguments to methods Each value is promoted to the “highest” type in the expression These conversions may lead to compilation errors if Java’s promotion rules are not satisfied Use explicit cast in this case 39

40 40

41 41

42 42 What if we add x = maximumValue here? Does the actual parameter, number 1, corresponding to x, change its value ? Java only support pass-by-value: a copy of the parameter is passed to the method. Method works on the copy of the parameter.

43 Outline Introduction Why method ? Static methods vs. non-static methods Example: Math class Declare a method Signature Method overloading Call/invoke/use a method Calling stack Argument passing Exercise 43

44 Implement binary search as method Implement the binary search as a static method How to pass an array as argument ? public static int BinarySearch (int array[], int x) Recall array is a reference object, you can use array.length to retrieve its length 44

45 Sorting Algorithms 45 Sorting algorithms are one of the most heavily studied topics in Computer Science Sorting is critical to improve searching efficiency There are many well known sorting algorithms in Computer Science, we focus on two: BubbleSort: a very simple but inefficient sorting algorithm MergeSort: a slightly more complex but efficient sorting algorithm

46 BubbleSort Algorithm Overview 46 BubbleSort: repeatedly scan the array, in each iteration “bubbles" the largest element in the unsorted part of the list to the end After 1 iteration, largest element in last position After 2 iterations, largest element in last position and second largest element in second to last position …. requires n-1 iterations at (n-1)-th iteration, only one item left, must already be in proper position (i.e., the smallest must be in the leftmost position)

47 BubbleSort Algorithm 47 Input: n-element array L Bublesort Algorithm 1 Repeat as i varies from n-1 down to 1 2 Repeat as j varies from 0 to i – 1 3 If l j > l j+1 swap l j with l j+1 Outer loop (1-3): i controls which part of the array is scanned for each iteration. (Only unsorted part is checked.) In 1st iteration, check everything, l 0, l 1, … l n-2 In 2nd iteration, check everything except last element, l 0, l 1, …, l n-3 … Inner loop (2-3): bubble up largest element in unsorted part of list to the end

48 BubbleSort Example 48 Use BubbleSort to sort list of number (9 2 8 4 1 3) into increasing order. How many comparisons did you do each iteration? Can you find a pattern?

49 Implement BubbleSort 49 Implement the bubble sort algorithm as a static method Start with document, the method head => the contract Then worry about implementation detail => others do not care them Recall: reference type vs. primitive type variable Reference type: stores address of objects Scanner input; int scores[ ] = new int[20]; Primitive type: stores the value itself int a=10;

50 Recursive algorithms Experiment with Fibonanci function F(n)=F(n-1)+F(n-2) F(1)=0 F(2)=1 Instrument the code so that it displays each invocation of Fib() method Lab3: Implement merge sort, a recursive sorting algorithm. Compare bubble sort with merge sort 50

51 Outline Introduction Why method ? Static methods vs. non-static methods Example: Math class Declare a method Signature Method overloading Call/invoke/use a method Calling stack Argument passing Exercise Random number generator 51

52 Random-Number Generation The element of chance can be introduced in a program via an object of class Random (package java.util) or via the static method random of class Math Objects of class Random can produce random boolean, byte, float, double, int, long and Gaussian values Math method random can produce only double values in the range 0.0 £ x < 1.0, where x is the value returned by method random Random class documentation http://java.sun.com/javase/6/docs/api/java/util/ Random.html http://java.sun.com/javase/6/docs/api/java/util/ Random.html 52

53 Random-Number Generation (cont.) If truly random, then every value in the range should have an equal chance (or probability) of being chosen each time nextInt is called The numbers are actually pseudorandom numbers—a sequence of values produced by a complex mathematical calculation Uses current time of day to seed random-number generator such that each execution of a program yields a different sequence of random values Random’s overloaded method nextInt( ) int nextInt(): generates a random int value in the range – 2,147,483,648 to +2,147,483,647, inclusive int nextInt (int max): returns a value from 0 up to, but not including, the argument’s value 53

54 54

55 55

56 56

57 Generalized Scaling and Shifting of Random Numbers scaling factor—represents the number of unique values that nextInt should produce shift the range of numbers produced by adding a shifting value number = shiftingValue + randomNumbers.nextInt( scalingFactor ); shiftingValue: specifies the first number in the desired range of consecutive integers scalingFactor: specifies how many numbers are in the range 57

58 Generalized Scaling and Shifting of Random Numbers Choose integers at random from sets of values other than ranges of consecutive integers, generalized as number = shiftingValue + differenceBetweenValues * randomNumbers.nextInt( scalingFactor ); where shiftingValue specifies the first number in the desired range of values, differenceBetweenValues represents the constant difference between consecutive numbers in the sequence and scalingFactor specifies how many numbers are in the range 58

59 Random-Number Repeatability for Testing and Debugging The calculation that produces random numbers uses the time of day as a seed value to change the sequence’s starting point Each new Random object seeds itself with a value based on the computer system’s clock at the time the object is created Sometimes useful to repeat the exact same sequence of pseudorandom numbers during each execution Enables you to prove that your application is working for a specific sequence of random numbers before you test the program with different sequences of random numbers When repeatability is important, you can create a Random object with a seed value as an argument to the constructor 59

60 Case Study: A Game of Chance; Introducing Enumerations Rules for the dice game Craps: You roll two dice. Each die has six faces, which contain one, two, three, four, five and six spots, respectively. After the dice have come to rest, the sum of the spots on the two upward faces is calculated. If the sum is 7 or 11 on the first throw, you win. If the sum is 2, 3 or 12 on the first throw (called “craps”), you lose (i.e., the “house” wins). If the sum is 4, 5, 6, 8, 9 or 10 on the first throw, that sum becomes your “point.” To win, you must continue rolling the dice until you “make your point” (i.e., roll that same point value). You lose by rolling a 7 before making your point. Simulates the game of craps, using methods to implement the game’s logic 60

61 61

62 Introducing Enumerations private enum Status {CONTINUE, WON, LOST}; Type Status is a private member of class Craps it will be used only in that class Status is an enumeration, Special kind of class that is introduced by keyword enum and a type name Declares a set of constants represented by identifiers Braces encloses an enum declaration’s body: a comma-separated list of enumeration constants, each representing a unique value The identifiers in an enum must be unique Convention: use only upper case letter Variables of an enum type can be assigned only the constants declared in enumeration Use Status.CONTINUE, … rather than 0, 1,..! 62

63 Case Study: A Game of Chance; Introducing Enumerations (cont.) Why we declare some constants as public final static int rather than as enum constants: Java does not allow an int to be compared to an enumeration constant Unfortunately, Java does not provide an easy way to convert an int value to a particular enum constant 63

64 64

65 65

66 66

67 67

68 Summary 68


Download ppt "4 th Week Spring 2011 Methods 1. Outline Introduction Why method ? Static methods vs. non-static methods Example: Math class Declare a method Signature."

Similar presentations


Ads by Google