680 likes | 696 Views
Learn about methods in Java programming, including the benefits of dividing programs into smaller methods, using static methods, and utilizing the Java API packages. Includes an example of a static method and its declaration.
E N D
Methods 4th Week Spring 2011
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
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
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
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
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
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 • finalindicates 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
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
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
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
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
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.
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)
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.
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
CallingMethods 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
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.
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
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.
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
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
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
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
Literal integer values are treated as type int • Literal floating-point values are treated as type double
By default, floating-point values are displayed with six digits of precision if the precision is not specified in the format specifier.
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
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)
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
Stack data structure • 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
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
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.
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
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
Sorting Algorithms • 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
BubbleSort Algorithm Overview • 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)
BubbleSort Algorithm • Input: n-element array L • Bublesort Algorithm 1 Repeat as i varies from n-1 down to 1 • Repeat as j varies from 0 to i – 1 • 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 • 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 • 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;
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