Java Notes

Table of Contents 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. Lecture 1 – Course Overview Lecture 2 – Using Objects Lecture 3 – Defining Classes Lecture 4 – Types and Conditionals Lecture 5 – Iteration and Arrays 1 Lecture 6 – Iteration and Arrays 2 Lecture 7 – Linked Lists 1 Lecture 8 – Linked Lists 2 Lecture 9 – Stack Frames Lecture 10 – Testing Lecture 11 – Inheritance Lecture 12 – Abstract Classes Lecture 13 – Java Packages Lecture 14 – Exceptions Lecture 15 – More Java Lecture 1 – Course Overview Lecture 1 – Course Overview Lecture 1 – Course Overview Lecture 1 – Course Overview Lecture 1 – Course Overview Lecture 1 – Course Overview Page 1 2–3 4–5 6–7 8–9 10 – 11 12 – 13 14 – 15 16 – 17 18 – 19 20 – 21 22 – 23 24 – 25 26 – 27 28 – 29 4–5 4–5 4–5 4–5 4–5 4–5

0

1) Lecture 1 – Course Overview a) Goals i) Learning efficient data structures and algorithms. ii) Design and write large programs. iii) Understanding and designing data abstraction and interfaces. iv) Learn Java b) Object – Oriented Programming i) Object: Repository of data. ii) Class: Type of Object. iii) Methods: A procedure or function that operates on a particular class or object. iv) Inheritance: A class can inherit properties from a more general class. v) Polymorphism: One method call can work on several classes, even if the classes need different implementations. vi) Object – Oriented: Each object knows its own class and method c) Java i) 2 ways to get classes (1) Use one defined by someone else. (2) Define one yourself. ii) You must declare a variable before using it. String myString; myString Variable of type String my String = new String( ); (1) This has 2 distinct steps (a) “new String” is called a constructor. It constructs a string object. (b) Assignment “=” causes myString to reference the object. myString A String Object

1

2) Lecture 2 – Using Objects a) Objects and Methods i) String s1; // Step 1: declare a String variable ii) s1 = new String( ); // Step 2: assign it a value: a new empty string. String s2 = new String ( ); // 1&2 combined Line 1 creates a variable s1 that can store references to strings Line 2 constructs a new String object The “=” sign creates a reference between the two s1 s1 = “Yow!”; s1 Yow! String

The reference to “Yow!” directs to the new object and over writes old reference. s1=s2; // s1&s2 both reference same object. s1 Yow!

s2

If you want to make a copy s1 for s2 instead of reference the same object you first construct a new object then reference that object to s1‟s object s2 = new String(s1);// Now 2 different objects s1 Yow! s2 Yow!

b) 3 String constructs: i) new String( ) constructs an empty string containing no characters. ii) “whatever” constructs a string of “whatever”. iii) new String(s1) takes a parameter s1. Makes a copy of object that s1 references. **Constructers always have same name as their class, except “stuff in quotes”. s2 = s1.toUppercase( ); ! s2 Yow! Yow!!!

String s3 = s2.concat(“!!”); s3 //same as s3 = s2 + “!!”; The object “Yow!” did not change, s2 changed Strings are immutable; their contents never change

c) Java I/O Classes i) Objects in system class for interacting with a user (1) System.out is a PrintStream object that outputs to the screen. (2) System.in is a InputStream object that reads from the user. (3) readLine method is defined on BufferedReaderObjects. (a) How do we construct a BufferedReader? (i) We need and InputStream 1. How do we construct an InputStream? a. System.in one (ii) The InputStream objects reads an unformatted stream of rawdata. (iii) The InputStream passes the data to the Input Stream Reader to compose the data into characters. 2

