Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Introduction to Programming II: Review by Chris Brooks - University of San Francisco, Study notes of Computer Science

A review of the introduction to programming ii course offered by chris brooks at the university of san francisco. It covers topics such as method invocation, method signatures, data hiding, constructors, multiple constructors, overloaded operators, arraylist, linkedlist, abstract classes, interfaces, recursion, binary search trees, and more. Students will learn about various programming concepts and techniques using java as the primary programming language.

Typology: Study notes

Pre 2010

Uploaded on 07/30/2009

koofers-user-ob7
koofers-user-ob7 🇺🇸

10 documents

1 / 92

Toggle sidebar

Related documents


Partial preview of the text

Download Introduction to Programming II: Review by Chris Brooks - University of San Francisco and more Study notes Computer Science in PDF only on Docsity! Intro to Programming II Review Chris Brooks Department of Computer Science University of San Francisco Department of Computer Science — University of San Francisco – p. 1/?? 25-2: Slides • So what have we learned about this semester? Department of Computer Science — University of San Francisco – p. 2/?? 25-5: Example /** This is a method definition */ public double depositFunds(double amt) { balance = balance + amt; return balance; } ... bankacct b = new bankacct(); paycheck = 100.0 /* this is a method invocation */ b.depositFunds(paycheck); Department of Computer Science — University of San Francisco – p. 5/?? 25-6: Method signature • Specification of all data types coming in and out of a method. ◦ Type and order of input parameters ◦ Type of return variable • A method signature allows the compiler to uniquely identify a method. Department of Computer Science — University of San Francisco – p. 6/?? 25-7: Example • Consider the following method declaration: • double calculate(double a1, double a2, double a3); • Which of the following are valid calls to this method? ◦ calculate(3, 52.0, -5.1); ◦ double y = calculate(0, 1.1, 2.2); ◦ calculate(1.1, 2.3); ◦ calculate(“Hello”, 4.4, 2); ◦ calculate(); ◦ calculate(3.3); Department of Computer Science — University of San Francisco – p. 7/?? 25-10: Methods • As we know, classes also contain methods. • Methods are pieces of code that can be invoked on an object. • The allow us to encapsulate both state and behavior. Department of Computer Science — University of San Francisco – p. 10/?? 25-11: Data hiding • It’s also important to protect instance data from outside users. • One way to do this is by providing accessors and mutators ◦ “setters and getters” • Rather than the user modifying your object’s data directly, they use a method to do it. ◦ Reduces error ◦ Hides implementation from the user. Department of Computer Science — University of San Francisco – p. 11/?? 25-12: Constructors • A constructor is a method that is called when an object is first created. • Its responsibility is to initialize an object’s instance variables. • It must have the same name as the class in constructs. • It has no return type. • It is called when ’new’ is invoked. Department of Computer Science — University of San Francisco – p. 12/?? 25-15: Multiple Constructors public class Circle { private Point center; private int radius; public Circle(Point c) { center = c; radius = 1; } public Circle (Point c, int r) { center = c radius = r; } } Department of Computer Science — University of San Francisco – p. 15/?? 25-16: Strings in Java • Strings in Java are objects • This mean that they have a set of methods they respond to: ◦ compareTo(), equals() ◦ indexOf() ◦ length() ◦ replace() ◦ startsWith(), endsWith() ◦ etc Department of Computer Science — University of San Francisco – p. 16/?? 25-17: Overloaded operators • Unlike most other objects, Strings also have special behavior for creating string literals and for concatenation. • String literals are strings where the value is known at compile time: ◦ String s1 = “hello world” ◦ String s2 = “USF” ◦ String s3 = “I love Java” • We can create a string without calling new. Department of Computer Science — University of San Francisco – p. 17/?? 25-20: Working with Files • We can use Scanner to also read from a file. • Relevant methods: ◦ hasNext() ◦ next() ◦ nextLine() ◦ nextInt() ◦ ... Department of Computer Science — University of San Francisco – p. 20/?? 25-21: Using Scanner to read from files • We can use the Scanner class to read from a file instead of System.in try { Scanner sc = new Scanner(new File("studentlist")); while (sc.hasNext()) { System.out.println(sc.next()); } } catch(FileNotFoundException e) { System.out.println("File not found."); } Department of Computer Science — University of San Francisco – p. 21/?? 25-22: File output • Output is a little more complicated. ◦ No equivalent of the Scanner class. • PrintWriter is the thing to use. Department of Computer Science — University of San Francisco – p. 22/?? 25-25: Run-time environment • The run-time environment refers to the way in which memory is used/arranged. • Memory is arranged as a sequence of addresses • Each address refers to a word in memory. • We can break the runtime environment into four sections: ◦ Program code: Where the program itself resides ◦ Global data area: Global and static data is stored here. ◦ Run-time stack: This contains an activation record for each method that is called. ◦ Heap: Dynamically-allocated data (with new or malloc) is stored here. Department of Computer Science — University of San Francisco – p. 25/?? 25-26: Activation Records • An activation record sets a context for a method’s execution. • It contains: ◦ Space for all parameters, including ’this’, a pointer to the object itself. ◦ Space for a return value ◦ Space for local variables. • Each time a method is called, its activation record is pushed onto the stack. • When the method exits, its activation record is removed. Department of Computer Science — University of San Francisco – p. 26/?? 25-27: Symbol table • The symbol table is responsible for mapping variable names to addresses. • This is how the Java interpreter knows the value that is currently associated with a variable. Department of Computer Science — University of San Francisco – p. 27/?? 25-30: Arrays • We need to use ’new’ to actually allocate memory for the array. int x = sc.nextInt(); atBats = new int[10]; runs = new int[x]; • This means that the reference to the array will be allocated on the stack, while the array itself will be allocated on the heap. Department of Computer Science — University of San Francisco – p. 30/?? 25-31: Advantages and disadvantages of arrays • Advantages: ◦ All memory is contiguous ◦ Can ’jump’ directly to any element of the array. • Disadvantages: ◦ Hard to resize or add elements. Department of Computer Science — University of San Francisco – p. 31/?? 25-32: The ArrayList class • Last time, we learned about how to use arrays in Java. • Java also provides an ArrayList class that can help manage arrays. • ArrayList is a generic container. ◦ That means that we can use the same container to store different kinds of elements. Department of Computer Science — University of San Francisco – p. 32/?? 25-35: Accessing elements • get(index) lets us access the element at a particular index. • Elements in an ArrayList are stored as Objects. • This means that we need to cast them back to Strings. • Can’t store primitives. String name = (String)band.get(2); Department of Computer Science — University of San Francisco – p. 35/?? 25-36: Finding elements • We can use indexOf to find where an element is located. • remove lets us remove things. int index = band.indexOf(‘‘ringo’’) band.remove(index) Department of Computer Science — University of San Francisco – p. 36/?? 25-37: Linked Lists • Linked lists have the opposite advantages and disadvantages • Advantages: ◦ Easy to insert and remove ◦ Easy to resize • Disadvantages: ◦ Elements are not stored sequentially ◦ Finding the nth element is slower. Department of Computer Science — University of San Francisco – p. 37/?? 25-40: List elements public class ListItem { public Object data; public ListItem next; public ListItem(Object d) { data = d; next = null; } } Department of Computer Science — University of San Francisco – p. 40/?? 25-41: Arranging ListItems • ListItems hook together like a chain. • All we need to do is keep track of the beginning of the chain. • No need to allocate everything ahead of time. Department of Computer Science — University of San Francisco – p. 41/?? 25-42: The LinkedList class • The LinkedList will be responsible for hanging onto the ’head’ of the list and providing methods for working with the list. ◦ Insert() ◦ InsertAt(index) ◦ get(index) ◦ remove(index) ◦ find(object) Department of Computer Science — University of San Francisco – p. 42/?? 25-45: Adding • What about adding something into the middle of a list? • If we want an item to go between current elements 5 and 6, then we need our new item to point to 6, and 5 to point to the new element. • How do we code this? Department of Computer Science — University of San Francisco – p. 45/?? 25-46: Adding public void insertAt(Object o, int index) { // first find the place to insert it. ListItem pointer = head; ListItem l = new ListItem(o); for (int i = 0; i < index -1; i++) { pointer = pointer.next; } l.next = pointer; pointer = l; } Department of Computer Science — University of San Francisco – p. 46/?? 25-47: Synchronous vs Asynchronous input • The programs you’ve built so far (lexer and parser) are examples of synchronous input. ◦ You prompt for input, then read input with a Scanner. • Programs with a graphical user interface (GUI) typically require asynchronous input ◦ A user can provide input at any time. • This requires a different model of programming. Department of Computer Science — University of San Francisco – p. 47/?? 25-50: Inheritance Review • Inheritance allows us to reuse existing code. • Allows us to define a hierarchy of classes. • Base class has the most general behavior • Derived classes have more specific behavior. Department of Computer Science — University of San Francisco – p. 50/?? 25-51: Example public class Person { public String lastName; public String id; public void eat() { }; public void sleep() { }; } Department of Computer Science — University of San Francisco – p. 51/?? 25-52: Example public class Professor extends Person { public String officeNum; public void teach() { }; public void grade() { }; public void forget() { }; } Department of Computer Science — University of San Francisco – p. 52/?? 25-55: Abstract classes • Solution: define Shape as an abstract class public abstract class Shape { public int locX; public int locY; public abstract double area(); // note: semi-colon, no method body } Department of Computer Science — University of San Francisco – p. 55/?? 25-56: Abstract classes • An abstract class is one that has one or more abstract methods. ◦ Can also have concrete methods. • Classes that subclass from an abstract class must override all abstract methods. • An abstract class therefore provides a common interface for a set of subclasses Department of Computer Science — University of San Francisco – p. 56/?? 25-57: Dynamic binding • What if we have this situation: public class A { public void m1() { } public void m2() { } } public class B extends A { public void m2() { } } B bex = new B(); A aex = new B(); bex.m1(); aex.m1(); bex.m2() • Which methods are called? Department of Computer Science — University of San Francisco – p. 57/?? 25-60: Interfaces • Interfaces let us specify which methods an object should respond to, without specifying how they should respond. • This provides polymorphism - each object responds to a method in the appropriate way. • A class can implement as many interfaces as it wants. Department of Computer Science — University of San Francisco – p. 60/?? 25-61: Recursion • Recursion is a fundamental problem-solving technique • Involves decomposing a problem into: ◦ A base case that can be solved directly ◦ A recursive step that indicates how to handle more complex cases. • A common recursive example is factorial: long factorial(int input) if (input == 1) return 1; else return input * factorial(input - 1); Department of Computer Science — University of San Francisco – p. 61/?? 25-62: Recursion • A more interesting example is the Towers of Hanoi. • It’s hard to write an iterative program to solve this, but the recursive version is startlingly simple: void towers(int ndisks, Tower startTower, Tower goalTower, Tower tempTower) if (ndisks == 0) return; else towers(ndisks - 1, startTower, tempTower, goalTower); moveDisk(startTower, goalTower); towers(ndisks - 1, tempTower, goalTower, startTower); Department of Computer Science — University of San Francisco – p. 62/?? 25-65: Implementing a tree • A struct representing a tree containing strings: typedef struct treeNode *treeptr; typedef struct treeNode { char *data; treeptr left; treeptr right; } treeNode; • We need to declare a type called ’treeptr’, because otherwise the C compiler doesn’t know what a treeNode is until the definition is processed. Department of Computer Science — University of San Francisco – p. 65/?? 25-66: Binary Search Trees • Binary Trees • For each node n, (value stored at node n) > (value stored in left subtree) • For each node n, (value stored at node n) < (value stored in right subtree) Department of Computer Science — University of San Francisco – p. 66/?? 25-67: Adding methods to BST void insert(treeptr root, char *newdata) { treeNode *newNode; if (strcmp(root->data, newdata) <= 0) { if (root->left == NULL) { newNode = makeNode(newdata); root->left = newNode; return; } else { return insert(root->left, newdata); } } else { if (root->right == NULL) { newNode = makeNode(newdata); root->right = newNode; return; } else { return insert(root->right, newdata); } } } Department of Computer Science — University of San Francisco – p. 67/?? 25-70: Counting nodes • So how would we count the number of nodes in a tree? Department of Computer Science — University of San Francisco – p. 70/?? 25-71: Counting nodes • If the tree is null, return 0. • Otherwise, return 1 + the number of nodes in the left subtree + the number of nodes in the right subtree. • Exercise: add a countNodes() method to our TreeNode class. Department of Computer Science — University of San Francisco – p. 71/?? 25-72: Introduction to C • C is a compiled language ◦ Produces a binary that executes on one architecture/OS • Java compiles to an intermediate representation (bytecodes) ◦ A Java program can be executed by a Java interpreter on any system. Department of Computer Science — University of San Francisco – p. 72/?? 25-75: Things that are different in C and Java • No built-in String class • No classes/objects/methods • Memory allocation • No garbage collection • Much fewer standard libraries • Java has references; C allows you to directly manipulate pointers. Department of Computer Science — University of San Francisco – p. 75/?? 25-76: Pointers • The biggest difference between C and Java is the use of pointers. • A pointer is the actual address that a variable is stored at. int main(void) \{ char *testStr = "hello world"; printf("\%s\n", testStr); printf("\%d\n", *testStr); printf("\%d\n", *testStr + 3); \} Department of Computer Science — University of San Francisco – p. 76/?? 25-77: Pointers • To declare a pointer to a variable, use * ◦ char *hello = “hello world”; • To get at the data, use the variable name ◦ printf(“%s”, hello); • To dereference the data and use the address, add a the ’*’ to the front of the variable name. ◦ This produces an integer. ◦ printf(“%d”, *hello); Department of Computer Science — University of San Francisco – p. 77/?? 25-80: Paramters in C • In C, things are more straightforward. • Variables are passed by value. • To pass by reference, you can provide a reference to the variable using &. Department of Computer Science — University of San Francisco – p. 80/?? 25-81: References vs Pointers • Let’s start with a variable: ◦ int x • To refer to the address that x is stored at, we use the address operator ◦ &x • To create a pointer to an integer, we use the * operator: ◦ int *iptr; • iptr is a variable of type int * - that is, it’s the address of an integer. • So, we can do: ◦ iptr = &x; ◦ (the variable iptr, which is an address of an int, is set to the address of x, which is an int.) Department of Computer Science — University of San Francisco – p. 81/?? 25-82: References vs Pointers • So, & is used to get from a variable to its address. ◦ scanf ◦ calling a function with pass by reference • * is used when you want to start with an address, and then create a variable. ◦ dynamically allocating memory ◦ being called with pass by reference Department of Computer Science — University of San Francisco – p. 82/?? 25-85: Multidimensional Arrays • Many times, you want to have an array with more than one dimension. ◦ A 2D game board. ◦ An array or strings. ◦ A bitmap representing a graphic object. • In C, this is represented as an array of arrays. Department of Computer Science — University of San Francisco – p. 85/?? 25-86: Arrays of pointers • What if we don’t know ahead of time how big our array should be? • Then we need to use malloc to allocate memory on the fly. • In this case, we treat our 2D array as an array of pointers (or, an array of arrays) int **intArray; • intArray is a pointer to an array of pointers. Department of Computer Science — University of San Francisco – p. 86/?? 25-87: Arrays of pointers • We start out using malloc as usual (almost): int **intArray = (int **)malloc(10 * sizeof(int *)); • We used malloc to create an array of 10 int pointers • But, none of those pointers point to anything yet. • We have to go through and use malloc to allocate space for each of those arrays as well. for (i = 0; i < 10; i++) intArray[i] = (int *)malloc(10 * sizeof(int)); Department of Computer Science — University of San Francisco – p. 87/?? 25-90: Opening files for reading • For example FILE *fp = fopen("myfile","r"); opens myfile for reading. Department of Computer Science — University of San Francisco – p. 90/?? 25-91: Reading from a file • fscanf is used to read from a file. • Works exactly like scanf, except that the first argument is the file pointer. • You can also use getc - it returns the integer representing the next character in the file. • getc() returns EOF if you’re at the end of the file. Department of Computer Science — University of San Francisco – p. 91/?? 25-92: Working with command line arguments • To do this, we need to specify that main() will receive arguments. ◦ Remember, main is just another function. • It takes its arguments in a special form: int main(int argc, char **argv) • argc is the number of command line arguments • argv is an array of strings, one for each argument. • argv[0] is the name of the program. Department of Computer Science — University of San Francisco – p. 92/??
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved