CMSC 132: Object-Oriented Programming II Java Constructs 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

CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
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?
Topics Introduction Types of Errors Exceptions Exception Handling
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
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.
© 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.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
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.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
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.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
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.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
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. 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.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
CIS 270—Application Development II Chapter 13—Exception Handling.
1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions.
A Singleton Puzzle: What is Printed? 1 public class Elvis { public static final Elvis INSTANCE = new Elvis(); private final int beltSize; private static.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
COMP Exception Handling Yi Hong June 10, 2015.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
© 2004 Pearson Addison-Wesley. All rights reserved April 24, 2006 Exceptions (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING 2006.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Exceptions and Assertions Chapter 15 – CSCI 1302.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Recitation 5 Enums and The Java Collections classes/interfaces 1.
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.
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.
CS 61B Data Structures and Programming Methodology July 8, 2008 David Sun.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
© 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.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
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.
CS102 – Exceptions David Davenport Latest: May 2015
ATS Application Programming: Java Programming
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Exceptions 10-May-19.
Presentation transcript:

CMSC 132: Object-Oriented Programming II Java Constructs 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 }