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

Slides:



Advertisements
Similar presentations
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Advertisements

Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Dale Roberts Object Oriented Programming using Java - Class Constructors Dale Roberts, Lecturer Computer Science, IUPUI Department.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Recursion Review.
Programming in C++ Language ( ) Lecture 6: Functions-Part2 Dr. Lubna Badri.
Dale Roberts Procedural Programming using Java Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
 2008 Pearson Education, Inc. All rights reserved Function Call Stack and Activation Records Data structure: collection of related data items.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Functions and an Introduction to Recursion.  Recursive function ◦ A function that calls itself, either directly, or indirectly (through another function)
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
1 Introduction Modules  Most computer programs solve much larger problem than the examples in last sessions.  The problem is more manageable and easy.
 2005 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
 2007 Pearson Education, Inc. All rights reserved C Functions -Continue…-
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
CISC6795 Spring 11 Fordham Univ. Introduction to Classes and Objects 1.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo CET 3640 © Copyright by Pearson Education, Inc. All Rights Reserved.
Methods: A Deeper Look. Template for Class Definition public class { } A.Import Statement B.Class Comments C.Class Name D.Data members E.Methods (inc.
Object Oriented Programming with Java 03 - Introduction to Classes and Objects.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
ECE 250 Algorithms and Data Structures Douglas Wilhelm Harder, M.Math. LEL Department of Electrical and Computer Engineering University of Waterloo Waterloo,
Chapter 111 Recursion Chapter Objectives become familiar with the idea of recursion learn to use recursion as a programming tool become familiar.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
C++ Programming Lecture 12 Functions – Part IV
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
A First Book of ANSI C Fourth Edition
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
 2006 Pearson Education, Inc. All rights reserved Functions and an Introduction to Recursion.
Methods, classes, and Objects Dr. Jim Burns. Question  Which of the following access modifiers is the default modifier?  public  private  protected.
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Recursion Powerful Tool
Outline This topic covers merge sort
Introduction to Classes and Objects
RECURSION.
Java Primer 1: Types, Classes and Operators
Methods Chapter 6.
Chapter 3: Using Methods, Classes, and Objects
Programmazione I a.a. 2017/2018.
6.11 Function Call Stack and Activation Records
Chapter 5 - Functions Outline 5.1 Introduction
MSIS 655 Advanced Business Applications Programming
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Methods.
Object Oriented Programming in java
Classes, Objects and Methods
Review for Midterm 3.
Corresponds with Chapter 5
Presentation transcript:

6 th week Spring 2011 Midterm Review 1

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(); 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 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. 7

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 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 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

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, it’s 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 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]; } 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 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 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 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 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 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.

48

49

50

51

Outline 52 Call overloaded constructors

Outline 53

Outline 54

Something new … 55

Using Command-Line Arguments It’s 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 application’s 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