Home Previous Next

CSC110AB::Lecture Note::Week 15
Assignments | Handouts | Resources | Email Thurman {Twitter::@compufoo Facebook::CSzero}
GDT::Bits:: Time  |  Weather  |  Populations  |  Special Dates

Overview Assignment(s): All assignments have been assigned.
Code: FooInc.java | Factorial.java | Factorial.java (recursion) | RobotTester.java


Exceptions are "exceptional" conditions that can occur while a program is executing (i.e. running). Some exceptions are caused due to software defects (e.g. using a null object handle, or indexing beyond the bounds of an array).

   String s = null;
   String s1 = "hello";
   if (s.equals(s1)) { ... }     //this will cause an exception
   int[] array = new int[10];
   array[array.length] = 200;    //this will cause an exception

Exceptions are also generated by errors that are beyond the control of the program (e.g. the program needs to access a file that doesn't exist, or the program needs to fetch a webpage given an invalid [mal-formed] URL).

Exceptions can be "caught" by programs, but if an exception does occur that isn't caught, then the program (assuming it is non-graphical) terminates. (A GUI program returns to the user interface).

Exceptions are objects that are created from the Exception and RuntimeException classes.

   Error               Exception
   .....               /  ...  \
                  IOException   RuntimeException 
                    (checked)     (unchecked)

There are two categories of exceptions: checked and unchecked. Checked exceptions must be caught (otherwise, your program will not compile). Unchecked exceptions typically are not caught (i.e. they cause your program to terminate when they occur).

A method can throw an exception when it encounters a situation it cannot handle. There are numerous methods that come with the JCL (java class library) that throw exceptions.

A method declaration must contain a list of the the checked exceptions it may throw.

   public int someMethod() throws IOException, MalformedURLException

A method does not need to declare RuntimeException inherited exceptions that it may throw.

If a method overrides a method from a parent class, then the child method cannot throw more checked exceptions that the parent method does.

A method can say it throws exceptions that it really doesn't throw.

Catching an Exception

Whenever a method is called that throws a checked exception, then that method call must be called from within a try block and an exception handler (catch block) must be implemented.

   try {
   } catch (IOException e) {

If an exception occurs, then the flow control of the program jumps to a catch block. All remaining statements, if any, within the try block are skipped. If no exception is thrown, then the catch blocks are skipped.

A try block must be a compound statement. Ditto for the catchblocks.

The catch blocks are passed an argument: a reference to the exception (which may or may not be used).

Throwing an Exception

An exception is thrown as follows.

   throw new EOFException();


   throw new EOFException("file's empty");
      //supply additional information about the exception
      //this information can help the client "fix" the problem

A method that throws an exception does not return to the caller.

An exception can be re-thrown. You may want to do this in the event an exception occurs: you catch it locally to clean up any locally allocated objects and/or system resources, and then "pass" the exception on to those who know about handling it.

Exception A can be caught, and exception B can be thrown.

Creating an Exception Class

You can create your own exceptions by extending Exception or some child class of Exception.

   class MyException extends Exception {
      public MyException() {}
      public MyException(String msg) { super(msg); }

The following exception terminology was obtained from Just Java by Peter van der Linden:

Note Java Other Languages
An error condition that happens at run time Exception Exception
Causing an exception to occur Throwing Raising
Capturing an exception that has just occurred, and executing statements to resolve it in some way Catching Handling
The block that does this Catch clause Handler
The sequence of call statements that brought control to the method where the exception happened Stack trace Call chain
Miscellaneous Comments

Detect errors at a low level, handle them at a high level.

Use exceptions only for exceptional situations.

YouTube.com::CS 61B Lecture 14: Exceptions

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)

Abstract Classes and Methods

An abstract class is one that is used for derivation only. Objects cannot be instantiated from an abstract class. Attempting to do so at compile-time is a syntax error. Attempting to do so at run-time causes an error.

An abstract class can contain data and methods. Some of the methods may in turn be declared to be abstract. Abstract methods have no implementations.

If a class contains an abstract method, then it must be an abstract class. However, you can have an abstract class that doesn't have any abstract methods.

An abstract method is a method that is declared, but the method's implementation is found in one of the derived classes. In otherwords, the classes that extend an abstract class are responsible for providing implementations of the abstract methods.


      abstract class SomeClassName { ... }

The Number class in the java.lang package represents the abstract concept of numbers. It is used as a superclass to the wrapper classes (e.g. Integer and Float).

   public abstract class Number implements java.io.Serializable {
       public abstract int intValue();
       public abstract long longValue();
       public abstract float floatValue();
       public abstract double doubleValue();
       public byte byteValue() { return (byte)intValue(); }
       public short shortValue() { return (short)intValue(); }

Each wrapper class (e.g. Byte, Integer, etc.) extends Number (except for Character).

The Number class ensures that there is common functionality across all classes that extend it (e.g. intValue()).

Every class that inherits from Number must implement the methods that are defined to be abstract. The Number class contains a couple of non-abstract methods (shortValue() and byteValue()); in other words, these methods are implemented in the class. If you were to write a class that extends Number, then you would have to check to see if the non-abstracts methods work for you specific type of number. If they don't, then you can provide implementations for the non-abstract methods by overriding them.

You cannot instantiate a Number object. You can, however, have a handle (i.e. object variable) to a Number object (e.g. Number num). The values that can be assigned to a Number object variable are handles to objects instantiated from classes that extend the Number class.

   Number num = new Integer(100);  // a typecast is not necessary

Docs.Oracle.com::Tutorial::Abstract Methods and Classes

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)


From the The Java Programming Language by Arnold, Gosling, Holmes.

The fundamental unit of programming in Java is the class, but the fundamental unit of object-oriented design is the type. Interfaces define types in an abstract form as a collection of methods or other types that form the contract for that type.

An interface is defined using the keyword interface rather than class.

An interface contains no instance variables, nor does it contain any method implementations. You cannot create instances of an interface.

   interface Foo { ... }

   //! Foo f = new Foo();   // not legal

An interface can declare three kinds of members:

All interface members are implicitly public.

A class guarantees to implement the methods of an interface by using the implements keyword when the class is defined.

   class X implements Y

Any class that implements an interface must define (i.e. implement) the methods, if any, declared in the interface.

A class can implement more that one interface. In addition, a class can extend another class and still implement one or more interfaces.

   class X implements Y, Z { ... }
   class X extends A implements Y, Z { ... }

To an extent, interfaces support the concept of multiple inheritance.

Common interfaces from the java.lang package:

An interface can be used to "tie" together classes that are in separate inheritance trees.

                Assignment               Interface:  Submitable
            Exam   Program   Homework
            ...    ...       ...

              Game                       Interface:  Submitable
  Guessing  Yahtzee   Blackjack
  ...       ...       ....

Another example...

An interface can be used to encapsulate a collected of related manifest constants (i.e. simulate an enum in C).

   interface ExitStatus {
      int EXIT_SUCCESS = 0;
      int EXIT_FAILURE = 1;

When an interface declares named constants, then they are implicitly defined to be public, static, and final. [blank finals are not allowed]

Methods declared in an interface are implicitly abstract.

An interface can extend (i.e. inherit) other interfaces.

   interface Sortable { ... }
   interface Searchable { ... }
   interface Container extends Sortable, Searchable { ... }
Any class that implements interface Container must also implement the Sortable and Searchable interfaces.

Although you cannot instantiate an object using an interface, you can use an interface as the type for variable and assign to that variable any object whose class implements the interface. This allows for polymorphic run-time binding.

   interface Container { ... }

   class List implements Container { ... }

   List list = new List();
   Container c = list;  // list is a container

From a naming convention perspective, many interfaces have a -able suffix applied to them.

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)

Object Serialization

Any object that implements the Serializable interface can be turned into a sequence of bytes that can be restored fully into the original object.


The Serializable interface is used as a flag -- it has no methods. Some objects may not want to be serialized.

To serialize an object you create some sort of OutputStream object and wrap it inside an ObjectOutputStream object. Then, the object can be serialized by calling writeObject(). Reversing the process is accomplished by creating an InputStream inside a ObjectInputStream and calling the readObject() method.

When an object is serialized, so are all the references it may contain to other objects.

- Object Serialization (java1.1)
   * useful for saving the state of an application/applet
   * objects serialized/deserialized with  ObjectOutputStream  and
     ObjectInputStream, respectively, using the  writeObject()  and
     readObject()  methods
   * primitive types written to stream as if using DataOutputStream;
     otherwise,  writeObject() is called recursively to serialize
     other objects (arrays, strings, objects) -- infinite recursion
     is not a problem (so they say); can end up with an entire
     graph object serialized
   * not all objects can or should be serialized
   * a class is serialable iff it implements Serializable 
      (or Externalizable); no methods defined -- it is a
      marker interface
   * Component implements Serializable; thus, all AWT components
     can be serialized
   * transient  indicates that a field should not be serialized
   * custom serialization is accomplished by overriding  writeObject()
     and  readObject(), and by using  defaultWriteObject()  and
     defaultReadObject() -- note: they must be declared  private
   * classes are assigned a version # -- cannot deserialize a
     class that has a different version # than what was used when
     it was serialized;  'serialver'  program
        + static final long serialVersionUID = 19971209L;
   * serialized applets
      + <applet code=appletName.ser ...>
      + applets can be shipped in a pre-initialized state
   * Externalizable
      + ObjectOutputStream and ObjectInputStream use the
         writeExternal() and readInternal() methods instead
         of writeObject() and readObject(); allows the class
         to take complete control over writing/reading their state

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)

Object Cloning

Objects cannot be cloned unless they are created using a class that implements the Cloneable interface.

For a class to use the default implementation of Object.clone(), it must implement the Cloneable interface.

The Cloneable interface is an empty interface -- it is used as a tag only. In many cases, classes that can be cloned override Object.clone().

Object.clone() does a bit-wise copy, which works fine for primitive types, but not necessarily with references. Only individual classes know how to be cloned (if at all). By default, a shallow copy is done versus a deep copy.

If an attempt is made to clone an object that is not cloneable, then the CloneNotSupportedException exception is thrown. This is a checked exception; therefore, it must be caught.

It is common for cloneable classes to override clone() so as to make it public rather than protected.

   The Population class extends class X (which is cloneable), and it
   contains numerous primitive types and a bunch of object references:

      try {
         Population p = (Population)super.clone();
         p.name = new String(getName());
         p.growthRate = (GrowthRate)growthRate.clone();
         p.density = (Density)density.clone();
         return p;
      } catch (CloneNotSupportedException e) { return null; }

From the CoreJava book.

Why clone? You never want to return a mutable object as the value of a method because this violates encapsulation. As a rule of thumb, always use clone whenever you need to return a copy of a mutable data field.

When you start dealing with objects instantiated from classes that you do not know well, then how they clone becomes an unknown.

Here is an example of a program that will result in the throwing of a CloneNotSupportedException.

   class A {
      int a;
      public A (int i) { a = i; }
      public Object clone() throws CloneNotSupportedException {
         return super.clone();
   public class Main {
      public static void main(String[] arg) {
         A a1 = new A(260);
         try {
            A a2 = (A)(a1.clone());
         } catch (CloneNotSupportedException e) {}

      The execeptions occurs because class A calls Object.clone(),
      but it does not implement the  cloneable  interface.

{TopOfPage} {Oracle.com::API Specification | Tutorial} {GDT::Java Resources} {Eclipse IDE} {Udacity} {udemy} {CodingGround (online IDE)

Home Previous Next