(iv) The Buffered Reader then takes the characters and composes them into text. you need to “import” them. System.println(keyboard.readLine( )).io.In)). (a) Java.*.lang. BReader. import java.IO has ISR.out. class SimpleIO{ public static void main(string[]args)ThrowsException{ BufferedReader keyboard = new Buffered Reader( new InputStreamReader(System. other than java. } } (4) To use the Java libraries. (5) A Java program always begins with a method called “main” 3 .

// same as this.name.name = name. this. // “( )” show it‟s a method kayla.age. public String name.out. name = original. iii) Aka instance variables.println(numberOfHumans). // same as this.age = age. } public static void printHumans( ){ System. public void introduce( ){ System. public static int numberOfHumans.”). } } 4 .age = 12 name = givenName. this.println(“I‟m” + name + “and I‟m” + age + “years old.3) Lecture 3 – Defining Classes a) Fields: i) Variables stored in objects ii) Used to store data. } // Constructor public Human(String given Name){ age = 12.age. } public void copy(Human original){ age = original.introduce( ). // lack of “( )” shows it‟s a field class Human{ public int age.out. kayla.name = givenName } public void change(int age){ String name = “Chang”.

(2) also called class variables.change(8). THERE IS NOT “this”!// Compile error e) Lifetimes of variables i) A local variable is gone when method ends. // kayla is the parameter this so we change this with Chang age 8 kayla this Chang age 8 name kayla name ii) You Cannot change the value of “this”! // Compile error d) The “static” keyword i) Static field: (1) a single variable shared by a whole class of objects. // Create a variable kayla and a human object for it to reference. ii) Static Method: (1) Doesn‟t implicitly take an object as a parameter. kayla. Human kayla = new Human( ).name = “kayla”. // implicitly passes an object ( kayla as a parameter called “this”.age = 12. main( ) is always static (2) In a static method . kayla. c) The “this” keyword i) Whenever you do a method invocation. kayla. kayla.introduce( ).Each Human object can have different values of age & name. Java implicitly passes a hidden parameter of the object the method is on. age kayla name 12 “kayla” String Object b) Constructors i) Creates an object and allows you to initialize the fields ii) Constructors always returns a object of the class and always has the name of the class. 5 .

// Okay vi) Boolean Values A false false true true B false true false true A&&B false false false true A||B !A false true true false true true Primitive Types value built into Java “6”. ii) Boolean Types: (1) “true” or “false” iii) Character Types: (1) char – A single character iv) Table Object vs. // Compile error (cannot be sure same bits) i = (int) l .greater than or equal to (e) <+ . float f = (float) d. long l = 43L.less than (d) >= . “3.4”.7.greater than (c) < .not equal 6 .less than or equal to (f) != . Primitive Types Object Types Contains a reference How defined? class definition How create? “new” How initialized? constructor How used? methods v) Integers can be assigned to variables of longer typs int i = 43. //Okay after int cast double d = 23. etc) (1) Created by comparison operators (a) “==” .“*”.4) Lecture 4 – Types and Conditionals a) Primitive Types i) Number types (1) byte: 8 – bit integer -128…127 (2) short: 16 – bit integer -32768…32767 (3) int: 32 – bit integer -2147483648…2147483647 (4) long: 64 – bit integer (5) double: 64 – bit floating point number (6) float: 32-bit floating point numbers ** double and float values must have a decimal point. “true” default (usually zero) operators(“+”. // Okay after cast d = f.equality (b) > . l = i . // Okay i = l.

break‟ default: days = 31. boolean switch(month){ case 2: days = 28. // breaks jump to the end of the “switch” statement case 4: case 6: case 9: case 11: days = 30. } ix) The “return” keyword (1) “return” causes a method to end immediately (2) Control returns to the calling method (3) return is means by which a function returns a value x) Function (1) A method declared to return a non-void type. } viii) “switch” statements (1) If you have one variable with different results for each value Int. break. 7 . char. break.vii) Conditionals if( bool Value){ statements.

} divisor ++. } 8 . it will iterate the body then test the loop condition and repeat the process until the loop condition is false. } (2) When the loop condition is false the body won‟t iterate. while(divisor < n){ if( n%divisor == 0) { return false. } (b) initialize. } public static boolean isPrime(int n){ “loop condition” for(int divisor = 2. while(test){ statements.5) Lecture 5 – Iteration and Arrays 1 a) Loops i) “while” Loops (1) A while loop method that tests whether an integer is a prime number public static boolean isPrime(int n){ int divisor = 2. next){ statements. } } return true. divisor ++){ if ( n%divisory ==0){ return false. “loop condition” ii) “for” Loops (1) Equivalent: (a) for(initialize. divisor < n. test. next. if it is true. } return true.

9 . c[ 4 ] = „s‟.length = 7. c[ 2 ] = „u‟. // array of different objects field “c. c[ 1 ] = „l‟. Each is a primitive type of reference. // c is an array of length 4 c[ 0 ] = „b‟.length” – length of array c. Runtime ERROR Object o = new Object[ ]. c[ 3 ] = „e‟. 0 1 2 3 b l u e c char[ ] c. // Compile – Time error iv) Multi-Dimensional arrays (1) two-dimensional array: an array of references to arrays.iii) Arrays (1) An array is an object of a numbered list of variables. // Reference to array (any length of characters) c= new char[ 4 ].

5. c[ ][ ]. c) “do” loops i) “do” loop always executes loop body at least once do{ s = keybd. b. // Compile time ERROR int[ ] a. b.6) Lecture 6 – Iteration and Arrays 2 a) Automatic Array Construction int [ ][ ] table = new int [ x ] [ y ] „ //Creates an array of x references to arrays x arrays of y ints table Initializers: Human[ ] b = {kayla.7}. C is 2 D int [ ] a.readLine( ). new Human(“Paolo”)}.{y+2. b not array. d = {3. b [ ]. rishi. // a is 1D . c.{8.3}}.length( )>0). Java does not create the objects. }while(s. process(s).0}. ii) What “do” loop does enter read exit process d) The “break” and “continue” statements i) The “break” statement always exists the inner most “switch or loop enclosing the “break” ii) “continue” (1) Only applies to loops (2) Doesn‟t exit loop Another iteration may commence (if condition of while/do/for is satisfied) 10 .2}.0. b is 2D b) Array of objects i) When you create an array of objects.{x}. 2d Array initialized: int [ ][ ] c = {{7. // a is 1D.3. // all reference arrays int a[ ].

case 4 continue. // breaks to statement4( ). case 2 break loop. default: continue loop. // breaks to statement5( ). } statement 5( ). // breaks to statement2( ). // jumps to location 3 // jumps to location 3 “final” keyword (1) value that can never be changed For any arry x. // compile-time error 11 . case 1 break stuff. //location 3 } statement 4( ).e) Labeled statements test: // lebele “if” statement if ( x==0){ loop: while(i<a){ stuff: { } statement 2 ( ).length” is a “final” field. case 3 break test. // breaks to statement 1( ). i++. f) Constants i) switch(z[ i ]){ case 0 break. “x. } statement 1( ).

l3 2.insertAfter(i). } ListNode l1 = new ListNode(). l1 item 7 l2 2 next l1.item = 7. } 3. ii) Moreover.insertAfter(3). item 3 next 1.next = l3. ListNode l3 = new ListNode(). // other constructor } item 0 next 3. d) Method to instert a new item after “this”.next = l2. ii) Each node stores two things (1) an item (2) a reference to next node in the list public class ListNode{ int item.item = 6. a item 6 next //to do as often as you want for(…){ l2. new value of next . old value of next public void insertAfter(int item){ next = new ListNode(item. new ListNode(0. 1. list can keep growing until memory runs out. l1. l3.7) Lecture 7 – Linked Lists 1 a) Lists i) Store a list of ints as an array. c) Advantages over array lists: i) Inserting item in the middle of linked list takes constant time if you have regerence to previous node. (2) Arrays have a fixed length.item = 0. // Using List Node before defining it. } 12 .next. b) Linked Lists (a recursive data type) i) Made up of data structures called “nodes”.null). l3. next l2. next). new ListNode(6))). //Node Operations … constructers public ListNode(int item){ this(item. l2. l1 item 7 l2 item 0 next l3 item 6 next } ListNode l1 = new ListNode(7. ii) Disadvantages (1) Inster item at the beginning or middle Time to go through array proportional to array length. l2. ListNode l2 = new ListNode().next = null. l2 = l2. ListNode next.

