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

Slides:



Advertisements
Similar presentations
9-Jun-14 Enum s (and a review of switch statements)
Advertisements

Module 4: Statements and Exceptions. Overview Introduction to Statements Using Selection Statements Using Iteration Statements Using Jump Statements Handling.
New features in JDK 1.5 Can these new and complex features simplify Java development?
Java Review – Exec, I/O, New Features George Blankenship1 CSCI 6234 Object Oriented Design: Java Review – Execution, I/O and New Features George Blankenship.
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Yoshi
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
COMP 121 Week 5: Exceptions and Exception Handling.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
For use of Cleveland State's IST410 Students only 1 Exception.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
10-1 Writing to a Text File When a text file is opened in this way, a FileNotFoundException can be thrown – In this context it actually means that the.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
CS 206 Introduction to Computer Science II 01 / 21 / 2009 Instructor: Michael Eckmann.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Java Exceptions, Cloning, Serialization Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
Java 1.5 & Effective Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Review Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
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.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Java Software Solutions Foundations of Program Design Sixth Edition
CIS 270—Application Development II Chapter 13—Exception Handling.
COSC 1P03 Data Structures and Abstraction 4.1 Abstract Data Types The advantage of a bad memory is that one enjoys several times the same good things for.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
COMP Exception Handling Yi Hong June 10, 2015.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
© 2004 Pearson Addison-Wesley. All rights reserved April 24, 2006 Exceptions (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING 2006.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Transition to Java Programming with Alice and Java First Edition.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Chapter 11 Exceptions and Input/Output Operations.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
© 2004 Pearson Addison-Wesley. All rights reserved December 5, 2007 I/O Exceptions & Working with Files ComS 207: Programming I (in Java) Iowa State University,
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Object Throwable ErrorException RuntimeException.
Objectives You should be able to describe: Interactive Keyboard Input
CS102 – Exceptions David Davenport Latest: May 2015
I/O Basics.
I/O Exceptions & Working with Files
Presentation transcript:

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

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

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 SortValues.java

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

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

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

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

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

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(it.next()); for (String student : roster) // using for loop System.out.println(student);

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

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

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

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

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

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

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

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

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 }

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

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 java.io.* ; 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