6 th week spring 2011 midterm review 1. primitive types vs. reference types javas types: primitive...

Download 6 th week Spring 2011 Midterm Review 1. Primitive Types vs. Reference Types Javas types: primitive types and reference types. Primitive types: boolean,

If you can't read please download the document

Upload: rosemary-cook

Post on 18-Jan-2018

234 views

Category:

Documents


0 download

DESCRIPTION

Primitive Types vs. Reference Types 3 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 Content is 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 …

TRANSCRIPT

6 th week Spring 2011 Midterm Review 1 Primitive Types vs. Reference Types Javas 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(); 2 Primitive Types vs. Reference Types 3 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 Content is 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 Primitive Types vs. Reference Types 4 5 Call methods on the Dog object through remote control (i.e., reference variable): myDog.bark() Primitive Types vs. Reference Types 6 Java variables are either primitive type or reference type. A variables declared type indicates whether the variable is of a primitive or a reference type If a variables 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 statements header: the body of the for statement and the other expressions in the header. A method or fields scope: the entire body of the class. 7 Scope Rules (contd) 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 8 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 9 10 Recursion Problem-Solving Concepts If method is called with more complex problem, problem divided into two piecesa 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 casethe 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 11 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)! 12 13 14 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. 15 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, its the previous recursive call 16 Method call stacks during factorial (3) 17 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 Outline 18 Initial call to recursive method; There are no removed characters yet, so first argument is 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? 19 Example Consider the two sorted arrays and an empty array Define three indices at the start of each array 20 Example We compare 2 and 3: 2 < 3 Copy 2 down Increment the corresponding indices 21 Example We compare 3 and 7 Copy 3 down Increment the corresponding indices 22 Example We compare 5 and 7 Copy 5 down Increment the appropriate indices 23 Example We compare 18 and 7 Copy 7 down Increment... 24 Example We compare 18 and 12 Copy 12 down Increment... 25 Example We compare 18 and 16 Copy 16 down Increment... 26 Example We compare 18 and 33 Copy 18 down Increment... 27 Example We compare 21 and 33 Copy 21 down Increment... 28 Example We compare 24 and 33 Copy 24 down Increment... 29 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 30 Merging Two Lists Programming a merge is straight-forward: the sorted arrays, array1 and array2, are of size n1 and n2, respectively, and we have an empty array, arrayout, of size n1 + n2 Define three variables int in1 = 0, in2 = 0, out = 0; which index into these three arrays 31 Merging Two Lists We can then run the following loop: #include //... 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; } 32 Merging Two Lists Were 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]; } 33 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 34 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 35 The Algorithm Thus, a graphical interpretation of merge sort would be 36 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 37 The Algorithm Merge sort using two arrays 38 Example Applying the merge sort algorithm: 39 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: 40 Merge Sort The (likely) first implementation of merge sort was on the ENIAC in 1945 by John von Neumann The creator of the von Neumann architecture used by all modern computers:41 Object-Oriented Programming 42 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 43 Software engineering observations 44 A class is a user defined type A classs public interface public methods: a view of the services the class provides to the classs clients A classs implementation details private variables and private methods are not accessible to the classs clients non-static method & this Reference 45 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 objects instance variables and other methods can be explicitly used to access instance variables when they are shadowed by local variables or method parameters Constructors 46 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 47 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 constructors 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. 48 49 50 51 Outline 52 Call overloaded constructors Outline 53 Outline 54 Something new 55 Using Command-Line Arguments Its possible to pass arguments from the command line (these are known as command-line arguments) to an application by including a parameter of type String[] in the parameter list of main. By convention, this parameter is named args. When an application is executed using java command, i.e., java Cashier weekend Java passes command-line arguments that appear after class name (i.e., weekend) to the applications main method as Strings in the array args. 56 57 58 59 Enhanced for Statement Iterates through elements of an array without using a counter Avoiding possibility of stepping outside the array. Syntax: for ( parameter : arrayName ) statement where parameter has a type and an identifier, and arrayName is the array through which to iterate. Parameter type must be consistent with the type of the elements in the array. Can be used only to obtain array elements it cannot be used to modify elements. Can be used in place of the counter-controlled for statement whenever code looping through an array 60 Acknowledgement Slides on Merge Sort is adapted from slides by Douglas Wilhelm Harder, Mmath This presentation uses materials from Head First Java Java How to Program, slides set 61