algorithms and data structuresenos.itcollege.ee/~jpoial/algorithms/ads_intro.pdfschedule tue 16:00...

57
Algorithms and Data Structures 5 ECTS Exam Jaanus Pöial, PhD http://enos.itcollege.ee/~jpoial/

Upload: dohanh

Post on 19-Mar-2018

222 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Algorithms and Data

Structures

5 ECTS

Exam

Jaanus Pöial, PhD

http://enos.itcollege.ee/~jpoial/

Page 2: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Schedule

Tue 16:00 Lecture ITC-217

Wed 10:15 Lab ITC-319 (every second week) + two

extra labs in May (Wed 2 and Wed 16 – 9:15)

Homeworks in Moodle using Java

https://moodle.hitsa.ee/course/view.php?id=18143

http://enos.itcollege.ee/~jpoial/algorithms/

Textbook: Michael T. Goodrich, Roberto Tamassia. Data Structures

and Algorithms in Java. John Wiley and Sons, Inc.

Page 3: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Topics

Algorithms, properties of algorithms, time complexity and

space complexity, asymptotic behaviour of functions,

analysis of algorithms, main complexity classes

Searching and sorting. Linear search, binary search,

hashing. Insertion sort, binary insertion sort, quicksort,

merge sort, counting sort, radix sort, bucket sort.

Complexity of different methods

Abstract data types. Stacks and queues. Reverse Polish

Notation (RPN). Linked lists and other pointer structures

Page 4: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Trees. Examples of trees - arithmetic expression tree.

Traversal of trees - preorder, postorder, in-order. Forms of

expression for trees - parenthetic expressions, pointer

structures, textual representation. Examples of "top-down"

and "bottom-up" traversal

Graphs. Directed and undirected graphs, multigraphs.

Cyclic and acyclic graphs. Connected components.

Strongly connected and weakly connected graphs. Paths

and cycles. Simple graphs. Matrices related to graphs:

adjacency matrix, matrix of shortest pathlengths.

Operations on graphs: sum, multiplication, transitive

closure. Representation and implementation of graphs.

Algorithms on graphs: Floyd-Warshall (lengths of shortest

paths), topological sort of vertices, depth-first and breadth-

first traversal, Dijkstra (shortest path), finding connected

components, minimal spanning tree

Page 5: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Recursion: Hanoi towers, elimination of recursion, tail

recursion. Exhaustive search: 8 queens problem,

knapsack problem

Binary search trees, AVL trees, red-black trees, binomial

trees. B-trees. Heaps, heapsort

String algorithms: exact matching (linear, Knuth-Morris-

Pratt, Boyer-Moore, Rabin-Karp)

Coding and compressing, coding schemes: Huffman,

Shannon-Fano. Greedy algoritms: Huffman encoding

Dynamic programming: longest common subsequence

problem

Page 6: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Correctness of algorithms: preconditions, postconditions,

loop invariants, weakest precondition, structural rules,

total correctness and partial correctness, halting problem

Exam

Page 7: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Java – History

1991 - P. Naughton, J. Gosling: project "Green", Sun virtual

machine, Oak ==> Java

1992 - "*7" - video-, cableTV equipment

1993 - Mosaic ==> HotJava web browser (P.Naughton, J.Payne)

1996 - JDK 1.02, 1997 – JDK 1.1

1998 - Java 2 (JDK 1.2..), 1999 – J2EE

2004 – Java 5

2006 – Java 6, 2011 – Java 7

2014 – Java 8

2017 – Java 9

Page 8: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Features

C-like syntax, simpler than C++ (more similar to C#)

No preprocessor

Object oriented (single inheritance until Java 7, automatic

garbage collection, late binding, abstract classes and

interfaces)

Standard and rich APIs (graphics, I/O, data structures,

networking, multithreading, … )

Standard documentation format and documenting tools

Page 9: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Features

Supported by variety of development environments

(IDEs): IntelliJ, Eclipse, NetBeans, …

Mostly interpretive language, binary representation of a

program is platform independent Java bytecode

interpreted by Java Virtual Machine (JVM)

JIT (just-in-time) compilation to machine code is possible

JVM is used by many other languages (Scala, Clojure,

Groovy, ...)

Page 10: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Drawbacks

Low-level (hardware) programming is hard

Interpretive => slow (bias)?

Not flexible enough to create totally new

abstractions

Not suited for beginners, simple programs look

complex, drastic learning curve

Generic programs (programs with type variables)

are hard to write (and even hard to understand) in

Java 5

Page 11: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

General Structure

Platform API = “technology” (J2SE, J2EE, J2ME,

JFX, JavaCard, Java DB, Java TV…)Java SE – Java Standard Edition, JDK 9 (JRE included)

Modules in Java 9: java.base, javafx.base, javafx…., …

Packages (flat namespace): java.lang, java.util,

java.io, java.nio, java.net, java.math, …Default package is unnamed, package java.lang is

always present, other packages need to be imported

Classes, interfaces, abstract classes – hierarchy (single

inheritance for classes, multiple interfaces allowed)

Class Object is the root of class tree and default parent

class if „extends“ clause is missing

Page 12: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Structure of the Class

Data

Class variables (static), common for all objects, e.g.

constants (final)

Instance variables, individual data, also known as

“attributes” or “fields” or “properties”

Possible inner classes, …

Actions

Class methods (static), imperative paradigm

Constructors to create new objects

Instance methods (work on objects)

Page 13: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

JDK – Java Development Kit

javac – Java compiler, X.java => X.class

java - Java interpreter, executes X.class

javadoc – documentation generator, generates *.html

from javadoc comments in program source

Page 14: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May
Page 15: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Examples

Life cycle of a program:

edit, compile, debug syntax, …, run, debug semantics, …,

run, test, …, test …

First.java

demo/Example.java

Control.java

Page 16: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Statements

block { declarations; statements }

expression

• method call: String.valueOf (56); s.length();

• constructor call: new StringBuilder();

• assignment: variable = expression

• complex expression containing operators: a+b*(c-d)

empty statement and labelled statement

if statement and if-else statement

switch statement

Page 17: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Statements (2)for statement

while statement and do-while statement

break statement

continue statement

return statement

throw statement

try-catch construction (try statement)

synchronized (object) block;

(synchronized statement)

assert statement

Page 18: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May
Page 19: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May
Page 20: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Examples

Mswitch

Mswitchbreak

Page 21: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Data Structures in Java

Simple variables: primitive types and object types

Arrays: base type, index, length

Objects: encapsulate different fields into one instance (like records in “old” imperative languages + methods)

Collections – built-in tools in Java API to manipulate group of objects: Vector, Hashtable, etc. Java collections framework

Page 22: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Types

Primitive types: byte, short, int, long, float, double,

boolean, char

Object types:

• Wrappers: Byte, Short, Integer, Long, Float, Double,

Boolean, Character

• Other API types: String, Object, StringBuffer, …

• Interface types: Comparable, Runnable, …

Page 23: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

ArraysArray creation and initialization

int [] a = { 1, 5, 8 };

consists of 3 steps:

int [] a; // variable declared

a = new int [3]; // memory allocated

a[0]=1; a[1]=5; a[2]=8; // values assigned

int n = a.length; // array size

Array expression:

int [] a = new int [] { 1, 5, 8};

Page 24: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Multi-dimensional Arrays

2-dimensional array is an array of 1-dimensional arrays (NB! these can be of different length):

int [][] m; // 2-dim array

m = new int [2][]; // first level

System.out.println (m.length);

m[0] = new int [4]; // second level

m[0][0] = -8;

m[1] = new int [3]; // different size

m[1][0] = 9;

Page 25: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Objects

Object fields:

class Person {

String surname;

String firstName;

Calendar birthDate;

// etc. whatever we want to record

Page 26: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Constructors

Person (String sn, String fn, Calendar bd) {

surname = sn;

firstName = fn;

birthDate = bd;

} // constructor

Person() {

this (“*”, “*”, Calendar.getInstance());

} // default constructor

Page 27: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Instance Methodspublic String toString() {

return (firstName + " " + surname

+ " " + String.valueOf (

birthDate.get (Calendar.YEAR)

) + " " + String.valueOf (

birthDate.get (Calendar.MONTH)

) + " " + String.valueOf (

birthDate.get(Calendar.DAY_OF_MONTH)));

} // toString

} // Person

Page 28: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Usage of Objectspublic class PersonMain {

public static void main (String[] args) {

Calendar bd1 = Calendar.getInstance();

bd1.set (1959, 04, 30);

Person p1 = new Person ("Smith",

"John", bd1);

System.out.println (p1);

Person p2 = new Person();

System.out.println (p2);

} // main

} // PersonMain

Page 29: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Collections

CollectionSet (set, unique elements)

HashSet

LinkedHashSet

SortedSet (ordered set, unique elements)

TreeSet

List (dynamic, indexed, multiple copies allowed)

ArrayList

LinkedList

Vector (legacy API, similar to ArrayList)

Queue (since Java 5, not discussed here)

Page 30: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Collections

Map ("key-value" pairs)HashMap

LinkedHashMap

SortedMap

TreeMap

Hashtable (legacy API)

WeakHashMap (allow garbage collection)

Iterator (to find the next element)

Enumeration (legacy API, similar to Iterator)

Iterable (has iterator)Collection

Page 31: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Collections

Comparablewhich of two elements is "bigger"public int compareTo (Object o)

/ -1, if o1 < o2

o1.compareTo (o2) =( 0, if o1 == o2

\ 1, if o1 > o2

Arraysstatic utilities – asList, search, sort, fill, ...

Collectionsstatic utilities – search, sort, copy, fill, replace, min, max,

reverse, shuffle, ...

Page 32: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Java Command Line

Javac – compilerjavac Cunit.java

javac –cp classpath Cunit.java

javac my/package/Myclass.java

Java – interpreterjava Cunit any text you like to pass

java –cp classpath Cunit

java my/package/Myclass

java my.package.Myclass

Page 33: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Junit – www.junit.org

javac -cp .:junit-4.12.jar ClassTest.java

java -cp .:junit-4.12.jar org.junit.runner.JUnitCore ClassTest

Page 34: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Decrease complexity (use layers of abstraction,

interfaces, modularity, ...)

Reuse existing code, avoid duplication of code

Support formal contracting between independent

development teams

Detect errors as early as possible (general goal of

software engineering)

Motivation for Object Oriented

Programming

Page 35: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Motivation

Object oriented approach was introduced on 1980-s to

reduce complexity of programming large software

systems (e.g. graphical user interfaces).

Flat library of standard functions (common for early

imperative programming languages) is not flexible

enough to create complex software systems.

Powerful and well organized object oriented framework

makes programming easier – programmer re-uses

existing codebase and specifies only these

properties/functions she needs to elaborate/change (and

framework adjusts to these changes).

Page 36: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Object

Object is characterized by

• State (defined by values of instance variables in Java)

• Behaviour (defined by instance methods in Java)

• Identity (defined by memory location in Java)

Object = Instance = Specimen = ...

• Instance variable (Java terminology) = (Object) field

= Property = Attribute = ...

• Method = Subroutine = Function / Procedure = ...

Page 37: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Object

Encapsulation – data and operations on the data are

integrated into whole (object = capsule)

ADT approach – set of operations is a part of data type

Data hiding – object state can be changed only by

dedicated (usually public) methods - instance variables

should be protected from direct modification

Object is an instance of the class. E.g. „Rex is a dog“.

Page 38: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Class

Class defines common features of its objects („template“).

E.g. „All dogs have a name“.

Instantiation – creating a new object of the class.

Subclass can be derived from the class – subclass inherits

all the features of its parent class. Subclass allows to add

new (specific) features and redefine (=override) inherited

features. E.g. „Dog is (a special kind of) Animal“.

If A is a subclass of B then B is superclass of A.

Page 39: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Class Hierarchy

Generalization – common features of similar classes are

described on the level of superclass (mental process –

design the hierarchy of classes).

Specialization – subclass is created to concretize (refine)

certain general features and add specific data/operations

to the subclass (process of coding).

Page 40: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Instance Methods and Class Methods

Instance methods define the behaviour of an object

(=instance).• s.length() - the length of string s in Java.

Class methods can be used without creating an

object (imperative style).

• Math.sqrt(2.) - square root of 2.

Keyword static in Java is used to define class

methods.

Page 41: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Polymorphism

Same notation has different meaning in different contexts

Two types of polymorphism:

Overloading – operation is redefined in subclass and is

binded to the activating message statically (compile

time choice).

Java constructors support overloading.

Overriding – operation is redefined in subclass and is

binded to the activating message dynamically (runtime

choice).

Java instance methods support overriding.

Page 42: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Examples

Pets.java

Phones.java

Num.java

Complex.java

Page 43: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Errors and Exceptions

Error handling without dedicated tools: return codes, global

error states etc.

Problem: it is not reasonable (or even possible) to handle

each unusual situation in the same place (subroutine) it

occurs. How to separate error handling from the normal

control flow?

Page 44: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Errors and Exceptions

In Java:

try / catch (control statement)

Throwable (specialized objects)

• Error (program cannot continue)

• Exception (unusual situation)

• RuntimeException (no obligation to catch)

throw (raise exception)

throws (method heading - delegating)

Page 45: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

ErrorsError

LinkageError

ClassCircularityError

ClassFormatError

IncompatibleClassChangeError

NoSuchMethodError

NoSuchFieldError

InstantiationError

AbstractMethodError

IllegalAccessError

NoClassDefFoundError

VerifyError

AbstractMethodError

ExceptionInInitializationError

Page 46: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Errors

ThreadDeath

VirtualMachineError

InternalError

OutOfMemoryError

StackOverflowError

UnknownError

AWTError

Page 47: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Checked Exceptions

Exception

ClassNotFoundException

CloneNotSupportedException

IllegalAccessException

InstantiationException

InterruptedException

NoSuchMethodException

TooManyListenersException

ParseException

AWTException

Page 48: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

IOExceptionIOException

CharConversionException

EOFException

FileNotFoundException

InterruptedIOException

ObjectStreamException

InvalidClassException

InvalidObjectException

NotActiveException

NotSerializableException

OptionalDataException

StreamCorruptedException

WriteAbortedException

Page 49: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

IOException

SyncFailedException

UnsupportedEncodingException

UTFDataFormatException

MalformedURLException

ProtocolException

SocketException

BindException

ConnectException

NoRouteToHostException

UnknownHostException

UnknownServiceException

Page 50: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

RuntimeExceptionRuntimeException

ArithmeticException

ArrayStoreException

ClassCastException

IllegalArgumentException

IllegalThreadStateException

NumberFormatException

FormatException

IllegalMonitorStateException

IllegalStateException

IndexOutOfBoundsException

ArrayIndexOutOfBoundsException

StringIndexOutOfBoundsException

Page 51: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

RuntimeException

NegativeArraySizeException

NullPointerException

SecurityException

EmptyStackException

MissingResourceException

NoSuchElementException

IllegalComponentStateException

Page 52: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Try / Catchtry {

block where exceptions may occur;

}

catch (ExcType_1 variable) {

trap_1;

}

...

catch (ExcType_n variable) {

trap_n;

}

finally {

epilogue;

}

Page 53: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Exampletry {

FileInputStream p = new FileInputStream ("/etc/passwd");

byte[] sisu = new byte [p.available()];

p.read (sisu);

p.close();

System.out.write (sisu);

} catch (FileNotFoundException e) {

System.out.println ("File not found " + e);

} catch (IOException e) {

System.out.println ("Input/Output error " + e);

} catch (Exception e) {

System.out.println ("Something unusual happened " + e);

} finally {

System.out.println (" This is finally branch");

} // try

Page 54: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Throw Statement

To raise an exception in your program

throw throwableObject;

Usually error message is provided

throw new SecurityException

("No permission to read!");

All checked (not RuntimeExceptions) exceptions need

handling – try/catch or delegation "up" using exception

declaration in method heading

Page 55: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Throws Declarationpublic static void pause()

throws InterruptedException {

Thread.sleep (1000);

}

public Object nextElement()

throws java.util.NoSuchElementException {

if (pointerToNext() == null)

throw new

java.util.NoSuchElementException();

else

return pointerToNext();

}

Corresponding javadoc tag!

Page 56: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Problems

When extending existing exception class provide both

default constructor (with no parameters) and a

constructor with String parameter (error message).

No "resume" – use loop structures to continue execution

Declare needed variables before try-block, otherwise

they are not accessible in traps (catch branches)

Page 57: Algorithms and Data Structuresenos.itcollege.ee/~jpoial/algorithms/ADS_intro.pdfSchedule Tue 16:00 Lecture ITC-217 Wed 10:15 Lab ITC-319 (every second week) + two extra labs in May

Examples

Chaining – ExceptionUsage.java

Resume and other things – Apples.java