CS S-24 Final Review I 1

Similar documents
Intro to Computer Science II

Intro to Computer Science II

CS S-08 Arrays and Midterm Review 1

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

Lecture 2, September 4

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Chapter 1: Introduction to Computers, Programs, and Java

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

CS 231 Data Structures and Algorithms, Fall 2016

Compilers CS S-10 Object Oriented Extensions

Pace University. Fundamental Concepts of CS121 1

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

COE318 Lecture Notes Week 4 (Sept 26, 2011)

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Programming Languages and Techniques (CIS120)

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

Chapter 1 Getting Started

Compilers CS S-05 Semantic Analysis

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

CIS 120 Midterm II November 8, 2013 SOLUTIONS

Programming Language Concepts Scoping. Janyl Jumadinova January 31, 2017

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Computer Science II Data Structures

CS121/IS223. Object Reference Variables. Dr Olly Gotel

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

Introduction to Computer Science II CS S-16 Recursion III

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

CS 251 Intermediate Programming Java Basics

Fall 2017 CISC124 9/16/2017

COE318 Lecture Notes Week 6 (Oct 10, 2011)

Introduction to Programming Using Java (98-388)

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

CMSC330. Objects, Functional Programming, and lambda calculus

Introduction to Java

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

CS 61C: Great Ideas in Computer Architecture Introduction to C

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Lecture Set 4: More About Methods and More About Operators

Object Oriented Programming Exception Handling

4. Java language basics: Function. Minhaeng Lee

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion.

University of Palestine. Mid Exam Total Grade: 100

Chapter 5 Names, Bindings, Type Checking, and Scopes

OCaml Language Choices CMSC 330: Organization of Programming Languages

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2

Midterm Exam CS 251, Intermediate Programming March 12, 2014

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

CIS 120 Midterm II November 8, Name (printed): Pennkey (login id):

Selected Questions from by Nageshwara Rao

CS 61B Discussion 5: Inheritance II Fall 2014

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Getting started with Java

CS Programming I: Arrays

Short Notes of CS201

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

CS 211: Methods, Memory, Equality

Programming refresher and intro to C programming

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Summer Final Exam Review Session August 5, 2009

CS201 - Introduction to Programming Glossary By

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II

CS S-10 Object Oriented Extensions 1. What do we need to add to simplejava classes to make them true objects?

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Lecture 3. Lecture

The return Statement

Object-Oriented Programming

Variables and Java vs C++

Java Bytecode (binary file)

Final Exam CS 251, Intermediate Programming December 10, 2014

Controls Structure for Repetition

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException

Building Java Programs

Principles of Object Oriented Programming. Lecture 4

CSE 307: Principles of Programming Languages

Java Fundamentals (II)

Computer Science II (20082) Week 1: Review and Inheritance

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

array Indexed same type

CHAPTER 7 OBJECTS AND CLASSES

CA31-1K DIS. Pointers. TA: You Lu

CSE 431S Type Checking. Washington University Spring 2013

COM S 213 PRELIM EXAMINATION #2 April 26, 2001

CSCI 355 LAB #2 Spring 2004

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011

CSCI 355 Lab #2 Spring 2007

Transcription:

CS112-2012S-24 Final Review I 1 24-0: Review Memory Basics (stack vs. heap) Creating Objects Control Structures (if, while, etc) Mutable and Immutable objects (Strings!) Methods (including recursion) Arrays Static fun For Wednesday: Linked Lists Inheritance (including polymorphism) Potpourri (Exceptions, etc) 24-1: Memory Basics Parameters and local variables are all stored on the stack Instance variables in classes are stored on the heap Pointers to classes can be stored on the stack Primative types (int/boolean/double/etc non-classes) are stored on the stack unless they are instance variables within a class Heap memory is only created if you call new 24-2: Memory Basics public class Foo int x; int y; public static void main(string args[]) int x; int y; Foo f1, f2; // What does the stack / heap look like? f1 = new Foo(); f2 = new Foo(); // What about now? 24-3: Memory Basics public class Foo public class Bar int x; Foo f1; int y; Foo f2; public static void main(string args[]) int x; int y; Bar b; // What does the stack / heap look like? b = new Bar(); // Now What does the stack / heap look like? b.f1 = new Foo(); // What about now? b.f2 = new Foo(); // What about now?

