CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… ·...

37
CS 180 Final Exam Review 12/(11, 12)/08

Transcript of CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… ·...

Page 1: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

CS 180 Final Exam Review12/(11, 12)/08

Page 2: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Announcements

Final ExamThursday, 18th December, 10:20 am – 12:20 pm in PHYS 112Format

30 multiple choice questions5 programming questions

More stress on topics (chap 11 – 15) covered after exam 2

RecursionDynamic Data StructuresWindow Interfaces using SwingApplets and HTML More Swing

Page 3: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Object-Oriented Design

MethodsExtract functionalities of a program which will be performed multiple times

Encapsulation and Information HidingClasses, Objects, and Polymorphism

Covered in more detail later

Page 4: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Primitives

int, double, boolean, float, char, etc.

These are NOT ObjectsCan be compared with ==, !=, <=, >=, etc.Wrapper classes for each primitive

Why do we need them?

Explicit type-casting may need to be donebyte short int long float double

Page 5: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Objects and ClassesClass variables hold references (the address) to the objectsAlways compare with the equals() method

Do NOT use == to compare objectsAssignment operators assign references – they do not make separate copiesConstructors should be used to initialize class variables

Calling methodsNeed objectStatic methods

Can use class nameCannot access non-static methods/variables inside

Pass by value always

Keyword: this

Page 6: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Strings

Strings are a type of objectAlso should not be compared with ==

Important String functionscharAtindexOfsubstringlengthConcatenation operator +

Page 7: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Selection Statements

Modifies the flow of control of the programif/else construct

Must have a boolean condition to check against{ } are strongly recommended, but not necessary for one line statements

switch constructMulti-way branch which makes a decision based on a char, byte, short, or int typedefault casebreak statement

Page 8: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Repetition statements - Loops

forwhiledo-whileBeware of -

Off-by-one errorsInfinite loopingOverflow

Page 9: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

ArraysLinear collection of data

Can hold primitives or class types, but must all be of the same type

length tells the number of elements in the arrayMember, not a method

Indexed from 0 to length – 1Multiple dimension arraysConvenient to use for-loops to iterate through members of the arrayRemember – arrays are reference types

Page 10: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Exceptions

Use a try/catch/finally block to handle exceptions thrown by a program

Use throw statement to notify caller of an error

User defined exceptions must extend Exception

Page 11: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

File I/O

Useful classesFileInputStream, DataInputStream, FileReader, BufferedReader, Scanner, PrintWriter, DataOutputStream, etc.ObjectInputStream, ObjectOutputStream

Used to write objects to a fileAny object serialized by a stream must implement Serializable

Which classes are used to write text and which are used to write binary?Always close files you open

Page 12: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Inheritance and PolymorphismDifferences between abstract classes and interfacesPolymorphism can simplify codeExtend specific classes from general classesUse protected keyword to protect information and methodsReuse inherited functionality from parent class.Call to base class’s constructor is always called at the first line of constructor.

Page 13: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Dynamic Data Structures

Inner classesLists

Node classCircularly linked listsDoubly linked lists

Trie data structure ( from project 7 )Java Collections

VectorArrayListLinkedList

Page 14: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Recursion

Break down a problem to one or more sub-problemsBe concerned only with the current level of recursionTwo necessary cases

Base caseRecursive step

Page 15: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

GUI and Event-driven Programming

Common classesJFrameJPanelJLabelJMenu, JMenuItemJButton

LayoutsBorderLaoutGridLayoutFlowLayout

Page 16: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Challenges

Page 17: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Types

Given the following classes, which of the following declarations are valid?

public interface I {…}

public interface J extends I {…}

public interface K {…}

public abstract class A {…}

public class B extends A {…} implements J, K

public class C extends B {…}

public class D extends A {…} implements I

A a = new B();B b = new J();C c = new B();B b = new C();I i = new A();I i = new B();I i = new D();K k = new C();

Page 18: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Types

Given the following classes, which of the following declarations are valid?

public interface I {…}

public interface J extends I {…}

public interface K {…}

public abstract class A {…}

public class B extends A {…} implements J, K

public class C extends B {…}

public class D extends A {…} implements I

A a = new B();B b = new J();C c = new B();B b = new C();I i = new A();I i = new B();I i = new D();K k = new C();

valid – B is a subclass of Ainvalid – cannot instantiate interfacesinvalid – B is the superclass of Cvalid – C is a subclass of Binvalid – A does not implement Ivalid – A implements J, and J is-a Ivalid – D implements Ivalid – C extends B which implements K

Page 19: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Recursion and Linked Lists

Question-A gradebook is made out of the the following Node class.

class Node{

private int[] values; // these values are sorted in ascending orderprivate Node next;

public Node(int[] values, Node next)public int[] getValues()public void setValues(int[] values)public Node getNext()public void setNext(Node next)

}1) Each Node contains an array of scores that are within a certain range. 2) The gradebook contains a linked list of the Node class.For example, you may use the 1st Node to store all the scores in the F range, the 2nd Node to store all the scores in the D range, the 3rd Node to store all the scores in the C range, etc.

Page 20: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Recursion and Linked Lists

Question continued-

Each node represents a non-overlapping group of grade values and each successive Node contains a range of group values greater than the previous Node.

Write an efficient method gradeExists(int), which returns true if the grade exists within the Gradebook, and false otherwise.

Since the values array is sorted, you should take advantage of this and perform a binary search for the specified value.

Page 21: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Recursion and Linked Lists

Approach to the solution:

The solution can be broken into two parts:1. Finding the node which might contain the grade.

Since all nodes have non-overlapping ranges (in sorted order) and the arrays in turn are sorted, we only need to compare the range of each node with the given grade.

2. Do binary search on the values in that node.

Page 22: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Recursion and Linked Lists

Part 1:public boolean gradeExists(int grade){

Node temp = gradebook;while (temp != null){

int[] values = temp.getValues();if (grade < values[0])

return false;if (grade >= values[0] && grade <= values[values.length-1])

return binarySearch(values, grade, 0, values.length-1);temp = temp.getNext();

}return false;

}

Page 23: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Recursion and Linked Lists

Part 2:private boolean binarySearch(int[] array, int value, int lo, int hi){

if (lo > hi)return false;

if (lo == hi)return array[lo] == value;

int mid = (hi + lo)/2;if (array[mid] == value)

return true;else if (array[mid] > value)

return binarySearch(array, value, lo, mid-1);else

return binarySearch(array, value, mid+1, hi);}

Page 24: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

RecursionWrite a function isPalindrome(String) which takes in a String and returns true if the String is a palindrome, false otherwise.Ignore the case of the letters and skip over blanks when you make the comparison.public boolean isPalindrome(String s){

}

Page 25: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Recursion

Solution:public boolean isPalindrome(String s){

if (s == null)return false;

if (s.length() <= 1)return true;

return ( s.charAt(0) == s.charAt(s.length()-1) &&isPalindrome(s.substring(1, s.length()-1)) );

}public static void main(String[] args){

...result = isPalindrome(s.toLowerCase().replace(“ “,””));

}

Page 26: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

GUIQuestion:Create a complete Java GUI program that allows the user to enter the text for JLabels, possibly with multiple lines, and then preview them. You should use the following design:

The user can enter text in the text area. Then, when the button is pushed, this text is displayed as a label in the label preview.

Title

Button

Text Area Label Preview

Enter Text: Label Preview:

Page 27: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

GUI - solution

public class CH12 extends JFrame implements ActionListener

{JButton theButton = new JButton(

"Preview" );JTextArea theText = new JTextArea();JLabel theLabel = new JLabel();

public CH12() {super( "Label Previewing Program" );setSize( 400, 200 );

//button in south JPanel aPanel = new JPanel();aPanel.add( theButton );this.add( "South", aPanel );

//label in northaPanel = new JPanel();aPanel.add( new JLabel("The Label

Previewer") );this.add( "North", aPanel );

JPanel centerPanel = new JPanel( new GridLayout(1,2) );

//text area in center leftaPanel = new JPanel( new BorderLayout());aPanel.add( "North", new JLabel("Enter

Text:") );theText.setLineWrap( true );aPanel.add( "Center", theText );centerPanel.add( aPanel );

//preview label in center rightaPanel = new JPanel( new BorderLayout());aPanel.add( "North", new JLabel("Label

Preview:") );aPanel.add( "Center", theLabel );centerPanel.add( aPanel );

this.add( "Center", centerPanel );

theButton.addActionListener( this );

}

Page 28: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

GUI – solution contd.public void actionPerformed( ActionEvent e ){

theLabel.setText( theText.getText() );}

public static void main( String[] args ){

JFrame ch12Frame = new CH12();ch12Frame.setVisible( true );

}

} //end of class def

Page 29: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Arrays

Write a method which takes in an array of integers and replaces the values of the array with a value ci, where ciis defined as –ci = the sum of the numbers in indices 0…i in the incoming array.

public void cumulativeArray(int[] a) {

}

Page 30: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

ArraysWrite a method which takes in an array of integers and replaces the values of the array with a value ci, where ciis defined as –ci = the sum of the numbers in indices 0…i in the incoming array.

public void cumulativeArray(int[] a) {

if (a.length <= 1)

return;

for (int k=1; k<a.length; k++)

a[k] = a[k] + a[k-1];

}

Page 31: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

What is the output?public class A

{

private int x;

public static int doStuff()

{

x = 100;x /= 3;x++;return x;

}

public static void main(String[] args)

{

System.out.println(A.doStuff());

}

}

Page 32: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

What is the output?

public class A

{

private int x;

public static int doStuff()

{x = 100;x /= 3;x++;return x;

}

public static void main(String[] args)

{

System.out.println(A.doStuff());

}

}

Because this method is static, it does not haveaccess to non-static class variables. This code will not compile because x is non-static.

Page 33: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Linked Lists

Given an appropriate Node class, write a method which removes every other node from the list, starting with the second.

public Node removeEveryOther(Node l){

}

Page 34: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Linked Lists

Given an appropriate Node class, write a method which removes every other node from the list, starting with the second.

public Node removeEveryOther(Node l){

Node l1 = l;while (l1 != null && l1.next != null){

l1.next = l1.next.next;l1 = l1.next;

}return l;

}

Page 35: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Linked Lists

Now write the same method, but recursively.

public Node removeEveryOther(Node l){

}

Page 36: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed

Linked Lists

Now write the same method, but recursively.

public Node removeEveryOther(Node l){

// base caseif (l == null || l.next == null)return l;

// recursive caseNode l1 = removeEveryOther(l.next.next);l.next = l1;return l;

}

Page 37: CS 180 Final Exam Review - web.ics.purdue.educs180/Fall2008Web/slides/finalexam-rev… · Object-Oriented Design Methods {Extract functionalities of a program which will be performed