cmsc 132: object-oriented programming ii java constructs department of computer science university...

18
CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

Upload: theodore-shepherd

Post on 17-Jan-2016

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

CMSC 132: Object-Oriented Programming II

Java Constructs

Department of Computer Science

University of Maryland, College Park

Page 2: 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

Page 3: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

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

Page 4: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

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

Page 5: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

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

}

Page 6: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

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

Page 7: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

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

}

Page 8: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

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

Page 9: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

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

Page 10: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

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

Page 11: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

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

Page 12: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

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

Page 13: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

Representing Exceptions

Java Exception class hierarchyTwo types of exceptions checked & unchecked

Page 14: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

ObjectObject

ErrorError

ThrowableThrowable

ExceptionException

LinkageErrorLinkageError

VirtualMachoneErrorVirtualMachoneError

ClassNotFoundExceptionClassNotFoundException

CloneNotSupportedExceptionCloneNotSupportedException

IOExceptionIOException

AWTErrorAWTError

AWTExceptionAWTException

RuntimeExceptionRuntimeException

ArithmeticExceptionArithmeticException

NullPointerExceptionNullPointerException

IndexOutOfBoundsExceptionIndexOutOfBoundsException

UncheckedUnchecked

CheckedChecked

NoSuchElementExceptionNoSuchElementException

Representing Exceptions

Java Exception class hierarchy

Page 15: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

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

Page 16: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

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

Page 17: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

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

Page 18: CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park

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

}