0% found this document useful (0 votes)
29 views

07 Java Classes Pt6

The document compares abstract classes and interfaces in Java. It notes that abstract classes are similar to interfaces in that they cannot be instantiated and can contain methods declared without implementation. However, abstract classes have additional capabilities that interfaces do not, such as the ability to define non-static, non-final fields and public, protected, and private concrete methods. The document also states that a class can extend only one class but implement multiple interfaces, while interfaces can only contain public, static, and final fields and public abstract methods.

Uploaded by

ahelmy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

07 Java Classes Pt6

The document compares abstract classes and interfaces in Java. It notes that abstract classes are similar to interfaces in that they cannot be instantiated and can contain methods declared without implementation. However, abstract classes have additional capabilities that interfaces do not, such as the ability to define non-static, non-final fields and public, protected, and private concrete methods. The document also states that a class can extend only one class but implement multiple interfaces, while interfaces can only contain public, static, and final fields and public abstract methods.

Uploaded by

ahelmy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

Comparing Abstract

Classes & Interfaces


1

Comparing Abstract Classes & Interfaces

Abstract classes are similar to


interfaces

Interface
Abstract
Class

See docs.oracle.com/javase/tutorial/java/IandI/abstract.html
2

Comparing Abstract Classes & Interfaces

Abstract classes are similar to


interfaces, e.g.
They cant be instantiated

