DOC PREVIEW
UMD CMSC 132 - Object-Oriented Programming II

This preview shows page 1-2-19-20 out of 20 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 20 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 20 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 20 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 20 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 20 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

CMSC 132: Object-Oriented Programming IIOverviewAutoboxing & UnboxingEnumerated TypesSlide 5Iterator InterfaceSlide 7Enhanced For LoopSlide 9Standard Input/OutputScanner classException HandlingRepresenting ExceptionsSlide 14Unchecked ExceptionsChecked ExceptionsExceptions – Java PrimitivesExceptions - SyntaxStream Input/OutputUsing StreamsCMSC 132: Object-Oriented Programming IINelson Padua-PerezWilliam PughDepartment of Computer ScienceUniversity of Maryland, College ParkOverviewAutoboxingEnumerated TypesIterator InterfaceEnhanced for loopScanner classExceptionsStreamsAutoboxing & UnboxingAutomatically convert primitive data typesData value  Object (of matching class)Data types & classes convertedBoolean, Byte, Double, Short, Integer, Long, FloatExampleSee SortValues.javaEnumerated TypesNew type of variable with set of fixed valuesEstablishes all possible values by listing themSupports values(), valueOf(), name(), compareTo()…Can add fields and methods to enumsExamplepublic enum Color { Black, White } // new enumerationColor myC = Color.Black;for (Color c : Color.values()) System.out.println(c);When to use enumsNatural enumerated types – days of week, phases of the moon, seasonsSets where you know all possible valuesEnumerated TypesThe 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.Examplepublic 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 InterfaceIteratorCommon interface for all Collection classesUsed to examine all elements in collectionPropertiesCan remove current element during iterationWorks for any collectionIterator InterfaceInterface public interface Iterator { boolean hasNext(); Object next(); void remove(); // optional, called once per next()}Example usageIterator i = myCollection.iterator();while (i.hasNext()) {myCollectionElem x = (myCollectionElem) i.next(); }Enhanced For LoopWorks for arrays and any class that implements the Iterable interface.For loop handles Iterator automaticallyTest 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 LoopExample 2ArrayList<String> roster = new ArrayList<String>();roster.add("John");roster.add("Mary");Iterator it = roster.iterator(); // using an iteratorwhile (it.hasNext()) System.out.println(it.next()); for (String student : roster) // using for loop System.out.println(student);Standard Input/OutputStandard I/O Provided in System class in java.lang System.in An instance of InputStreamSystem.out An instance of PrintStream System.err An instance of PrintStreamScanner class ScannerAllow us to read primitive type and strings from the standard inputExampleSee ScannerExample.javaIn the example notice the use of printfException HandlingPerforming action in response to exceptionExample actionsIgnore exceptionPrint error messageRequest new dataRetry actionApproaches1. Exit program2. Exit method returning error code3. Throw exceptionRepresenting ExceptionsJava Exception class hierarchyTwo types of exceptions  checked & uncheckedObjectObjectErrorErrorThrowableThrowableExceptionExceptionLinkageErrorLinkageErrorVirtualMachoneErrorVirtualMachoneErrorClassNotFoundExceptionClassNotFoundExceptionCloneNotSupportedExceptionCloneNotSupportedExceptionIOExceptionIOExceptionAWTErrorAWTError…AWTExceptionAWTExceptionRuntimeExceptionRuntimeException…ArithmeticExceptionArithmeticExceptionNullPointerExceptionNullPointerExceptionIndexOutOfBoundsExceptionIndexOutOfBoundsExceptionUncheckedUncheckedCheckedCheckedNoSuchElementExceptionNoSuchElementException…Representing ExceptionsJava Exception class hierarchyUnchecked ExceptionsClass Error & RunTimeExceptionSerious errors not handled by typical programUsually indicate logic errorsExampleNullPointerException, IndexOutOfBoundsExceptionCatching unchecked exceptions is optionalHandled by Java Virtual Machine if not caughtChecked ExceptionsClass Exception (except RunTimeException)Errors typical program should handleUsed for operations prone to errorExample IOException, ClassNotFoundExceptionCompiler requires “catch or declare” Catch and handle exception in method, ORDeclare method can throw exception, force calling function to catch or declare exception in turnExamplevoid A( ) throws ExceptionType { … }Exceptions – Java PrimitivesJava primitivesTryForms try blockEncloses all statements that may throw exceptionThrowActually throw exceptionCatchCatches exception matching typeCode in catch block  exception handlerFinallyForms finally blockAlways executed, follows try block & catch codeExceptions - Syntaxtry { // 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 StreamA connection carrying a sequence of dataBytes  InputStream, OutputStreamCharacters  FileReader, PrintWriterFrom a source to a destinationKeyboard FileNetworkMemoryBasis for modern I/OUsing StreamsOpening a stream Connects program to external dataLocation of stream specified at openingOnly need to refer to stream Usage1. import java.io.* ; 2. Open stream connection3. Use stream  read and / or writeCatch exceptions if needed4. Close streamExamples See fileExamples package in


View Full Document

UMD CMSC 132 - Object-Oriented Programming II

Documents in this Course
Notes

Notes

8 pages

Recursion

Recursion

12 pages

Sorting

Sorting

31 pages

HTML

HTML

7 pages

Trees

Trees

19 pages

HTML

HTML

18 pages

Trees

Trees

19 pages

Honors

Honors

19 pages

Lecture 1

Lecture 1

11 pages

Quiz #3

Quiz #3

2 pages

Hashing

Hashing

21 pages

Load more
Download Object-Oriented Programming II
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Object-Oriented Programming II and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Object-Oriented Programming II 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?