4 th week spring 2011 methods 1. outline introduction why method ? static methods vs. non-static...
TRANSCRIPT
4th WeekSpring 2011
Methods
1
OutlineIntroduction
Why method ? Static methods vs. non-static methods
Example: Math classDeclare a method
Signature Method overloading
Call/invoke/use a methodCalling stackArgument passing
Java API Packages
2
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
Program Modules in Java Java programs development involves:
Design and implement new methods and classesStatements 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
Method (function) CallA method is invoked by a method callWhen 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 managementA 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
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 staticEach 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
8
static Methods, static Fields and Class Math
Class Math declares commonly used mathematical constantsMath.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 changestatic allows them to be accessed via the class
name Math and a dot (.) separatorstatic fields are also known as class variables
9
static Methods, static Fields and Class MathWhy 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
OutlineIntroduction
Why method ? Static methods vs. non-static methods
Example: Math classDeclare a method
Signature Method overloading
Call/invoke/use a methodCalling stackArgument passing
Java API Packages
11
Example of static methodClass 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 automaticallyYou must call method maximum explicitly to
tell it to perform its task
12
13
14
15
Methods declarationpublic static double maximum(double x, double y, double z)
{
…
}Method header
modifiers: public, private, staticreturn 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
Methods declarationpublic 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
Methods Signaturepublic 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
Modifierspublic 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
Return type and Parameter listMethod 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 methodEach 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
Calling Methodsdouble result = maximum (number1, number2, number3);A method call supplies arguments for each
parameterThere must be one argument for each parameterEach 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
Return control to callerAfter “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 callerwithout 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
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
Scope RulesScope 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
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 executionAvoid shadowing by use different names !
Declaring a local variable for multiple times leads to compilation error
25
26
27
28
OutlineIntroduction
Why method ? Static methods vs. non-static methods
Example: Math classDeclare a method
Signature Method overloading
Call/invoke/use a methodCalling stackArgument passing
Java API Packages
29
Method OverloadingMethod overloading: one can declare multiple
methods of same name in a class, as long as they have different of parameter listUseful for creating several methods that perform
similar tasks on different types or different numbers of arguments
Compiler distinguishes overloaded methods by signaturesA 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
Method OverloadingE.g., Math methods min and max are
overloaded with four versions each:One with two double parametersdouble min (double x, double y)One with two float parametersfloat min (float x, float y); One with two int parametersOne with two long parameters
31
32
Literal integer values are treated as type int
Literal floating-point values are treated as type double
33
By default, floating-point values are displayed with six digits of precision if the precision is not specified in the format specifier.
34
OutlineIntroduction
Why method ? Static methods vs. non-static methods
Example: Math classDeclare a method
Signature Method overloading
Call/invoke/use a methodCalling stackArgument passing
35
Calling/Invoking MethodsWithin same class, use a method name by
itselfe.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 namex = input.nextInt ();
To call a static method of a class: use class name and a dot (.), followed by method nameMath.abs(-12.0)
36
Activation RecordsHow 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 methodcontains the memory for the local variables used
in the methodWhen 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
Stack data structureStack 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
Argument Promotion and CastingArgument 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
41
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.
OutlineIntroduction
Why method ? Static methods vs. non-static methods
Example: Math classDeclare a method
Signature Method overloading
Call/invoke/use a methodCalling stackArgument passing
Exercise
43
Implement binary search as methodImplement the binary search as a static
methodHow 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
Sorting Algorithms
45
Sorting algorithms are one of the most heavily studied topics in Computer ScienceSorting 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 algorithmMergeSort: a slightly more complex but
efficient sorting algorithm
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 positionAfter 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)
BubbleSort Algorithm
47
Input: n-element array L Bublesort Algorithm
1 Repeat as i varies from n-1 down to 12 Repeat as j varies from 0 to i – 13 If lj > lj+1 swap lj with lj+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, l0, l1, … ln-2 In 2nd iteration, check everything except last
element, l0, l1, …, ln-3 …
Inner loop (2-3): bubble up largest element in unsorted part of list to the end
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?
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
variableReference type: stores address of objects
Scanner input;int scores[ ] = new int[20];
Primitive type: stores the value itselfint a=10;
Recursive algorithmsExperiment with Fibonanci function
F(n)=F(n-1)+F(n-2)F(1)=0F(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
OutlineIntroduction
Why method ? Static methods vs. non-static methods
Example: Math classDeclare a method
Signature Method overloading
Call/invoke/use a methodCalling stackArgument passing
ExerciseRandom number generator
51
Random-Number GenerationThe 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 documentationhttp://java.sun.com/javase/6/docs/api/java/util/Random.
html
52
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
55
56
Generalized Scaling and Shifting of Random Numbersscaling factor—represents the number of
unique values that nextInt should produce shift the range of numbers produced by adding
a shifting valuenumber = 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
Generalized Scaling and Shifting of Random NumbersChoose 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
Random-Number Repeatability for Testing and DebuggingThe 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 executionEnables 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
Case Study: A Game of Chance; Introducing EnumerationsRules 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
Introducing Enumerationsprivate 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
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
65
66
67
Summary
68