cmsc 132: object-oriented programming ii java constructs department of computer science university...
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 typesData value Object (of matching class)
Data types & classes converted
Boolean, Byte, Double, Short, Integer, Long, Float
ExampleSee 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
Examplepublic 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 values
Enumerated 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.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
IteratorCommon interface for all Collection classes
Used to examine all elements in collection
PropertiesCan 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 usageIterator 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<String> roster = new ArrayList<String>();
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
ScannerAllow us to read primitive type and strings from the standard input
ExampleSee ScannerExample.java
In the example notice the use of printf
Exception Handling
Performing action in response to exception
Example actionsIgnore exception
Print error message
Request new data
Retry action
Approaches1. Exit program
2. Exit method returning error code
3. Throw exception
Representing Exceptions
Java Exception class hierarchyTwo types of exceptions checked & unchecked
ObjectObject
ErrorError
ThrowableThrowable
ExceptionException
LinkageErrorLinkageError
VirtualMachoneErrorVirtualMachoneError
ClassNotFoundExceptionClassNotFoundException
CloneNotSupportedExceptionCloneNotSupportedException
IOExceptionIOException
AWTErrorAWTError
…
AWTExceptionAWTException
RuntimeExceptionRuntimeException
…
ArithmeticExceptionArithmeticException
NullPointerExceptionNullPointerException
IndexOutOfBoundsExceptionIndexOutOfBoundsException
UncheckedUnchecked
CheckedChecked
NoSuchElementExceptionNoSuchElementException
…
Representing Exceptions
Java Exception class hierarchy
Unchecked Exceptions
Class Error & RunTimeException
Serious errors not handled by typical program
Usually indicate logic errors
ExampleNullPointerException, 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 primitivesTry
Forms try block
Encloses all statements that may throw exceptionThrow
Actually throw exceptionCatch
Catches exception matching type
Code in catch block exception handlerFinally
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
}