size++. public SListNode next. of type Object public class SListNode{ //S is for single linked list public Object item. public SList( ){ //empty list constructor public void insertFront(Object Item){ head = new SList(item. x and y can update x = new SListNode(“soap”. }} new item 13 y x SList size 1 head SListNode item next milk y x y x milk milk . } else if ((position c1)||(next==null)){ return null. (2) How do you represent an empty list? (a) x = null.e) Disadvantages: i) Finding the nth item of a linked list takes time proportional to n  length of list. } } f) List of Objects i) Reference any object by declaring a ref. ] g) A List Class i) 2 proplems with SListNodes (1) If x and y share a list. // first object in list private int size. head). x). // x Run-time error if you call a method on a null object (b) Solution: public class SList{ soap private SListNode head.nth(position-1). } else { return next. (Constant – Time on array lists.) // find the nth item in a linked list public ListNode nth(int position){ if(position == 1){ return this.

DListNode next.prev. size--. iii) Interface of a class: prototypes for public methods. (1) Not all classes are ADT! Some classes just store data. (2) You can improve the implementation without causing other classes to fail.next. 2. (2) Both goals are accomplished because only SList methods can change the lists (a) The fields of SList (head and size) are “private” (b) No method of SList returns on SlistNode. 1. } } DList head tail item 4 prev next next item 1 prev next item 8 prev (3) Insert and delete items at both ends in constant running time. vii) Doubly – Linked Lists (1) Inserting/deleting at front of list is easy public void deleteFront( ){ if(head!=null){ head = head. (4) Removes the tail node( at least 2 items in DList): tail. item 8 prev next 14 . iv) Abstract Data Type (ADT):a class with a well-defined interface. (a) “size” is always correct (b) list is never circularly linked. ii) Why? (1) To prevent data from being corrupted by other classes. v) Invariant: a fact about a data structure that is always true. private DListNode head. vi) The SList ADT (1) Another advantage of SList class: SList ADT enforces 2 invariants. DListNode prev.8) Lecture 8 – Linked Lists 2 a) The “public” and “private” keywords i) A private method or field is invisible and inaccessible to other classes.next =null. 2.prev. moves tail pointer to new tail head tail item 4 prev next next item 1 prev 1. plus descriptions of their behaviors. deletes pointer to tail tail = tail. private DListNode tail. but implementation details are hidden from other classes. } } (2) Inserting/deleting at the end of the list takes a long time class DListNode{ class DList{ Object item.

private int size. d. DListNode next. } DListNode Sentinal item prev next } DList head 3 size class DList{ private DListNode head. (e) For any DListNode x.next!=null. x.head!=null.next == x.prev!=null (d) For any DListNode x. then y. item 4 prev item 1 prev item 8 prev next next next (2) DList invariants with sentinel: (a) For any DList d. (f) A DList‟s “size” variable is # variable is # of DListNodes not counting Sentinel (g) Empty DList: sentinel‟s prev & next field point to itself 15 . if x. (1) DList version 2: circularly linked class DListNode{ Object item. DListNode prev. x.prev == y. if x.prev == x. then y. (b) For any DListNode x.next == y.viii) Sentinel: A special node that does not represent an item. (c) For any DListNode x.

} 6 7 doNothing is destroyed: public int i.SListNode this obj obj SList. ib 2 set3(b). ii) The Stack stores all local variables. // 10 badSet4 is being destroyed leaving the new i object stranded i 8 4 5 1 9 IntBox i 3 16 . is copied. and class variables. } static void badSet4( IntBox ib){ 7 badSet4( ) 7 8 ib = new IntBox(4). ib 6 9 ib. vi) Method: Thread. its stackframe is erased. 2 } 4 1 IntBox b = new IntBox( ). 4 2 7 doNothing( ) x 1 2 a 1 5 6 a doesn‟t change static void set3( IntBox ib){ 10 5 ib. iv) The JVM maintains an entire stack of stackframes Stack Heap mehod name local variables SListNode. // in Java Lang (1) Prints out a list in order of all the stack frames on the stack at that moment. the ref. b) Paramter Passing i) All parameters are passed by value--. Java creates a stackframe(aka activation record) that stores the parameter & local variables. 1 int a = 1. including arrays.InsertEnd this str SList.copied. ii) When a parameter is a reference. 4 ib equal b b 6 //set3 is destroyed 7 badSet4(b).9) Lecture 9 – Stack Frames a) The Stack and the Heap i) The Heap stores all of the objects. but not the thing it points to in some method class IntBox{ static void doNothing( int x) 4 5 x=2.i = 3. including parameters iii) When a method is called.i = 4. 3 doNothing(a).main list args head words Input size milk item next v) When a method finishes.dumpstack( ).