package java.util;
public abstract class
AbstractMap<K,V> ... {
...
public abstract
Set<Entry<K,V>> entrySet();
...

Comparing Abstract Classes & Interfaces

Abstract classes are similar to


interfaces, e.g.
They cant be instantiated
They can contain methods
declared without any
implementation

package java.util;
public abstract class
AbstractMap<K,V> ... {
...
public abstract
Set<Entry<K,V>> entrySet();
...

Comparing Abstract Classes & Interfaces

However, abstract classes have


additional capabilities

package java.util;
public abstract class
AbstractMap<K,V> ... {
...
volatile Set<K> keySet;
volatile Collection<V> values;
...

Comparing Abstract Classes & Interfaces

However, abstract classes have


additional capabilities, e.g.
They can define fields that are
not static nor final

package java.util;
public abstract class
AbstractMap<K,V> ... {
...
volatile Set<K> keySet;
volatile Collection<V> values;
...

Comparing Abstract Classes & Interfaces

However, abstract classes have


additional capabilities, e.g.
They can define fields that are
not static nor final
They can also define public,
protected, & private concrete
methods

package java.util;
public abstract class
AbstractMap<K,V> ... {
...
public V put(K key, V value) {
...
}
protected Object clone()
{ ... }
private static boolean eq
(Object o1, Object o2)
{ ... }
...

Comparing Abstract Classes & Interfaces

In contrast, all fields in an


interface must be public, static,
& final

public interface Comparator<T> {


int compare(T o1, T o2);
boolean equals(Object obj);
default Comparator<T>
reversed() {
return Collections.
reverseOrder(this);
}
...

Comparing Abstract Classes & Interfaces

In contrast, all fields in an


interface must be public, static,
& final
Likewise, all methods in an
interface must be public & not
implemented

public interface Comparator<T> {


int compare(T o1, T o2);
boolean equals(Object obj);
default Comparator<T>
reversed() {
return Collections.
reverseOrder(this);
}
...

Default method implementations in interfaces


is a Java 8 feature not in Android
9

Comparing Abstract Classes & Interfaces

A class can extend only one class,


whether or not it is abstract

public class HashMap<K,V>


extends AbstractMap<K,V>
implements Map<K,V>,
Cloneable,
Serializable {
...
}

10

Comparing Abstract Classes & Interfaces

A class can extend only one class, public class HashMap<K,V>


extends AbstractMap<K,V>
whether or not it is abstract
implements Map<K,V>,
Conversely, it can implement any
Cloneable,
number of interfaces
Serializable {
...
}

See javapapers.com/core-java/why-multiple-inheritance-is-not-supported-in-java
11

Importing Classes
& Creating Classes
12

Importing Classes

You can refer to any class that is


in the same package by its name

Class Arrays & Vector


are both in the
java.util package

package java.util;
public class Arrays {
public static <T> T[]
copyOf(T[] original,
int newLength) {
...
public class Vector<E> {
public Object clone() {
...
Object[] v =
Arrays.copyOf(mData,
mCount);
...

13

Importing Classes

You can refer to any class that is


in the same package by its name

Class Arrays & Vector


are both in the
java.util package

package java.util;
public class Arrays {
public static <T> T[]
copyOf(T[] original,
int newLength) {
...
public class Vector<E> {
public Object clone() {
...
Object[] v =
Arrays.copyOf(mData,
mCount);
...

14

Importing Classes

If the class that you are referring


to is not in the same package,
you have two options:

15

Importing Classes

If the class that you are referring


to is not in the same package,
you have two options:
Use the fully qualified name of
that class

package java.util.concurrent;

public class
ConcurrentHashMap<K,V>
extends
java.util.AbstractMap<K,V>
...

This hypothetical example uses


a (verbose) fully qualified name

Using fully qualified names is often considered


poor form due to verbosity
16

Importing Classes

If the class that you are referring


to is not in the same package,
you have two options:
Use the fully qualified name of
that class
Add an import statement to
import that class

package java.util.concurrent;
import java.util.AbstractMap;
...
public class
ConcurrentHashMap<K,V>
extends
AbstractMap<K,V>
...

17

Importing Classes

If the class that you are referring


to is not in the same package,
you have two options:
Use the fully qualified name of
that class
Add an import statement to
import that class

package java.util.concurrent;
import java.util.AbstractMap;
...
public class
ConcurrentHashMap<K,V>
extends
AbstractMap<K,V>
...

Note succinct
class declaration

18

Importing Classes

If the class that you are referring


to is not in the same package,
you have two options:
Use the fully qualified name of
that class
Add an import statement to
import that class
Imports follow the package
declaration

package java.util.concurrent;
import java.util.AbstractMap;
...
public class
ConcurrentHashMap<K,V>
extends
AbstractMap<K,V>
...

19

Importing Classes

If the class that you are referring


to is not in the same package,
you have two options:
Use the fully qualified name of
that class
Add an import statement to
import that class
Imports follow the package
declaration
Allow direct use of classes
defined in other packages

package java.util.concurrent;
import java.util.AbstractMap;
...
public class
ConcurrentHashMap<K,V>
extends
AbstractMap<K,V>
...

20

Overview of Java
Exception Handling
21

Java Exception Handling

Apps occasionally encounter problems that just cant be ignored

See en.wikipedia.org/wiki/Murphys_law
22

Java Exception Handling

Apps occasionally encounter problems that just cant be ignored, e.g.


Attempting to open a file
thats not available
Error
File Not
Found

23

Java Exception Handling

Apps occasionally encounter problems that just cant be ignored, e.g.


Attempting to open a file
thats not available
Error
Trying to call a method or access
a field via a null reference
NullPointer
Exception

24

Java Exception Handling

Apps occasionally encounter problems that just cant be ignored, e.g.


Attempting to open a file
thats not available
Error
Trying to call a method or access
a field via a null reference
ArrayIndex
Indexing before or after the
OutOfBounds
valid range of an array

25

Java Exception Handling

Exception handling separates


control flow paths of normal
processing versus anomalous
processing

See en.wikipedia.org/wiki/Exception_handling
26

Java Exception Handling

Java exception handling is supported


by an extensible hierarchy of classes &
a set of virtual machine mechanisms

See eskatos.wordpress.com/2009/09/30/how-is-exception-handling-implemented-in-jvms
27

Java Exception Handling

If an error condition occurs, an exception can be thrown to notify that a


problem occurred

28

Java Exception Handling

If an error condition occurs, an exception can be thrown to notify that a


problem occurred
Appropriate actions when catching
an exception include interacting with
the user, logging, or exiting the app

29

Java Exception Handling

Any code can report an


exception via throw

public class Vector<E> {


...
public Vector(int initialCapacity,
......) {
if (initialCapacity < 0)
throw new
IllegalArgumentException
("Illegal Capacity: "
+ initialCapacity);
...
}
...

See docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
30

Java Exception Handling

Any code can report an


exception via throw

public class Vector<E> {


...
public Vector(int initialCapacity,
......) {
if (initialCapacity < 0)
throw new
IllegalArgumentException
("Illegal Capacity: "
+ initialCapacity);
...
}
...

31

Java Exception Handling

Any code can report an


exception via throw

public class Vector<E> {


...
public Vector(int initialCapacity,
......) {
if (initialCapacity < 0)
throw new
IllegalArgumentException
("Illegal Capacity: "
+ initialCapacity);
...
}
...

32

Java Exception Handling

Any code can report an


exception via throw

public class Vector<E> {


...
public int lastIndexOf(Object o,
int index){
if (index >= mCount)
throw new
IndexOutOfBoundsException
(index + " >= "+ mCount);
...
}

33

Java Exception Handling

Any code can report an


exception via throw

public class Vector<E> {


...
public int lastIndexOf(Object o,
int index){
if (index >= mCount)
throw new
IndexOutOfBoundsException
(index + " >= "+ mCount);
...
}

34

Java Exception Handling

The virtual machine performs


a number of steps when an
exception is thrown

35

Java Exception Handling


The virtual machine performs
a number of steps when an
exception is thrown

method1()
calls

Call Stack

method2() throws
IOException {}
calls
method3() throws
IOException {}
calls
method4() throw
IOException {}

36

Java Exception Handling


The virtual machine performs
a number of steps when an
exception is thrown

method1()
calls

Call Stack

method2() throws
IOException {}
calls
method3() throws
IOException {}
calls
method4() throw
IOException {}

37

Java Exception Handling


The virtual machine performs
a number of steps when an
exception is thrown

method1()
calls

Call Stack

method2() throws
IOException {}
calls
method3() throws
IOException {}
calls
method4() throw
IOException {}

38

Java Exception Handling


The virtual machine performs
a number of steps when an
exception is thrown

method1()
calls

Call Stack

method2() throws
IOException {}
calls
method3() throws
IOException {}
calls
method4() throw
IOException {}

39

Java Exception Handling


The virtual machine performs
a number of steps when an
exception is thrown

method1()
calls

Call Stack

Throws
IOException

method2() throws
IOException {}
calls
method3() throws
IOException {}
calls
method4() throw
IOException {}

40

Java Exception Handling


The virtual machine performs
a number of steps when an
exception is thrown
1. Normal program execution
stops

method1()
calls

Call Stack

method2() throws
IOException {}
calls
method3() throws
IOException {}
calls
method4() throw
IOException {}

41

Java Exception Handling


The virtual machine performs
a number of steps when an
exception is thrown
1. Normal program execution
stops
2. Control then transfers to
appropriate handler

The virtual machine searches


up the runtime call stack to
find exception handler

method1()
calls

Call Stack

method2() throws
IOException {}
calls
method3() throws
IOException {}
calls
method4() throw
IOException {}

42

Java Exception Handling


The virtual machine performs
a number of steps when an
exception is thrown
1. Normal program execution
stops
2. Control then transfers to
appropriate handler

method1()
calls

Call Stack

method2() throws
IOException {}
calls
method3() throws
IOException {}
calls
method4() throw
IOException {}

43

Catches
IOException

Java Exception Handling

A try block encloses regions of


code that may throw exceptions

public class MyClass {


public MyClass() {
try {
Vector<String> v =
new Vector<>(-1);
} catch
(IllegalArgumentException e){
...
}
...

See docs.oracle.com/javase/tutorial/essential/exceptions/try.html
44

Java Exception Handling

A try block encloses regions of


code that may throw exceptions
A try block contains one or
more statements that may
throw an exception

public class MyClass {


public MyClass() {
try {
Vector<String> v =
new Vector<>(-1);
} catch
(IllegalArgumentException e){
...
}
...

See docs.oracle.com/javase/tutorial/essential/exceptions/try.html
45

Java Exception Handling

A try block encloses regions of


code that may throw exceptions
A try block contains one or
more statements that may
throw an exception

public class MyClass {


public MyClass() {
try {
Vector<String> v =
new Vector<>(-1);
} catch
(IllegalArgumentException e){
...
}
...

46

Java Exception Handling

A try block encloses regions of


code that may throw exceptions
A try block contains one or
more statements that may
throw an exception

public class MyClass {


public MyClass() {
try {
Vector<String> v =
new Vector<>(-1);
} catch
(IllegalArgumentException e){
...
}
...

47

Java Exception Handling

One or more catch blocks can


be associated with a try block

public class MyClass {


public MyClass() {
try {
Vector<String> v =
new Vector<>(-1);
} catch
(IllegalArgumentException e){
...
}
...

See docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
48

Java Exception Handling

One or more catch blocks can public class MyClass {


public MyClass() {
be associated with a try block
try {
A catch block defines an
Vector<String> v =
exception handler that handles
new Vector<>(-1);
the type of exception indicated
} catch
by its argument
(IllegalArgumentException e){
...
}
...

See docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
49

Java Exception Handling

One or more catch blocks can public class MyClass {


public MyClass() {
be associated with a try block
try {
A catch block defines an
Vector<String> v =
exception handler that handles
new Vector<>(-1);
the type of exception indicated
} catch
by its argument
(IllegalArgumentException e){
...
}
...

50

Java Exception Handling

One or more catch blocks can public class MyClass {


public MyClass() {
be associated with a try block
try {
A catch block defines an
Vector<String> v =
exception handler that handles
new Vector<>(-1);
the type of exception indicated
} catch
by its argument
(IllegalArgumentException e){
...
}
...

51

Java Exception Handling

A finally block always runs


when the try block exits

public class SomeClass {


...
private final ReentrantLock
lock = new ReentrantLock();
...
public void someMethod() ... {
final ReentrantLock lock
= this.lock;
lock.lock();
try {
// ...
} finally {
lock.unlock();
}
...

See docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
52

Java Exception Handling

A finally block always runs


when the try block exits

Runs regardless of whether


an exception is thrown or
if the try block returns

public class SomeClass {


...
private final ReentrantLock
lock = new ReentrantLock();
...
public void someMethod() ... {
final ReentrantLock lock
= this.lock;
lock.lock();
try {
// ...
} finally {
lock.unlock();
}
...

53

Java Exception Handling

A try-with-resources try block


declares one or more resources
that are closed after block exits

public class SomeClass {


...
String readFirstLineFromFile
(String path)
throws IOException {
try (BufferedReader bufReader =
new BufferedReader
(new FileReader(path)))
{ return bufReader.readLine(); }
}
...

See docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
54

Java Exception Handling

A try-with-resources try block


declares one or more resources
that are closed after block exits

public class SomeClass {


...
String readFirstLineFromFile
(String path)
throws IOException {
try (BufferedReader bufReader =
new BufferedReader
(new FileReader(path)))
{ return bufReader.readLine(); }
}
...

55

Java Exception Handling

A try-with-resources try block


declares one or more resources
that are closed after block exits

public class SomeClass {


...
String readFirstLineFromFile
(String path)
throws IOException {
try (BufferedReader bufReader =
new BufferedReader
(new FileReader(path)))
{ return bufReader.readLine(); }
}
...

56

Java Exception Handling

A try-with-resources try block


declares one or more resources
that are closed after block exits

public class SomeClass {


...
String readFirstLineFromFile
(String path)
throws IOException {
try (BufferedReader bufReader =
new BufferedReader
(new FileReader(path)))
{ return bufReader.readLine(); }
}
...

bufReader is automatically
closed when the block exits

57

Java Exception Handling


Java exceptions are organized
as a class hierarchy

58

Java Exception Handling

Java exceptions are organized


as a class hierarchy
Handlers can be specified for
different exception subclasses

public class MyClass {


public void aMethod() {
try { ... }
catch
(IndexOutOfBoundsException i)
{ ... }
catch
(IllegalArgumentException e)
{ ... }
}

59

Java Exception Handling

Java exceptions are organized


as a class hierarchy
Handlers can be specified for
different exception subclasses

public class MyClass {


public void aMethod() {
try { ... }
catch
(IndexOutOfBoundsException i)
{ ... }
catch
(IllegalArgumentException e)
{ ... }
}

60

Java Exception Handling

Java exceptions are organized


as a class hierarchy
Handlers can be specified for
different exception subclasses

public class MyClass {


public void aMethod() {
try { ... }
catch
(IndexOutOfBoundsException i)
{ ... }
catch
(IllegalArgumentException e)
{ ... }
}

61

Java Exception Handling

public class MyClass {


Java exceptions are organized
public void method1() {
as a class hierarchy
try { method2(); }
Handlers can be specified for
catch (SomeException e) {
different exception subclasses
// do something w/exception
e.printStackTrace();
If a handler isnt specified for
}
the exception thrown, the next
matching handler up the
public void method2()
runtime stack get called
{ method3(); }

public void method3()


{ throw new SomeException(); }
}

62

Java Exception Handling

public class MyClass {


Java exceptions are organized
public void method1() {
as a class hierarchy
try { method2(); }
Handlers can be specified for
catch (SomeException e) {
different exception subclasses
// do something w/exception
e.printStackTrace();
If a handler isnt specified for
}
the exception thrown, the next
matching handler up the
public void method2()
runtime stack get called
{ method3(); }

public void method3()


{ throw new SomeException(); }
}

63

Java Exception Handling

public class MyClass {


Java exceptions are organized
public void method1() {
as a class hierarchy
try { method2(); }
Handlers can be specified for
catch (SomeException e) {
different exception subclasses
// do something w/exception
e.printStackTrace();
If a handler isnt specified for
}
the exception thrown, the next
matching handler up the
public void method2()
runtime stack get called
{ method3(); }

public void method3()


{ throw new SomeException(); }
}

64

Java Exception Handling

public class MyClass {


Java exceptions are organized
public void method1() {
as a class hierarchy
try { method2(); }
Handlers can be specified for
catch (SomeException e) {
different exception subclasses
// do something w/exception
e.printStackTrace();
If a handler isnt specified for
}
the exception thrown, the next
matching handler up the
public void method2()
runtime stack get called
{ method3(); }

public void method3()


{ throw new SomeException(); }
}

65

Java Exception Handling

public class MyClass {


Java exceptions are organized
public void method1() {
as a class hierarchy
try { method2(); }
Handlers can be specified for
catch (SomeException e) {
different exception subclasses
// do something w/exception
e.printStackTrace();
If a handler isnt specified for
}
the exception thrown, the next
matching handler up the
public void method2()
runtime stack get called
{ method3(); }

public void method3()


{ throw new SomeException(); }
}

66

Java Exception Handling

public class MyClass {


Java exceptions are organized
public void method1() {
as a class hierarchy
try { method2(); }
Handlers can be specified for
catch (SomeException e) {
different exception subclasses
// do something w/exception
e.printStackTrace();
If a handler isnt specified for
}
the exception thrown, the next
matching handler up the
public void method2()
runtime stack get called
{ method3(); }

public void method3()


{ throw new SomeException(); }
}

67

Java Exception Handling

public class MyClass {


Java exceptions are organized
public void method1() {
as a class hierarchy
try { method2(); }
Handlers can be specified for
catch (SomeException e) {
different exception subclasses
// do something w/exception
e.printStackTrace();
If a handler isnt specified for
}
the exception thrown, the next
matching handler up the
public void method2()
runtime stack get called
{ method3(); }

public void method3()


{ throw new SomeException(); }
}

68

Java Exception Handling

public class MyClass {


Java exceptions are organized
public void method1() {
as a class hierarchy
try { method2(); }
Handlers can be specified for
catch (SomeException e) {
different exception subclasses
// do something w/exception
e.printStackTrace();
If a handler isnt specified for
}
the exception thrown, the next
matching handler up the
public void method2()
runtime stack get called
{ method3(); }

public void method3()


{ throw new SomeException(); }
}

69

Java Exception Handling

public class MyClass {


Java exceptions are organized
public void method1() {
as a class hierarchy
try { method2(); }
Handlers can be specified for
catch (SomeException e) {
different exception subclasses
// do something w/exception
e.printStackTrace();
If a handler isnt specified for
}
the exception thrown, the next
matching handler up the
public void method2()
runtime stack get called
{ method3(); }

public void method3()


{ throw new SomeException(); }
}

70

Java Exception Handling

public class MyClass {


Java exceptions are organized
public void methodA() {
as a class hierarchy
...
Handlers can be specified for
}
different exception subclasses
public void methodB() {
If a handler isnt specified for
try { methodA(); }
the exception thrown, the next
catch (Exception e) {
matching handler up the
// do something w/exception
runtime stack get called
}
To handle every possible type
}
of exception, catch Exception

See developer.android.com/reference/java/lang/Exception.html
71

Java Exception Handling

public class MyClass {


Java exceptions are organized
public void methodA() {
as a class hierarchy
...
Handlers can be specified for
}
different exception subclasses
public void methodB() {
If a handler isnt specified for
try { methodA(); }
the exception thrown, the next
catch (Throwable e) {
matching handler up the
// Every recoverable runtime
runtime stack get called
// error and exception will
To handle every possible type
// be caught
of exception, catch Exception
e.printStackTrace();
}
To hancle every possible type of
}
error, catch Throwable

See developer.android.com/reference/java/lang/Throwable.html
72

Java Exception Handling

public class MyClass {


Java exceptions are organized
public void methodA() {
as a class hierarchy
...
Handlers can be specified for
}
different exception subclasses
public void methodB() {
If a handler isnt specified for
try { methodA(); }
the exception thrown, the next
catch (Throwable t) {
matching handler up the
// Every recoverable runtime
runtime stack get called
// error and exception will
To handle every possible type
// be caught
of exception, catch Exception
t.printStackTrace();
}
To handle every possible type
}
of error, catch Throwable

See developer.android.com/reference/java/lang/Throwable.html#printStackTrace()
73

Java Exception Handling

There are two types of exceptions:

74

Java Exception Handling

There are two types of exceptions: public class Vector<E> {

Checked exceptions

Methods declaring checked


exceptions require callers to
provide an exception handler

private void writeObject


(java.io.ObjectOutputStream s)
throws java.io.IOException {
...
}
...

See en.wikibooks.org/wiki/Java_Programming/Checked_Exceptions
75

Java Exception Handling

There are two types of exceptions: public class Vector<E> {

Checked exceptions

Methods declaring checked


exceptions require callers to
provide an exception handler

private void writeObject


(java.io.ObjectOutputStream s)
throws java.io.IOException {
...
}
...

76

Java Exception Handling

There are two types of exceptions: public class Vector<E> {

Checked exceptions

Methods declaring checked


exceptions require callers to
provide an exception handler

private void writeObject


(java.io.ObjectOutputStream s)
throws java.io.IOException {
...
}
...
void method1(Vector<Integer> v
ObjectOutputStream s) {
try { v.writeObject(s); }
catch (IOException ioe) {
...
}
}
...

77

Java Exception Handling

There are two types of exceptions: public class Vector<E> {

Checked exceptions

Methods declaring checked


exceptions require callers to
provide an exception handler

private void writeObject


(java.io.ObjectOutputStream s)
throws java.io.IOException {
...
}
...
void method1(Vector<Integer> v
ObjectOutputStream s) {
try { v.writeObject(s); }
catch (IOException ioe) {
...
}
}
...

78

Java Exception Handling

There are two types of exceptions: public class MyClass {

Checked exceptions
Unchecked exceptions

Can be thrown without a


method declaring it

public void methodA(int index) {


if (index < 0)
throw new
IndexOutOfBoundsException();
...
}
public void methodB() {
try { methodA(-1); }
catch (Exception e) {
throw new
RuntimeException(e);
}
}

See docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
79

Java Exception Handling

There are two types of exceptions: public class MyClass {

Checked exceptions
Unchecked exceptions

Can be thrown without a


method declaring it

public void methodA(int index) {


if (index < 0)
throw new
IndexOutOfBoundsException();
...
}
public void methodB() {
try { methodA(-1); }
catch (Exception e) {
throw new
RuntimeException(e);
}
}

80

Java Exception Handling

There are two types of exceptions: public class MyClass {

Checked exceptions
Unchecked exceptions

Can be thrown without a


method declaring it

public void methodA(int index) {


if (index < 0)
throw new
IndexOutOfBoundsException();
...
}
public void methodB() {
try { methodA(-1); }
catch (Exception e) {
throw new
RuntimeException(e);
}
}

81

Java Exception Handling

There are two types of exceptions: public class MyClass {

Checked exceptions
Unchecked exceptions

Can be thrown without a


method declaring it

public void methodA(int index) {


if (index < 0)
throw new
IndexOutOfBoundsException();
...
}
public void methodB() {
methodA(-1);
}

82

Java Exception Handling

There are two types of exceptions: public class MyClass {

Checked exceptions
Unchecked exceptions

Can be thrown without a


method declaring it

public void methodA(int index) {


if (index < 0)
throw new
IndexOutOfBoundsException();
...
}
public void methodB() {
methodA(-1);
}

83

Java Exception Handling

There are two types of exceptions: public class MyClass {

Checked exceptions
Unchecked exceptions

Can be thrown without a


method declaring it

public void methodA(int index) {


if (index < 0)
throw new
IndexOutOfBoundsException();
...
}
public void methodB() {
try { methodA(-1); }
catch (Exception e) {
throw new
RuntimeException(e);
}
}

84

Java Exception Handling

There are two types of


exceptions:

Checked exceptions
Unchecked exceptions

Can be thrown without a


method declaring it

public class MyClass {


public void methodA(int index) {
if (index < 0)
throw new
IndexOutOfBoundsException();
...
}
public void methodB() {
try { methodA(-1); }
catch (Exception e) {
throw new
RuntimeException(e);
}
}

85

Java Exception Handling

See docs.oracle.com/javase/tutorial/essential/exceptions
86

Overview of Java
Garbage Collection
87

Java Garbage Collection

Java has garbage collection, so memory


neednt be managed explicitly

88

Java Garbage Collection

Java has garbage collection, so memory


neednt be managed explicitly
Garbage collection makes writing
most applications much easier

See en.wikipedia.org/wiki/Garbage_collection_(computer_science)#Advantages
89

Java Garbage Collection

Java has garbage collection, so memory


neednt be managed explicitly
Garbage collection makes writing
most applications much easier
e.g., avoids dangling pointers,
double deletions, memory leaks,
etc.

Determining when to release memory is


especially hard when objects are used by
threads, processes, remote clients, etc.

90

Java Garbage Collection

Java has garbage collection, so memory


neednt be managed explicitly
Garbage collection makes writing
most applications much easier
There are disadvantages, however

See en.wikipedia.org/wiki/Garbage_collection_(computer_science)#Disadvantages
91

Java Garbage Collection

Java has garbage collection, so memory


neednt be managed explicitly
Garbage collection makes writing
most applications much easier
There are disadvantages, however
e.g., additional overhead & nondeterminism

92

Java Garbage Collection

Java has garbage collection, so memory


neednt be managed explicitly
Garbage collection makes writing
most applications much easier
There are disadvantages, however
Modern JVMs have sophisticated
garbage collection implementations

See www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01
93

You might also like