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