looking for 1.except when shadowed by variables. drop the right 1 3. int left. } int mid = (left + right)/2. private static int bsearch (int [ ] i. e) Scope & Recursion i) Scope of a variable is the partion of the program that can access the variable (1) Class Variables: in scope everywhere in the class. right. findMe). otherwise. (3) Instance variables: inscope in non-static methods of the class. 0<1 so cut at 0. 17 . } } iv) How fast? It takes recursive b search calls.out”) in scope everywhere in the class. found 1 d) Recursion base cases: i) findMe = middle element: return its index ii) Subarray of length zero: return Failure iii) Example public static final int FAILURE = -1. (2) Fully Qualified Class Variable (“System. mid -1. only for top most stack frame. -3 -2 0 0 1 5 5 1. except when shadowed. and cannot be shadowed. “this. return its array index. v) Method bsearch local variables bsearch left 4 mid 4 left 4 mid 5 right 4 findMe 1 i right 6 findMe 1 i bsearch bsearch bsearch main left 0 findMe 1 right 6 mid 3 i findMe 1 args i ? -3 -2 0 0 1 5 5 0 1 2 3 4 5 6 vi) Most Operating Systems give enough stack space for a few thousands of stack frames (1) works on Arrays but NOT Linked Lists. 5>1 so cut at 5. findMe). return failure Array. int right. (4) Fully Qualified instance variables (“kayla-name”. left. mid+1.item”) (5) Local variables & parameters: only in scope in the method that defines them. (for a value “find me”) (1) If we find “find me”. } else{ return bsearch(i. If public. drop the left 1 5 5 2. int findMe){ if(left > right){ return FAILURE. they‟re in scope in all classes. if( findMe == i[mid]){ return mid.c) Binary Search i) Search a sorted array. } else if(findMe < i[mid]){ return bsearch(i.

} n1 = n1.g. while (n1 != null){ if(n1. SListNode n2 = other. s2 == s3. ii) Default: r1.equals(n2 item)){ return false.next. True b) 4 degrees of equality: i) Reference equality. s2. fields are equals( ).head. } SListNode n1 = head.next. } } d) Testing i) Modular Testing (1) Testing drivers & Stubs (a) Test drivers call the cod. check the results (i) usually put in main( ) (ii) If class is entry point for program 18 . fields are ==. == ii) Shallow Structural equality.equals(s3).10) Lecture 10 – Testing a) equals( ) method i) Every class has an equals( ) method. String s1 Yes s2 Yes s3 s1 == s2 // False s1. n2 = n2. e. iv) Logical equality (1) Fractions 1/3 and 2/6 are “equals” (2) “set” objects are equals if they contain same elements (even stored in different orders) c) SLists “Shallow structural” SList head SList head 3 SList head SList head 3 4 4 public class SList{ public boolean equals (SList other){ if (size!=other.equals(r2) // same as r1 == r2 iii) Many classes define equals( ) to compare content.item. } return true.equals(s2).size){ return false. iii) Deep Structural equality.

){ MyProgram. i) assert( x==3).public class MyProgram{ public static void testDriver( ){…} } public class TestMyProgram{ …………. (2) Algorithm result checker Sorting Algorithm check that each # is <=to its successor in the list. } } (2) Stubs. bits of code called by the code being tested. (a) reasons for stubs (i) Fills in for missing method not yet implemented (ii) Determine whether bug lies in calling method or callee by replacing callee with stub. (2) LEARN TO USE THE DEBUGGER iii) Result Verification (1) Data Structure integrity checkers. f) 19 . Inspects data structure and verifies that all invariants are satisfied.main(…. Produces repeatable test data. iii) Turn them on: “java – ea” code is tested iv) Turn them off: “java-da” code is fast Regression Testing i) Regression test is a test suite that can be re-run whenever changes are made to the code. (iii) Produce test data that real subroutines rarely or never produce.TestDriver( ). 1. ii) Integration Testing (1) Define interfaces well! No ambiguity in descriptions or behaviors of methods.countLength( )). “wrong sList size: “ + list.size..size == list.//Prints only if assertion fails. e) Assertion: Code that test an invariant or result.// If x==3 nothing happens. but if x!=3 then throws an error ii) assert(list.

insertFront(obj). } c) Invoke Overidden Methods i) The “protected” keyword public class SList{ protected SListNode head. } } } i) TailList is a subclass of SList ii) SList is the super class of Tail List. public void insertEnd(Object obj){ …. .. iii) A subclass can modify a superclass in 3 ways (1) It can declare new fields (2) It can declare methods (3) It can override old methods with new implementations. (2) “private” fields aren‟t visible to subclasses 20 . **isEmpty( ).// This overrides the insertEnd(Object object) } public void insertFront(Object obj){ super. zero-parameter constructor called by default } To change: public TailList(int x){ super(x). protected int size.// does not have to be first statement If(size == 1){ tail = head.// MUST be first statement in constructor tail = null. head = null Tail = null. . . toString( ) are inherited from SList b) Inheritance & Constructors i) Java exevutes a Tail List constructor. length( ). but first it excutes SList( )constructor public TailList( ){ //SList( ) sets size = 0. nth( ).11) Lecture 11 – Inheritance a) Inheritance public class TailList extends SList{ /*head and size are inherited from SList*/ private SListNode tail. } (1) “protected” field/method is visible to declaring class & all its subclasses.