CS112-2012S-24 Final Review I 2 24-4: Memory Basics public class Bar public class Foo public Foo f1; int x; public Foo f2; int y; public Bar() f1 = new Foo(); f2 = new Foo(); public static void main(string args[]) int x,y; Foo f; bar b; // What does the stack / heap look like? b = new Bar(); // Now What does the stack / heap look like? f = new Foo(); 24-5: Memory Basics Classes are Templates Need to call new to create instance of classes Can only get memory on heap by calling new 24-6: Java Control Structures If: if (<test>) <statement> or if (<test>) <statement1> else <statement2> A statement is either a single statment (terminated with ;), or a block of statements inside 24-7: If test What can we have as the test of an if statement? 24-8: If test Boolean valued expression What can we have as the test of an if statement? boolean variable function that returns a boolean value comparison x < y or x!= 0 Combination of boolean expressions, using not (!), and (&&), or ( ) 24-9: Boolean Variables

CS112-2012S-24 Final Review I 3 Hold the value true or false Can be used in test (if, while, etc) boolean b; boolean c; b = true; c = b false; b = (3 < 10) && (5 > 11); c =!b && c; 24-10: if Gotchas What is (likely) wrong with the following code? if (x!= 0) z = a / x; y = b / x; 24-11: if Gotchas What is (likely) wrong with the following code? if (x!= 0) z = a / x; y = b / x; Moral: Always use in if statements, even if they are not necessary 24-12: while loops while(test) <loop body> Evaluate the test If the test is true, execute the body of the loop Repeat Loop body may be executed 0 times 24-13: do-while loops do <loop body> while (<test>); Execute the body of the loop If the test is true, repeat

CS112-2012S-24 Final Review I 4 Loop body is always executed at least once 24-14: while vs. do-while What would happen if: Found a while loop in a piece of code Changed to to a do-while (leaving body of loop and test the same) How would the execution be different? 24-15: while vs. do-while What would happen if: Found a while loop in a piece of code Changed to to a do-while (leaving body of loop and test the same) How would the execution be different? If the while loop were to execute 0 times, do-while will execute (at least!) one time If the while loop were to execute 1 or more times, should to the same thing...... except if the test had side effects 24-16: Side Effects class BoolFun private int size; boolean calledtoomuch() return (++size > 4) // in main: BoolFun bf = new BoolFun(); while (!bf.calledtoomuch()) System.out.print("x"); 24-17: Side Effects class BoolFun private int size; boolean calledtoomuch() return (++size > 4) // in main: BoolFun bf = new BoolFun(); do System.out.print("x"); while (!bf.calledtoomuch()); 24-18: for loops for (<init>; <test>; <inc>) <body> Equivalent to:

CS112-2012S-24 Final Review I 5 <init> while(<test>) <body> <inc> 24-19: for loops for (number = 1; number < 10; number++) System.out.print("Number is " + number); Equivalent to: number = 1; while(number < 10) System.out.print("Number is " + number); number++; 24-20: Strings Strings in Java are objects Contain both methods and data 24-21: Strings Data is the sequence of characters (type char) that make up the string Strings have a whole bunch of methods for string processing Strings in Java are objects Strings are stored on the heap, like all other objects Data is stored as an array of characters Strings are immutable (once created, can t be changed) 24-22: String Literals String s; s = "Dog"; Dog is called a String Literal Anything in quotation marks is a string literal System.out.println("Hello There") 24-23: String Literals Any time there is a string literal in your code, there is an implicit call to new

