Presentation is loading. Please wait.

Presentation is loading. Please wait.

CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.

Similar presentations

Presentation on theme: "CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park."— Presentation transcript:

1 CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park

2 Overview Autoboxing Enumerated Types Iterator Interface Enhanced for loop Scanner class Exceptions Streams

3 Autoboxing & Unboxing Automatically convert primitive data types Data value Object (of matching class) Data types & classes converted Boolean, Byte, Double, Short, Integer, Long, Float Example See

4 Enumerated Types New type of variable with set of fixed values Establishes all possible values by listing them Supports values(), valueOf(), name(), compareTo()… Can add fields and methods to enums Example public enum Color { Black, White } // new enumeration Color myC = Color.Black; for (Color c : Color.values()) System.out.println(c); When to use enums Natural enumerated types – days of week, phases of the moon, seasons Sets where you know all possible values

5 Enumerated Types The following example is from the presentation "Taming the Tiger" by Joshua Bloch and Neal Gafter that took place at Sun's 2004 Worldwide Java Developer Conference. Example public class Card implements Serializable { public enum Rank {DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE } public enum Suit {CLUBS, DIAMONDS, HEARTS, SPADES} private final Rank rank; private final Suit suit; private Card(Rank rank, Suit suit) { this.rank = rank; this.suit = suit; } public Rank rank() {return rank;} public Suit suit() {return suit;} public String toString() {return rank + " of " + suit;} }

6 Iterator Interface Iterator Common interface for all Collection classes Used to examine all elements in collection Properties Can remove current element during iteration Works for any collection

7 Iterator Interface Interface public interface Iterator { boolean hasNext(); Object next(); void remove(); // optional, called once per next() } Example usage Iterator i = myCollection.iterator(); while (i.hasNext()) { myCollectionElem x = (myCollectionElem); }

8 Enhanced For Loop Works for arrays and any class that implements the Iterable interface. For loop handles Iterator automatically Test hasNext(), then get & cast next() Example 1 // Iterating over a String array String[] roster = {"John", "Mary", "Peter", "Jackie", "Mark"}; for (String student : roster) System.out.println(student);

9 Enhanced For Loop Example 2 ArrayList roster = new ArrayList (); roster.add("John"); roster.add("Mary"); Iterator it = roster.iterator(); // using an iterator while (it.hasNext()) System.out.println(; for (String student : roster) // using for loop System.out.println(student);

10 Standard Input/Output Standard I/O Provided in System class in java.lang An instance of InputStream System.out An instance of PrintStream System.err An instance of PrintStream

11 Scanner class Scanner Allow us to read primitive type and strings from the standard input Example See In the example notice the use of printf

12 Exception Handling Performing action in response to exception Example actions Ignore exception Print error message Request new data Retry action Approaches 1. Exit program 2. Exit method returning error code 3. Throw exception

13 Representing Exceptions Java Exception class hierarchy Two types of exceptions checked & unchecked

14 Object Error Throwable Exception LinkageError VirtualMachoneError ClassNotFoundException CloneNotSupportedException IOException AWTError … AWTException RuntimeException … ArithmeticException NullPointerException IndexOutOfBoundsException Unchecked Checked NoSuchElementException … Representing Exceptions Java Exception class hierarchy

15 Unchecked Exceptions Class Error & RunTimeException Serious errors not handled by typical program Usually indicate logic errors Example NullPointerException, IndexOutOfBoundsException Catching unchecked exceptions is optional Handled by Java Virtual Machine if not caught

16 Checked Exceptions Class Exception (except RunTimeException) Errors typical program should handle Used for operations prone to error Example IOException, ClassNotFoundException Compiler requires catch or declare Catch and handle exception in method, OR Declare method can throw exception, force calling function to catch or declare exception in turn Example void A( ) throws ExceptionType { … }

17 Exceptions – Java Primitives Java primitives Try Forms try block Encloses all statements that may throw exception Throw Actually throw exception Catch Catches exception matching type Code in catch block exception handler Finally Forms finally block Always executed, follows try block & catch code

18 Exceptions - Syntax try {// try block encloses throws throw new eType1(); // throw jumps to catch } catch (eType1 e) { // catch block 1...action... // run if type match } catch (eType2 e) { // catch block 2...action... // run if type match } finally { // final block...action... // always executes }

19 Stream Input/Output Stream A connection carrying a sequence of data Bytes InputStream, OutputStream Characters FileReader, PrintWriter From a source to a destination Keyboard File Network Memory Basis for modern I/O

20 Using Streams Opening a stream Connects program to external data Location of stream specified at opening Only need to refer to stream Usage 1. import* ; 2. Open stream connection 3. Use stream read and / or write Catch exceptions if needed 4. Close stream Examples See fileExamples package in lect2.jar

Download ppt "CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park."

Similar presentations

Ads by Google