Now TailLists are sorted as well.M. iv) Dynamic method look-up: (1) When we invoke an over-ridden method. regardless static type. MATTERS i) Method that sorts an SList using only method calls. Java calls method for the object‟s of dynamic type. f) WHY D.d) Class Hierarchies Object String Worker Proletariat Bourgeoisie Student TA Professor e) Dynamic Method Lookup i) Every TailList is a SList ii) Static type: the type of variable iii) Dynamic type: the class of the object the variables references. 21 .L.

nth(1). the rules are more complicated when you assign from one variable to another rather than creating an object. // works just fine SList s = new TailList( ). } b) Abstract Classes i) A class whose sole purpose is to be extended. SList s. } // cannot creat a List Object. //works fine String z = t. ii) You can‟t assign an SList object to a tailList variable. //Comile-Time ERROR Why? Not every SList object has an “eatList( )” method. // this is fine myList = newList( ). TailList t = new TailList( ).intValue( ). public int length( ){ return size. TailList t = new TailList( ). you can declare variables whose static type is List List myList. t. t = (TailList) s.nth(1)).eatList( ).nth(1). s = t. not the original variable.eatList( ). int x = t.toString( ). ** Java can‟t use dynamic method lookup on S. // if you cast s as a TailList it corrects the CT error s = new SList( ). // Compile-Time Error 22 .intValue( ). // Run-Time Error **Casts change only the Static type of an expression.12) Lecture 12 – Abstract Classes a) Subtleties of Inheritance i) Now suppose we have a new method in the TailList class called eatList( ). // Compile-Time Error t = (TailList) s. // nth returns an Object and intValue( ) is defined on only ints so Compile-Time error int y = ( (Integer)t. // works fine iv) “instanceof” operator tells you whether object is of specific class if( s instanceof TailList){ // s instanceof TailList is false if s is null or doesn‟t reference a TailList or subclass t = (TailList) s. // every SList is a tailList so this compiles fine t = s. } public abstract void insertFront(Object item). public abstract class List{ // This is an Abstract Data Type protected int size. s. iii) Sometimes you can use these casts directly in a line of code.