CS112-2012S-24 Final Review I 6 A new string object is created on the heap Data is filled in to match the characters in the string literal Pointer to that object is returned String s; s = "MyString"; // Implicit call to new here! 24-24: Stack vs. Heap I public void foo() int x = 99; char y = c ; String z = "c"; String r = "cat"; float w = 3.14; 24-25: Immutable Strings Strings are immutable Once you create a string, you can t change it. String s = "Car"; unknown.foo(s); // Create a block of memory containing car // Return a pointer to this block of memory // This function can t mess with contents of s System.out.println(S); // s is guaranteed to be "Car" here 24-26: Immutable Strings String objects are immutable Once a string object is created, it can t be changed String variables can be changed Create a new String object, assign it to the variable String s = "dog"; s = "cat"; 24-27: Mutable Objects public class ICanChange private int x; public ICanChange(int initialx) this.x = initialx; public int getx() return this.x; publc void setx(int newx) this.x = newx; 24-28: Mutable Objects

CS112-2012S-24 Final Review I 7 ICanChange c = new ICanChange(4); c.setx(11); // Changed the value in object // c points to System.out.println(c.getX()); Created an object of type ICanChange Changed the data within that object 24-29: Mutable Objects ICanChange c = new ICanChange(4); c = new ICanChange(11); System.out.println(c.getX()); Created an object of type ICanChange, with value 4 Created a new object of type ICanChange, with value 11 Throw away the old object 24-30: Mutable Objects ICanChange c = new ICanChange(4); StrangeClass s = new StrangeClass(); // Don t know what this does... s.foo(c); System.out.println(c.getX()); 24-31: Mutable Objects public class StrangeClass void foo(icanchange a) a.setx(99); 24-32: Immutable Object public class ICantChange private int x; public ICanChange(int initialx) this.x = initialx; public int getx() return this.x; 24-33: Immutable Object ICantChange c = new ICantChange(13); System.out.println(c.getX()); c = new ICantChange(37); System.out.println(c.getX()); Create a new object, have c point to this new object Old object didn t change, but the value of c did...

CS112-2012S-24 Final Review I 8 24-34: Immutable Object ICantChange c = new ICantChange(13); Strange s = new Strange(); s.foo(c); System.out.println(c.getX()); Do we know anything about what the println will ouput? 24-35: Immutable Objects public class Strange void foo(icantchange icc) // We can t change the value of x stored in icc // directly (private, no setters) // // Best we can do is change what icc points to... icc = new ICantChange(99); // icc.getx() would return 99 here, but what about // the calling function? 24-36: Methods Classes can contain both data and methods When a method is called: 24-37: Methods Calculate values of all method parameters (including implicit this parameter) Copy values of parameters into activation record of new method Execute method, using activation record for local variables When method is completed, pop activation record off the stack class MyClass public static void main(string args[]) public int x; int x; public int y; MyClass c = new MyClass(); x = 3; int foo(int w) c.x = 4; c.y = 5; int q; x = c.foo(x); q = x + w; System.out.println(x); return q+y; 24-38: Methods class MyClass public static void main(string args[]) public int x; int x; public int y; MyClass c = new MyClass(); x = 3; int foo(int w) c.x = 4; c.y = 5; int q; x = c.bar(x); q = x + w; System.out.println(x); return q+y; int bar(int p) return foo(x) + foo(p); 24-39: Collections of Data We want to bundle a bunch of values together

CS112-2012S-24 Final Review I 9 We can: 24-40: Arrays Want to represent several different values using a single variable Create a class with several instance variables Create an array Arrays are objects Access elements using [] notation Need to declare the size of the array when it is created Can t change the size of an array once it is created Get the length of the array using public length instance variable 24-41: Arrays Two ways to declare arrays: <typename>[] variablename; <typename> variablename[]; Examples: int A[]; // A is an array of integers int[] B; // B is an array if integers String C[]; // C is an array of strings 24-42: Arrays: New Like all other objects, Arrays are stored on the heap int A[] just allocates space for a pointer Need to call new to create the actual array new <type>[<size>] 24-43: Arrays: New Show contents of memory after each line: int A[]; int B[]; A = new int[10]; B = new int[5]; A[7] = 4; B[2] = 5; B[5] = 13; /// RUNTIME ERROR! 24-44: Arrays: Copying

