610 likes | 624 Views
Midterm Review. 6 th week Spring 2011. Primitive Types vs. Reference Types. Java’s types: primitive types and reference types . Primitive types : boolean, byte, char, short, int, long, float and double. A primitive-type variable can store exactly one value of its declared type at a time.
E N D
Midterm Review 6th week Spring 2011
Primitive Types vs. Reference Types • Java’s types: primitive types and reference types. • Primitive types: boolean, byte, char, short, int, long, float and double. • A primitive-type variable can store exactly one value of its declared type at a time. • Reference type variable (sometimes called reference) stores location of object in memory, i.e., it refer to an object in program. • E.g., Scanner input = new Scanner (System.in); • A reference is required to invoke (i.e., call) method defined for the object • E.g., number1 = input.nextInt();
Primitive Types vs. Reference Types • Primitive types: boolean, byte, char, short, int, long, float, double • A primitive variable => a cup with name, size (type), and content • Name: name of variable • Size is measured in bits • Contentis the value of the variable stored as bits • Reference type (or, nonprimitive types) • Size: all reference variable have same size • Content: bits representing a way to get to (access) a specific object • Default value of null • How JVM does it ? Pointers …
Call methods on the Dog object through remote control (i.e., reference variable): myDog.bark()
Primitive Types vs. Reference Types • Java variables are either primitive type or reference type. • A variable’s declared type indicates whether the variable is of a primitive or a reference type • If a variable’s type is not one of the eight primitive types, then it is a reference type. • E.g., array date type is a reference type • int [] array = new int[20];
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
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
Recursion Problem-Solving Concepts • If method is called with more complex problem, problem divided into two pieces—a piece the method knows how to do and a piece the method does not know how to do (called recursive call or recursion step) • Base case • Recursive method capable of solving only simplest case—the base case • If method is called with base case, method returns result • Recursive call/recursion step • Must resemble original problem but simpler or smaller version • Method calls fresh copy of itself to work on smaller problem • Normally includes return statement
Example Using Recursion: Factorials • Factorial of n, or n! is the product n· (n – 1) · (n – 2) · … · 1 With 1! equal to 1 and 0! Defined to be 1. • Can be solved recursively or iteratively (nonrecursively) • Recursive solution uses following relationship: n! = n · (n – 1)!
Common Programming Error • Either omitting the base case or writing the recursion step incorrectly so that it does not converge on the base case can cause a logic error known as infinite recursion, where recursive calls are continuously made until memory has been exhausted. This error is analogous to the problem of an infinite loop in an iterative (nonrecursive) solution.
Recursion and Method Call Stack • Method call stack used to store method activation records • Last-In-First-Out, or First-In-Last-Out • Upon method call: a new method activation record is created and pushed onto stack, it stores: • Parameters: all parameters are pass-by-value • Return address: where to return afterwards? • Local variables • Upon (recursive) method return, its activation record are popped off the stack • Resume execution based on return address • For recursive call, it’s the previous recursive call
Recursion vs. Iteration • Any problem that can be solved recursively can be solved iteratively • Both iteration and recursion use a control statement • Iteration uses a repetition statement • Recursion uses a selection statement • Iteration and recursion both involve a termination test • Iteration terminates when the loop-continuation condition fails • Recursion terminates when a base case is reached • Recursion can be expensive in terms of processor time and memory space, but usually provides a more intuitive solution
Initial call to recursive method; There are no removed characters yet, so first argument is “” Outline
Merge Sort MergeSort algorithm is one which is defined recursively Suppose we: • divide an unsorted list into two sub-lists, • sort each sub list How quickly can we recombine the two sub-lists into a single sorted list?
Example Consider the two sorted arrays and an empty array Define three indices at the start of each array
Example • We compare 2 and 3: 2 < 3 • Copy 2 down • Increment the corresponding indices
Example • We compare 3 and 7 • Copy 3 down • Increment the corresponding indices
Example • We compare 5 and 7 • Copy 5 down • Increment the appropriate indices
Example • We compare 18 and 7 • Copy 7 down • Increment...
Example • We compare 18 and 12 • Copy 12 down • Increment...
Example • We compare 18 and 16 • Copy 16 down • Increment...
Example • We compare 18 and 33 • Copy 18 down • Increment...
Example • We compare 21 and 33 • Copy 21 down • Increment...
Example • We compare 24 and 33 • Copy 24 down • Increment...
Example We would continue until we have passed beyond the limit of one of the two arrays After this, we simply copy over all remaining entries in the non-empty array
Merging Two Lists Programming a merge is straight-forward: • the sorted arrays, array1 and array2, are of sizen1and n2, respectively, and • we have an empty array, arrayout, of size n1 + n2 Define three variablesint in1 = 0, in2 = 0, out = 0; which index into these three arrays
Merging Two Lists We can then run the following loop: #include <cassert> //... int in1 = 0, in2 = 0, out = 0; while ( in1 < n1 && in2 < n2 ) { if ( array1[in1] < array2[in2] ) { arrayout[out] = array1[in1]; ++in1; } else { assert( array1[in1] >= array2[in2] ); arrayout[out] = array2[in2]; ++in2; } ++out; }
Merging Two Lists We’re not finished yet, we have to empty out the remaining array for ( /* empty */ ; in1 < n1; ++in1, ++out ) { arrayout[out] = array1[in1]; } for ( /* empty */ ; in2 < n2; ++in2, ++out ) { arrayout[out] = array2[in2]; }
MergeSort Algorithm Question: • we split the list into two sub-lists and sorted them • how should we sort those lists? Answer (theoretical): • if the size of these sub-lists is > 1, use merge sort again • if the sub-lists are of length 1, do nothing: a list of length one is sorted
The Algorithm However, just because an algorithm has excellent asymptotic properties, this does not mean that it is practical at all levels Answer (practical): • If the sub-lists are less than some threshold length, use an algorithm like insertion sort to sort the lists • Otherwise, use merge sort, again
The Algorithm Thus, a graphical interpretation of merge sort would be
The Algorithm Some details: • if the list size is odd, just split the array into two almost equally sized list – one even, one odd • each merging requires an additional array • we can minimize the amount of memory required by using two arrays, splitting and sorting in one, then merging the results between the two arrays
The Algorithm Merge sort using two arrays
Example Applying the merge sort algorithm:
Run-time Analysis of Merge Sort Thus, the time required to sort an array of size n > 1 is: • the time required to sort the first half, • the time required to sort the second half, and • the time required to merge the two lists That is: Closed-form solution:
Merge Sort • The (likely) first implementation of merge sort was on the ENIAC in 1945 by John von Neumann • The creator of the von Neumannarchitecture used by all moderncomputers: http://en.wikipedia.org/wiki/Von_Neumann
Class declaration • We have designed several classes for our CashierRegister project • For each class, we defined data and method members • Syntax of class declaration • Use access modifier to control access to members • Static vs non-static fields • Static vs non-static methods
Software engineering observations • A class is a user defined type • A class’s public interface • public methods: a view of the services the class provides to the class’s clients • A class’s implementation details • private variables and private methods are not accessible to the class’s clients
non-static method & this Reference • Any non-static method must be called upon with an object Time1.toString(); ## leads to compilation error ! Time1 t = new Time1; ## create Time1 object and use t to reference it t.toString(); ## call toString() method upon a Time1 object referenced by t • Non-static method can access this reference, a reference to the object on which it is called upon • implicitly use this when referring to the object’s instance variables and other methods • can be explicitly used to access instance variables when they are shadowed by local variables or method parameters
Constructors • Constructors: special method to initialize an object of a class • Called when an object is the class is created new Dog ( ); new Scanner (System.in); • Java requires a constructor for every class • Java will provide a default no-argument constructor if none is provided • The default constructor initialize instance variables with default value • Default values are zero for primitive numeric types, false for boolean values and null for references • Unless default value for instance variables is acceptable, provide a constructor
Overloaded Constructors • Overloaded constructors • Provide multiple constructor definitions with different signatures • No-argument constructor: the constructor invoked without arguments • this reference can be used to invoke another constructor • Allowed only as the first statement in a constructor’s body • A constructor can call methods of the class. • However: instance variables might not yet be in a consistent state, because constructor is in process of initializing object. • Using instance variables before they have been initialized properly is a logic error.