590 likes | 774 Views
CSE 131 Final Exam Review Fall 2011. CSE 131 Full Review. Vinoo Ganesh. Java Details. What is Java? Java is a Programming Language Java is know as an Object Oriented Programming Language It works around things called “Objects” Ex. Color, Person, Vector, etc…
E N D
CSE 131 Final Exam ReviewFall 2011 CSE 131 Full Review Vinoo Ganesh
Java Details • What is Java? • Java is a Programming Language • Java is know as an Object Oriented Programming Language • It works around things called “Objects” • Ex. Color, Person, Vector, etc… • Java uses different data types to do calculations • Ex. int, boolean, double • Java is the LANGUAGE, Eclipse, is the IDE (Integrated Development Environment) • All statements in Java end with a semicolon
Data Types • Examples include: int, double, boolean • Basic data types (int, double, boolean) are NOT Objects • Some of these you can cast to another, some you can’t. • Ex. Which of the following will work? int var1 = true; double var2 = 4; int var3 = 6.9; boolean var4 = 5; THIS DOES NOT WORK THIS DOES WORK THIS DOES NOT WORK THIS DOES NOT WORK
Operators • && this is for and • || this is for or • < this is for less than • > this is for greater than • <= this if for less than or equal to • >= this is for greater than or equal to • == this is for equals
Recursion • Defn: Recursion is when a method calls itself • Recursion breaks down large problems into smaller sub-problems public void add(int x){ if (x==0) return 0; return x+add(x-1); }
Classes • Classes have 3 main components: • Instance Variables • Methods • Constructors • To instantiate a class (create an Object of a class), you must use the “new” keyword. • The new keyword allocates memory for whatever structure you are going to use.
Public/Private/Protected • Instance variables that are public: • Can be accessed from ANYWHERE, not just from the same class • Instance variables that are private: • Can be accessed from ONLY the class • Instance variables that are protected: • Can be accessed from ONLY the class and its subclasses
Constructors • A constructor helps “construct” an object • A constructor does not have a return type. • A constructor must have the same name as the class it is in • A default constructor has ZERO parameters public class Person{ private String name; public Person(String name){ this.name=name; } }
Loops • There are 2 kinds of loops: for loops and while loops. They look like the following.
While Loop • While Loop Structure: <initializing statement, ex. assign a variable a value> while(<condition>){ <do something until condition is met> <update so condition can eventually be met> } • Example: intnumber = 1; // initialize while(number <= 10){ // loop boundary conditionSystem.out.println(number); number++; // increment/decrement}
For Loops • A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. • A for loop is useful when you know how many times a task is to be repeated. for(<init>; <condition>; <update>) { <body> } <rest of program>
For-Each Loops • A for each loop is a shorthand way to iterate through all of the objects in a collection for(<dataTypeInCollection> a: <collection>) { <body> } <rest of program>
For-Each Loops • A for each loop is a shorthand way to iterate through all of the objects in a collection ArrayList<String> list; for(String a: list) { <body> } <rest of program>
Declaring a 1D Array type[] arrayName = new type[size];
Example Declaration Ex. int[] arr= new int[size]; Meaning: • int[] – tells the computer that you are making an array of integers • arr– the name of the array • new – this keyword actually tells the computer to allot memory • int[size] – allots memory for an array with “size” number of elements
Different Array Type Declarations int[] arr = new int[size]; double[] arr2 = new double[size]; boolean[] arr3 = new boolean[size]; Object[] arr4 = new Object[size]; • YES, you can have an array of Objects. • This is present in Conway too, where you have an array of Cell Objects
Index • The index of an element in the array is the “position” it is located at in the array • All array indices (indexs) start at 0. This means the first element of any array is at index 0
Accessing Elements in An Array Access elements in an array with the index of the position you want to access in brackets Example: If you have an array named “arr” arr[0] – accesses the first element arr[1] – accesses the second element arr[2] – accesses the third element
Traversal • To “move through” the array (either to set values in spots or to read values) int[] arr = newint[6]; // an array of 6 integers for (int b= 0; b< 6; b++){arr[b] = b* b;}
length • You have an array named arr: arr.length gives you the length of the array • Note: the last index in an array is at position: arr.length-1 • If you access an out of bounds index an ArrayIndexOutOfBoundsException is thrown
Note about length • Note: Length is NOT a method. • You are accessing an instance variable of array when you do “.length”
Your Turn Write a method, called average, that takes in an array as a parameter and that returns the average of the numbers in the array public double average (int[] arr) { //… }
Solution public double average (int[] arr) { int temp=0; for (int a=0; a<arr.length; a++) { temp+=arr[a]; } //length=0 check return 1.0*temp/arr.length; }
So we need… • Something that unordered (student order doesn’t matter) • Something where there is no early specification of size (don’t want a locked in size of students) • Something that doesn’t allow duplicates (can’t have duplicate people)
So we need… A Set!
Sets • A Set is an unordered collection of data • To traverse, you need to obtain something called an iterator • You cannot have duplicates in a set
Computer Science Vocab • Initialize: initial – ize • Give an initial value to something • Instantiate: intendance – ate • Create an instance of something (usually objects)
How to instantiate DataType<parameterization>name=new DataType<parameterization>(); • In the case of a set: HashSet<String> set = new HashSet <String>(); HashSet<Integer> set = new HashSet <Integer>(); HashSet <Person> set = new HashSet <Person>();
Common Set Methods -- Add boolean add(Object o) This attempts to add something to a set. If that element doesn’t already exist in the set (remember sets don’t have duplicates) it adds it and returns true. If the element is already in the set, it returns false. • But how does set know that two objects are the same? • There is a remove method that works similarily
Common Set Methods -- Contains boolean contains (Object o) Checks to see if the object named o already exists in the set. If it does exist,the method returns true. If it doesn’t exist, the method returns false.
Common Set Methods -- Size int size() Returns the number of objects in the set.
It look like… • We want a way to associate one piece of data with another. • We know that we can have multiple “things” with the same association value, but each “thing” has to be unique. • Ex. We can have multiple songs on the same album, but cannot have the same song be on different albums • For purposes of this, we are going to ignore “Greatest Hits” albums
So we need… A Map!
Maps • A Map maps a particular key to a particular value • Ex. Songs to Album
How to instantiate DataType<param1, param2>name=new DataType<param1, param2>(); • In the case of a map: HashMap<String, String> map = new HashMap<String, String>(); HashMap<String, Integer> map = new HashMap<String, Integer>(); HashMap<Integer, boolean> map = new HashMap<Integer, boolean>();
Common Map Methods -- Put boolean put(Key k, Value v) • Attempts to add a key and value pair to the map. If that key doesn’t already exist in the map it adds both the key and value pair and returns true. • If the key already exists in the map, it returns overwrites the value associated with that key and returns true. If an error occurs, it returns false.
Common Map Methods -- containsKey booleancontainsKey(Key k) • Checks to see if the map contains a the key k and returns true if it does • If it doesn’t, the method returns false.
Common Map Methods -- get <ValueType> .get(Key k) • Returns the value associated with the key k. • Returns null if no value associated with that key • For example, if k=“Stairway to Heaven”: map.get(k) will return “Led Zeppelin IV”
Common Map Methods -- size int size() Returns the number of keys in the map
It look like… • We want a way to index items on the list for easy accessibility. • We know that the order matters, so you need the ability to add things to particular places • We don’t want a pre-defined maximum sizebecause our list should be able to contain whatever we want.
So we need… A List!
How to instantiate DataType<param1>name=new DataType<param1>(); • In the case of a list: ArrayList<String> list= new ArrayList<String>(); LinkedList<Integer> list= new LinkedList<Integer>();
Common List Methods -- Add boolean add(Object o) • Adds a particular object o to the end of the list boolean add(int index, Object o) • Adds a particular object o to the specified index and pushes the rest of the elements back.
Common List Methods -- Get <ValueType> .get(int index) • Returns the object at the specified index value
Common List Methods -- isEmpty booleanisEmpty() • Returns true if the List is empty (has no elements)
Other ADTs -- Stack • Stack (LIFO)
Other ADTs -- Queue • Queue (FIFO)
Review: Queue Abstract Data Type • A queue stores a collection of items • Queues support the following operations: • enqueue(x) – add item x to the tail (end) of the queue • peek() – return the item at the head (beginning) of the queue • or null if nothing’s in the queue • dequeue() – remove the item at the head of the queue • also returns the item • throws an exception if nothing’s there!
This is a queue. • The first person added to the line is the first person removed from the line (or, in this case, the first to get an iPad) • This pattern called first-in, first-out (FIFO)
Binary Search Trees • Store items in a binary tree, with one element per node • Binary here means that each node has two children • Top of binary tree is called the root • Like the head of a list, this is where we start looking for things