CS112-2012S-24 Final Review I 10 int A[] = new int[size]; int B[] = new int[size]; // Code to store data in B A = B; What do you think this code does? What happens when we assign any object to another object? 24-45: Arrays: Copying int A[] = new int[size]; int B[] = new int[size]; // Code to store data in B A = B; How could we copy the data from B into A (A and B should point to different memory locations, have same values 24-46: Arrays: Copying int A[] = new int[size]; int B[] = new int[size]; // Code to store data in B for (int i = 0; i < B.length; i++) A[i] = B[i]; 24-47: Array: Copying int A[] = new int[5]; int B[] = new int[5]; int C[]; for (int i = 0; i < 5; i++) A[i] = i; for (int i = 0; i < 5; i++) B[i] = A[i]; C = A; B[2] = 10; C[2] = 15; 24-48: Arrays of Objects We can have arrays of objects, as well as arrays of integers

CS112-2012S-24 Final Review I 11... Point pointarray[] = new Point[10]; pointarray[3].setx(3); What happens? (refer to Java documentation for Point objects) 24-49: Arrays of Objects Point pointarray[] = new Point[10]; for (int i = 0; i < 10; i++) pointarray[i] = new Point(i, i); How would you calculate the average x value of all elements in the array? 24-50: Arrays of Objects How would you calculate the average x value of all elements in the array? Point pointarray[] = new Point[10]; // Fill in pointarray // double sum = 0.0; for (int i = 0; i < pointarray.length; i++) sum = sum + pointarray[i].getx(); sum = sum / pointarray.length; 24-51: 2D Arrays We can create 2D arrays as well as 1D arrays Like matrices 2D array is really just an array of arrays 24-52: 2D Arrays int x[][]; int[][] y; // Declare a 2D array // Alternate way to declare 2D array x = new int[5][10]; y = new int[4][4]; // Create 50 spaces // create 16 spaces 24-53: 2D Arrays int x[][]; x = new int[5][5]; // Declare a 2D array // Create 25 spaces x[2][3] = 11; x[3][3] = 2; x[4][5] = 7; // ERROR! Index out of bounds

CS112-2012S-24 Final Review I 12 24-54: 2D Arrays How would we create a 9x9 array, and set every value in it to be 3? 24-55: 2D Arrays How would we create a 9x9 array, and set every value in it to be 3? int board[][]; board = new int[9][9]; for (int i = 0; i < 9; i++) for int (j = 0; j < 9; j++) board[i][j] = 3; 24-56: Using Arrays Need to declare array size before using them Don t always know ahead of time how big our array needs to be Allocate more space than we need at first Maintain a second size variable, that has the number of elements in the array we actually care about Classes that use arrays often will have an array instance variable, and a size instance variable (how much of the array is used) 24-57: Arrays On board: What memory looks like for the following: public static void main(string args) int A[]; int x; String B[]; <-- Show memory here A = new int[5]; B = new String[3]; <-- Show memory here 24-58: Recursion The way function calls work give us a fantastic tool for solving problems Make the problem slightly smaller Solve the smaller probelm using the very function that we are writing Use the solution to the smaller problem to solve the original problem 24-59: Recursion What is a really easy (small!) version of the problem, that I could solve immediately? (Base case) How can I make the problem smaller?

CS112-2012S-24 Final Review I 13 Assuming that I could magically solve the smaller problem, how could I use that solution to solve the original problem (Recursive Case) 24-60: Recursion Example: Factorial n! = n (n 1) (n 2)... 3 2 1 5! = 5 4 3 2 1 = 120 8! = 8 7 6 5 4 3 2 1 = 40320 What is the base case? That is, a small, easy version of the problem that we can solve immediately? 24-61: Recursion Factorial Example: Factorial n! = n (n 1) (n 2)... 3 2 1 What is a small, easy version of the problem that we can solve immediately? 1! == 1. 24-62: Recursion Factorial How do we make the problem smaller? What s a smaller problem than n!? (only a liitle bit smaller) 24-63: Recursion Factorial How do we make the problem smaller? What s a smaller problem than n!? (n 1)! If we could solve (n 1)!, how could we use this to solve n!? 24-64: Recursion Factorial How do we make the problem smaller? What s a smaller problem than n!? (n 1)! If we could solve (n 1)!, how could we use this to solve n!? n! = (n 1)! n 24-65: Recursion Factorial

CS112-2012S-24 Final Review I 14 int factorial(int n) if (n == 1) return 1; else return n * factorial(n - 1); 24-66: Recursion Factorial 0! is defined to be 1 We can modify factorial to handle this case easily 24-67: Recursion Factorial 0! is defined to be 1 We can modify factorial to handle this case easily int factorial(int n) if (n == 0) return 1; else return n * factorial(n - 1); 24-68: Recursion To solve a recursive problem: Base Case: Version of the problem that can be solved immediately Recursive Case 24-69: Recursion Tips Make the problem smaller Call the function recursively to solve the smaller problem Use solution to the smaller problem to solve the larger problem When writing a recursive function Don t think about how the recursive function works all the way down Instead, assume that the function just works for a smaller problem Recursive Leap of Faith Use the solution to the smaller problem to solve the larger problem 24-70: Recursion NumDigits Write a method that returns the number of base-k digits in a number n int numdigits(int n, int k) numdigits(20201, 10) == 5

CS112-2012S-24 Final Review I 15 numdigits(34, 10) == 2 numdigits(3050060,7) == 7 numdigits(137, 2) == 8 What is the base case? How can we make the problem smaller? How can we use the solution to the smaller problem to solve the original problem? 24-71: Recursion NumDigits int numdigits(int n, k) if (n < k) return 1; else return 1 + numdigits(n / k); 24-72: Recursion Problems Write a recursive function that returns the smallest value in the first size elements of an array of integers int minimum(int A[], int size) 24-73: Recursion Problems int minimum(int A[], int size) if (size == 0) return null; if (size == 1) return A[0]; int smallest = minimum(a, size - 1); if (smallest < A[size - 1]) return smallest; else return A[size - 1]; 24-74: Static Normally, can only call methods on classes when we created an instance of the class 24-75: Static Methods can rely on instance variables to work properly Need to create an instance of a class before there are any instance variables What would the size() method return for an ArrayList if there was not an instance to check the size of? Some methods don t operate on an instance of the class pure functions that don t use instance variables at all Math functions like min, or pow parseint takes a string as an input parameter, and returns the integer value of the string parseint( 123 ) returns 123 Seems silly to have to instantiate an object to use these methods static to the rescue! 24-76: Static

CS112-2012S-24 Final Review I 16 If we declare a method as static, it does not rely on an instance of the class Can call the method without creating an instance first Use the Class Name to invoke (call) the method double x = Math.min(3.4, 6.2); double z = Math.sqrt(x); 24-77: Consants Having 3.14159 appearing all over your code is considered bad style Could end up using different values for pi in different places (3.14159 vs. 3.1415926) If you want to change the value of pi (to add more digits, for instance), need to search through all of your code to find it In general, any time you have a magic number (that is, an arbitrary numeric literal) in your code, it should probably be a symbolic constant instead. The final modifier is used to prevent you from changing the value of a variable 24-78: Consants class Calendar final int MONTHS_IN_YEAR = 12; final int DAYS_IN_WEEK = 12; final int DAYS_IN_YEAR = 365; // Methods that use the above constants Every instance of class Calendar will contain those 3 variables Somewhat wasteful Need to instantiate an object of type Calendar to access them 24-79: Consants: Static We can declare variables to be static as well as methods Typically used for constants (Math.pi, Math.e) Access them using class name, not instance name (just like static methods) You should only use static variables for constants public static final float pi = 3.14159; 24-80: Globals: Static It is technically possible to have a variable that is public and static, but not final Can be accesed anywhere Can be changed anywhere While the compiler will allow it, this is (usually!) a very bad idea. Why?