![Page 1: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/1.jpg)
CS221Week 1 - Friday
![Page 2: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/2.jpg)
Last time
What did we talk about last time? Basic programming model Other Java stuff
References Static Inner classes Exceptions
![Page 3: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/3.jpg)
Questions?
![Page 4: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/4.jpg)
Exceptions
![Page 5: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/5.jpg)
Exceptions
Java handles errors with exceptions Code that goes wrong throws an
exception The exception propagates back up
through the call stack until it is caught
If the exception is never caught, it crashes the thread it's running on, often crashing the program
![Page 6: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/6.jpg)
Kinds of exceptions
There are two kinds of exceptions: Checked Unchecked
Checked exceptions can only be thrown if the throwing code is: Surrounded by a try block with a catch block
matching the kind of exception, or Inside a method that is marked with the keyword throws as throwing the exception in question
Unchecked exceptions can be thrown at any time (and usually indicate unrecoverable runtime errors)
![Page 7: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/7.jpg)
Examples of exceptions
Checked exceptions FileNotFoundException IOException InterruptedException Any exception you write that extends Exception
Unchecked exceptions ArrayIndexOutOfBoundsException NullPointerException ArithmeticException Any exception you write that extends Error or RuntimeException
![Page 8: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/8.jpg)
Exceptions in code
Scanner in = null;try {in = new Scanner( file );while( in.hasNextInt() )
process( in.nextInt() );}catch( FileNotFoundException e ) {
System.out.println ("File " + file.getName () + " not
found !");}finally { if( in != null ) in.close (); }
![Page 9: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/9.jpg)
Threads
![Page 10: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/10.jpg)
Threads
In Java, concurrency and parallelism are achieved primarily through threads
A thread is a path of code execution that runs independently of others But threads can share memory with each
other Some other languages use message
passing semantics and no direct memory sharing
![Page 11: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/11.jpg)
Creating threads in Java
To create a customized thread in Java, there are two routes: Create a class which is a subclass of Thread
Create a class which implements the Runnable interface
If you subclass Thread, you can't subclass some other object
If you implement Runnable, there's an extra bit of syntax to create a new thread
![Page 12: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/12.jpg)
Sample thread to sum things
public class Summer extends Thread {private double[] array;private int start;private int end;private double result = 0.0;
public Summer(double[] array,int start, int end) {this.array = array;this.start = start;this.end = end;}
public void run() {for( int i = start; i < end; i++ )result += array[i];}
public double getResult() { return result; }}
![Page 13: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/13.jpg)
Using Summer
public double findSum( double[] array, int threads )throws InterruptedException {Summer[] summers = new Summer[threads];double result = 0.0;int step = array.length / threads;if( array.length % threads > 0 ) step++;
for( int i = 0; i < threads; i++ ) {summers[i] = new Summer(array, i*step,
Math.min((i+1)*step, array.length));summers[i].start();
}
for( int i = 0; i < threads; i++ ) {summers[i].join();result += summers[i].getResult();
}
return result;}
![Page 14: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/14.jpg)
Tips for concurrency
Keep it simple Do not share data via static
variables Be careful with load balancing
If the work is not evenly divisible by n (the number of threads), give the first n – 1 threads one extra piece of work
Why? Be aware that threading out a
program will not necessarily make it faster
![Page 15: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/15.jpg)
OOP
![Page 16: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/16.jpg)
What is an object?
Members Methods Why are they useful?
Monolitihic main() function
• Code and data together
Work divided
into functions
• Code separated, but data shared
Objects
• Code and data separated
![Page 17: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/17.jpg)
What is a class?
A template or prototype for an object
Class: Human
Object: David Bowie
Object: Barack Obama
Class: Company
Object: Microsoft
Object: Boeing
![Page 18: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/18.jpg)
Object Oriented Programming
Encapsulation Dynamic dispatch Polymorphism Inheritance Self-reference
![Page 19: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/19.jpg)
Encapsulation
Information hiding We want to bind operations and data tightly
together Consequently, we don't want you to touch
our privates Encapsulation in Java is provided by the private and protected keywords (and also by default, package level access)
Hardcore OOP people think that all data should be private and most methods should be public
![Page 20: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/20.jpg)
Encapsulation example
public class A{private int a;
public int getA(){
return a;}
public void setA(int value){
a = value;}
}
![Page 21: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/21.jpg)
Inheritance
Allows code reuse Is thought of as an is-a relationship Java does not allow multiple
inheritance, but some languages do Deriving a subclass usually means
creating a "refined" or "more specific" version of a superclass
![Page 22: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/22.jpg)
Inheritance example
public class B extends A{ //has member and methods from A}
public class C extends A{//has A stuff and moreprivate int c;public int getC(){ return c; }void increment() { c++; }
}
![Page 23: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/23.jpg)
Polymorphism
A confusing word whose underlying concept many programmers misunderstand
Polymorphism is when code is designed for a superclass but can be used with a subclass
If BMW235i is a subtype of Car, then you can use an BMW235i anywhere you could use a Car
![Page 24: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/24.jpg)
Polymorphism example
//defined somewherepublic void drive( Car car ){…}
public class BMW235i extends Car{…}
Car car = new Car();BMW235i bimmer = new BMW235i();drive( bimmer ); //okaydrive( car ); //okay
![Page 25: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/25.jpg)
Dynamic dispatch
Polymorphism can be used to extend the functionality of an existing method using dynamic dispatch
In dynamic dispatch, the method that is actually called is not known until run time
![Page 26: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/26.jpg)
Dynamic dispatch example
public class A {public void print() { System.out.println("A");}
}
public class B extends A {public void print() { System.out.println("B");}
}
![Page 27: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/27.jpg)
Dynamic dispatch example
A a = new A();B b = new B(); // B extends AA c;
a.print(); // Ab.print(); // B
c = a;c.print(); // Ac = b;c.print(); // B
![Page 28: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/28.jpg)
Self-reference
Objects are able to refer to themselves
This can be used to explicitly reference variables in the class
Or, it can be used to provide the object itself as an argument to other methods
![Page 29: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/29.jpg)
Self reference example
public class Stuff{private int things;
public void setThings(int things){
this.things = things;}
}
![Page 30: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/30.jpg)
Self reference example
public class SelfAdder{public void addToList(List list){
list.add(this);}
}
![Page 31: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/31.jpg)
Constructor syntax
Java provides syntax that allows you to call another constructor from the current class or specify which superclass constructor you want to call
The first line of a constructor is a call to the superclass constructor
If neither a this() or a super() constructor are the first line, an implicit default super() constructor is called
![Page 32: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/32.jpg)
Constructor example
public class A {private double half;public A(int value) {
half = value / 2.0;}
}
public class B extends A {public B(int input) {
super(input); // calls super constructor}
public B() {this(5); // calls other constructor
}}
![Page 33: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/33.jpg)
Interfaces
![Page 34: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/34.jpg)
Interface basics
An interface is a set of methods which a class must have
Implementing an interface means making a promise to define each of the listed methods
It can do what it wants inside the body of each method, but it must have them to compile
Unlike superclasses, a class can implement as many interfaces as it wants
![Page 35: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/35.jpg)
Interface definition
An interface looks a lot like a class, but all its methods are empty
Interfaces have no members except for (static final) constants
public interface Guitarist {void strumChord(Chord chord);void playMelody(Melody notes);
}
![Page 36: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/36.jpg)
Interface use
public class RockGuitarist extends RockMusician implements Guitarist {
public void strumChord( Chord chord ) {System.out.print("Totally wails on that " +chord.getName() + " chord!");
}
public void playMelody( Melody notes ) {System.out.print("Burns through the notes " +notes.toString() +" like Jimmy Page!" );
}}
![Page 37: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/37.jpg)
Usefulness
A class has an is-a relationship with interfaces it implements, just like a superclass it extends
Code that specifies a particular interface can use any class that implements it
public static void perform(Guitarist guitarist, Chord chord, Melody notes) {
System.out.println("Give it up " + "for the next guitarist!");
guitarist.strumChord( chord );guitarist.playMelody( notes );
}
![Page 38: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/38.jpg)
Generics
![Page 39: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/39.jpg)
Generics
Allow classes, interfaces, and methods to be written with a generic type parameter, then bound later
Java does the type checking (e.g. making sure that you only put String objects into a List<String>)
After typechecking, it erases the generic type parameter This works because all classes extend Object in Java
Appears to function like templates in C++, but works very differently under the covers
Most of the time you will use generics, not create them
![Page 40: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/40.jpg)
Generic classes
You can make a class using generics The most common use for these is
for container classes e.g. you want a List class that can be a
list of anything JCF is filled with such generics
![Page 41: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/41.jpg)
Generic class examplepublic class Pair<T> {
private T x;private T y;public Pair(T a, T b ) {
x = a;y = b;
}
public T getX() { return x; }
public T getY() { return y; }
public void swap() {T temp = x;x = y;y = temp;
}
public String toString() {return "( " + x + ", " + y + " )";
}}
![Page 42: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/42.jpg)
Generic class use
public class Test {public static void main(String[] args) {
Pair<String> pair1 = new Pair<String>("ham", "eggs");
Pair<Integer> pair2 =new Pair<Integer>( 5, 7 );
pair1.swap();System.out.println( pair1 );System.out.println( pair2 );
}}
![Page 43: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/43.jpg)
JCFJava Collections Framework
![Page 44: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/44.jpg)
Container interfaces
CollectionIterableListQueueSet
SortedSetMap
SortedMap
![Page 45: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/45.jpg)
Container classes
LinkedListArrayListStackVectorHashSetTreeSetHashMapTreeMap
![Page 46: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/46.jpg)
Tools
Collections sort() max() min() replaceAll() reverse()
Arrays binarySearch() sort()
![Page 47: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/47.jpg)
Upcoming
![Page 48: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/48.jpg)
Next time…
Computational complexity Read section 1.4
![Page 49: Week 1 - Friday. What did we talk about last time? Basic programming model Other Java stuff References Static Inner classes Exceptions](https://reader035.vdocuments.mx/reader035/viewer/2022070410/56649ea45503460f94ba8c39/html5/thumbnails/49.jpg)
Reminders
Read section 1.4 Work on Assignment 1
Due next Friday by 11:59pm Start on Project 1