Week 1 - Friday.  What did we talk about last time?  Basic programming model  Other Java stuff  References  Static  Inner classes  Exceptions.

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Testing and Error Handling Intro to Java. Testing We test to try and make sure our programs work correctly and have no bugs If we have access to the code,
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Final Review.
Slides 4/22 COP Topics Final Exam Review Final Exam The final exam is Friday, April 29 th at 10:00 AM in the usual room No notes, books, calculators,
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Collections. Lecture Objectives To understand the concepts of Java collections To be able to implement Java programs based on Collections.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
OOP Languages: Java vs C++
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Programming Languages and Paradigms Object-Oriented Programming.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Java and C++, The Difference An introduction Unit - 00.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Week 2 - Monday.  What did we talk about last time?  Exceptions  Threads  OOP  Interfaces.
Object Oriented Programming: Java Edition By: Samuel Robinson.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Week 1 - Wednesday.  What did we talk about last time?  Course overview  Policies  Schedule.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
LECTURE 8: EXCEPTIONS CSC 212 – Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
OOP Basics Classes & Methods (c) IDMS/SQL News
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Week 2 - Wednesday CS221.
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Java Programming Language
Exceptions, Interfaces & Generics
Week 14 - Wednesday CS222.
Introduction to Exceptions in Java
Interfaces and Inheritance
Advanced Programming Behnam Hatami Fall 2017.
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Java Basics Exception Handling.
Week 1 - Wednesday CS221.
Presentation transcript:

Week 1 - Friday

 What did we talk about last time?  Basic programming model  Other Java stuff  References  Static  Inner classes  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

 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)

 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

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 (); } 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 (); }

 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

 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

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; } } 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; } }

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; } 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; }

 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

 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

 A template or prototype for an object Class: Human Object: David Bowie Object: Barack Obama Class: Company Object: Microsoft Object: Boeing

 Encapsulation  Dynamic dispatch  Polymorphism  Inheritance  Self-reference

 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

public class A { private int a; public int getA() { return a; } public void setA(int value) { a = value; } public class A { private int a; public int getA() { return a; } public void setA(int value) { a = value; }

 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

public class B extends A { //has member and methods from A } public class C extends A { //has A stuff and more private int c; public int getC(){ return c; } void increment() { c++; } } public class B extends A { //has member and methods from A } public class C extends A { //has A stuff and more private int c; public int getC(){ return c; } void increment() { c++; } }

 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

//defined somewhere public void drive( Car car ) { … } public class BMW235i extends Car { … } Car car = new Car(); BMW235i bimmer = new BMW235i(); drive( bimmer ); //okay drive( car ); //okay //defined somewhere public void drive( Car car ) { … } public class BMW235i extends Car { … } Car car = new Car(); BMW235i bimmer = new BMW235i(); drive( bimmer ); //okay drive( car ); //okay

 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

public class A { public void print(){ System.out.println("A"); } public class B extends A { public void print() { System.out.println("B"); } public class A { public void print(){ System.out.println("A"); } public class B extends A { public void print() { System.out.println("B"); }

A a = new A(); B b = new B(); // B extends A A c; a.print(); // A b.print(); // B c = a; c.print(); // A c = b; c.print(); // B A a = new A(); B b = new B(); // B extends A A c; a.print(); // A b.print(); // B c = a; c.print(); // A c = b; c.print(); // B

 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

public class Stuff { private int things; public void setThings(int things) { this.things = things; } public class Stuff { private int things; public void setThings(int things) { this.things = things; }

public class SelfAdder { publicvoid addToList(List list) { list.add(this); } public class SelfAdder { publicvoid addToList(List list) { list.add(this); }

 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

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 } 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 }

 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

 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); } public interface Guitarist { void strumChord(Chord chord); void playMelody(Melody notes); }

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!" ); } 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!" ); }

 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 ); } 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 ); }

 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 )  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

 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

public class Pair { 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 + " )"; } public class Pair { 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 + " )"; }

public class Test { public static void main(String[] args) { Pair pair1 = new Pair ("ham", "eggs"); Pair pair2 = new Pair ( 5, 7 ); pair1.swap(); System.out.println( pair1 ); System.out.println( pair2 ); } public class Test { public static void main(String[] args) { Pair pair1 = new Pair ("ham", "eggs"); Pair pair2 = new Pair ( 5, 7 ); pair1.swap(); System.out.println( pair1 ); System.out.println( pair2 ); }

Java Collections Framework

 Collection  Iterable  List  Queue  Set  SortedSet  Map  SortedMap

 LinkedList  ArrayList  Stack  Vector  HashSet  TreeSet  HashMap  TreeMap

 Collections  sort()  max()  min()  replaceAll()  reverse()  Arrays  binarySearch()  sort()

 Computational complexity  Read section 1.4

 Work on Assignment 1  Due next Friday by 11:59pm  Start on Project 1