public class SList extends List{ // inherits “size” // inherits “length( )” public void insertFront( Object item){ // We have to supply an implementation of insertFront because there head = new SListNode(item. 2 differences (1) A class can inherit from only one class. head). Application calls List Sorter calls List ADT c) Java Interfaces i) “interfaces” = public method prototype & behaviors ii) “Java interfaces” = “interface” keyword iii) Java interface is like abstract class. 23 . but can “implement”(inherit from) as many Java interfaces as you like. (2) TransactionList: logs all changes on a disk for a power outage. then one list sorter sticks to the interface and just uses the official behaviors of the interface can sort every kind of List. // is not an implementation but theres a prototype size++. (i) Only contains method prototypes & constants. // ** The reason you would want an abstract method here is that you can call insertFront regardless the list type iv) If you implement a list sorter or any other algorithm that uses lists.insertFront(obj). (b) include any fields except “static final” constants. } iii) A non-abstract class may never (1) contain an abstract method. not the list sorter. chooses what kind of list is used. DList. (2) inherit one without providing an implementation List myList = new SList( ). (2) A Java interface cannot (a) implement any methods.ii) Abstract methods lack an implementation. (ii) sdf The application. public void listSort(List l) { … } v) Subclasses or List: SList. // SList is a subclass of List and SList is not abstract so this works myList. (1) TimedList: records time spent doing operations. TailList.

& subpackages. public void nuke( ){ head = null.java public void nuke( ). // returns a number < 0 if this comes before o in your ordering = 0 if this.Frame & photo. and a sub-interface can has multiple sub-interfaces. you can assign it to variables of these types. You just have to provide the compareTo method and java‟s library does the rest of the work. (3) Different packages can have classes with same name.Frame // you can use both iii) example: (1) java.util that sorts arrays of Comparable objects. Comparable { } b) Java Packages i) Package: a collection of classes that go together.compareTo(c2) > 0){…} v) An example of one of Java‟s sorting libraries (1) There is an Arrays class in java. // The reason for the cast is because not every nukeable is a comparable.equals(o) >0 if this comes after o in your odering // We use a boolean because there are three different possibilities so a boolean will not do. but every object in the array has to be a comparable object. Nukeable n = new SList( ).awt.13) Lecture 13 – Java Packages a) Interfaces cont. if(c. public static void sort(Object[ ] a){ //You can pass any array of objects. (2) Classes can have fields & methods visible inside the package only. Comparable c = (Comparable) n. } ii) Examples public interface Comparable { // in java.. public interface NukeAndCompare extends Nukeable . Comparable{ .io standard library 24 . } iii) If we want to have a class that inplements interfaces.nuke( ). // Run-Time error occurs if any item in a is not comparable vi) Interfaces can have sub-interfaces. } } iv) Because an SList is a nukeable and a comparable. } public int compareTo(Object o){ . i) Suppose we declare an interface called Nukeable. size = 0. . (a) java. ii) 3 benefits of packages: (1) Packages can contain hidden classes not visible outside package. public class SList extends List implements Nukeable. public interface Nukeable { // in Nukeable. you can include Java interfaces.lang public in compareTo(Object o). n.

println(“blah”). // Can now refer to File (3) import java.class d) Building Packages i) If you want to build an abstract data type that needs more than one class.* iii) What if you do import a file and get a name clash.io ii) Every program implicitly imports java.awt. In the same package In a subclass Declaration \ Visible “public” yes yes “protected” yes yes package yes no “private” no no Everywhere yes no no no 25 .canvas). (2) import java.lang. ii) Package protection is between private and protected.private.System. (1) java. unless their a subclass in there.y. public classSList{ SListNode head. // that‟s how you can tell the two different types of frames apart. } The class and fields have package protection. list/SList.lang.io.Frame.out.add(photo.Frame. SListNode next.Class in x/y/z/Class. field . or method with a fully qualified name anytime you want to (1) Fully qualified name: (a) java. etc) then package protection is the default. vi) “package” classes can go in any *java file e) Compiling & running must be done from outside the package.io. more protection than protected but less than private. then you want to build your own package. int size.*.c) Using Packages i) You can address any class. // Can now refer to everything in java.z. class SListNode{ Object item.File.java package list. v) Public class must be declared in file named after class. iii) A class/variable with package protection is visible to any class in same package.java package list. if you leave out the keyword (public. not visible outside the package (not visible to any files ouside the directory) iv) Files outside only see public classes/methods/fields.class (2) If you have a class called x. } list/SListNode. // if you have a written a class called Frame in the photo package then you actually have to find that file in a directory called photo and in that directory there has to be a file called Frame.

You do not have to return anything. (i) You can catch exception.solution”). “Matches” means that the actual exception object that got thrown is in the same class or sub-class of the static type of the catch clause. code – Jump to first “catch” clause that matches exception.] 26 . (2) Escaping a Sinking Ship (a) Throw your own exception. i = f. iii) You can prevent the error by “catching” the Exception iv) Purpose of using Catch Clauses: (1) Surviving errors (a) Example: Try to open a file that doesn‟t exist. 3) If “try” code throws exception. (iii) Only the first matching “catch” is executed. An exception can fly many methods down the stack. } (ii) How is a Throw Statement different from a return statement? 1. } … } return parseTree. 2. Exception } Object catch(IOException e2){ called “exception handlers” f.read( ). */ (ii) Jumps to code after all catch clauses. variable } catch( FileNotFoundException e1){ e1 whine(“Foiled!!”). do not finish “try”.close( ). 2) If “try” code executes normally. print error message. public class ParserException extends Exception{…} 1. } //one of the purposes of catch clauses are to close files /*This code: 1)Executes the code inside “try”. and continue try{ f = new FileInputStream(“~cs61b/pj2. skip “catch” clauses. (i) This allows you to “pile” your way to the top of the stack. public ParseTree parseExpression( ) throws ParserExpretion{ [ loops ] if (somethingWrong){ throw new ParserExcetion( ).14) Lecture 14 – Exceptions a) Exceptions i) Run-time error: Java “throws an exception” ii) An exception in Java is an object. execute that catch clause. The point of this ParserException is to be distinguishable from other types of Exceptions.

[…. 2 choices: (1) It can catch the exception. Try{ p = parse( ).public ParseTree parse( ) throws ParserException DumbCodeException{ [ loops & code ] p = parseExpression( ).toByteCode( ). 27 . } catch(ParserException e1){…} } Stack parseExpression parseExpression parse compile (iii) By doing a throw. a compiler still has control while an error is handeled by the b) Checked & Unchecked Exceptions i) All exceptions are a subclass of Throwable ii) Throwable has two subclasses: (1) Exceptions (2) Errors : running out of memory or stack space iii) Exception Types (1) RunTimeExceptions (a) NullPointer (b) ArrayIndex (c) … (2) ParserException iv) RunTimeException and Error unchecked. p.] } } public void compile( ){ ParseTree p.. they do not need a “Throws” declaration needed. (2) “throws” the same exception itself. v) When method calls method that “throws” a checked exception.

// the static type of supe is Super so i = 2 i = sub. return 1. the “finally” clause will be executed at the end. i = supe.x Super. } public MyException(String s) { super(s). }catch(someException e){ e. no matter what. ii) Different from overriding. f.f( ) void g( ) { int i.x supe int i.x. } Sub sub = new Sub( ). inf f( ) {return 2. Fields can be “shadowed” in subclasses. iv) An Exception thrown in the “finally” clause: new exception replaces old. class Super { int x = 2. return 2. Rule: If “try” statement begins.x. } finally { //A finally clause is composed of statements you want to happen no matter what happens above. return 3. then “finally” clause. } } (1) Error Message: (a) Printed if exception propagates out of main( ) (b) Read by Thowable.close( ). } } class Sub extends Super{ int x = 4. try{ statementX.getMessage( ). // the static type of supe is Super so i = 2 i = ((Sub)supe). d) Field Shadowing i) When you do inheritace.// Java took a snapshot of the stack when the exception was thrown. sub Sub.} //overrides Super. i = this.x int f( ) {return 4.x.) (1) Choice of fields is dictated by the static type.15) Lecture 15 – More Java a) The “finally” keyword i) A finally clause is something that can be part of a try clause.x.( overriding works by making the choice of methods dictated by the dynamic type.printStackTrace( ). b) Several things can happen: i) StatementX causes SomeException  “catch” clause executes. //shadows Super. Super supe = sub. ii) StatementX causes other Exception  “finally clause executes. // the static type of sub is Sub so i = 4 i = ((Supe)sub). so “finally” still executed first. // the static type of sub is Sub so i = 4 28 . method ends immediately c) Exception constructors i) Convention: most Throwables have 2 constructors class MyException extends Exception{ public MyException( ){ super( ). }// This piece of code ALWAYS returns 3. iii) An Exception thrown in “catch”clause: as usual. then the exception continues down the stack.x.

f) Simplified “for” int[ ] array = { 7. but when you call a static method there is no way to use dynamic method lookup because there is nothing to look up. for (int i : array){ System. Because when you call a normal method that‟s not static.iii) Shadowing is a nuisance but when your building very large software libraries. you call it so you can do dynamic method lookup on the method to find out what class it is. } // NOT iterating from 0 to 5. 8. iv) Static methods: same shadowing rules as fields. 9 }.out. taking on each array element in turn // this method prints 7 12 3 8 4 9 for( String s : stringArray){…} 29 .print( i + “ “). 12. ii) A “final” class  cannot be extended. 4. sometimes you can‟t help but use the same name in different places. e) “final” Methods and Classes i) A “final” method  cannot be overridden. iii) Compile-Time error if you try. 3.