Home Previous Next

CSC205::Lecture Note::Week 03
Assignments | Code | Handouts | Resources | Email Thurman | Tweets::@compufoo
GDT::Bits:: Time  |  Weather  |  Populations  |  Special Dates

Overview Assignment(s)
  1. [assessment] #VintonCerf [due 2/6/2017]
  2. [program] #ValleyPeak [due 2/11/2017]
  3. [program] #RecursionPlay [due 2/18/2017]
Code PolyNumber.java {continued} | XYZ.java | A.java (arrays) | Exceptions.java | TestExceptions.java | Rot13.java


Arrays

An array is a aggregate (collection, set, group, list) of individual data values with two characteristics: it is ordered and homogeneous.

The following are some array-related terms:

An array is homogeneous because each element must be of the same type. Example: an array of int values, an array of float values, an array of char values, and array of Object values (handles, references, pointers).

An array is ordered because it has a 1st element, a 2nd element, a 3rd element, and so on. Array elements are probably stored in contiguous memory locations [this is definitely true in C and C++; in Java it is left up to the JVM implementors].

Here is a list of items you should understand when using arrays:

Defining an Array of Primitive Types

The following creates an array of long values:

   long[] ssNbrs;      // an array of social security numbers

      // ssNbrs is an object variable that is going to point to
      // an array of  long  values; at this point and time, it 
      // doesn't point to anything (i.e. it is equal to  null)

   ...

   int n = fooA();    // get the array length somehow

   ...

   ssNbrs = new long[n];

      // array length is decided at run-time (i.e. we don't know
      // the array length at compile-time; the information is
      // obtained from a user, or from a database file, etc.)
      // two things occur when an array is defined:  memory is
      // allocated from the heap and the memory is initialized
      // to the appropriate default values  [0 for integral and
      // floating-point types,  false  for  boolean  arrays, and
      // null  for arrays of object references]

   ...

   for (int i = 0; i < ssNbrs.length; i++)
      ssNbrs[i] = -1L;  // initialize each element to -1

      // use the  <  relational operator is important; a common
      // programming defect is to use the  <=  operator -- what
      // would happen if we did?

   ...

   ssNbrs = new long[2 * n];

      // after an array has been created, its length if fixed; if you
      // need more elements, then you need to create a new array;
      // now  ssNbrs  references (i.e. points to) an entirely
      // different array of long values; the original array still
      // exists, but the reference to it has been lost and it are
      // not able to copy the original values into the new array

   long[] orig = ssNbrs;
   ssNbrs = new long[n * 3];

   for (int i = 0; i < orig.length; i++) ssNbrs[i] = orig[i];

      // the handle to the original array is stored in the array variable
      // named  orig.  The new array is allocated and the contents of
      // the original arrray is copied to the new array

   System.arraycopy(orig, 0, ssNbrs, 0, orig.length);

      // arraycopy(Object src, int srcOffset, 
      //           Object destdst, int destOffset, int count);
      //
      // the  arraycopy()  method copies a region of one array, src,
      // beginning at element  srcOffset, to another array, dst,
      // beginning at element  destOffset;  count  elements are copied.
      // note:  the arrays must already be allocated

   Tip:  In the control-EXPR of the loop, I'm better off using
         ssNbrs.length  rather than the variable  'n'  because 
         since 'n' is a variable, it could be modified such that 
         the EXPR  n == ssNbrs.length  is not true.
Defining an Array of Objects

The following code snippet an array of object variables.

   Integer[] iArray;

      // iArray  is a reference (handle, pointer) to an array of 
      // Integer references -- at this point and time, it doesn't
      // "point" to any array

   ...

   iArray = new Integer[10];

      // array length is known compile-time; an array to store 
      // 10 Integer references is created; each array element is 
      // initialized to   null   (recall,  null  is a Java keyword)

   ...

   for (int i = 0; i < iArray.length; i++)
      iArray[i] = new Integer(i);

         // an  Integer  object is created and a reference to it is
         // stored in  iArray; when the Integer object is created,
         // it is initialized to the value of 'i'...

Arrays are always stored on the heap. The reference to the array will be stored either on the stack or in the data segment depending on where it is defined.

The following are some comments on the efficiency of arrays:

Arrays.java | A.java

{TopOfPage} {Oracle.com::API Specification | Tutorial} {Derek Banas Videos}


Exceptions

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.

          Throwable
             |
   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 {
      ...
      someMethodThatThrowsIOException();
      ...
   } 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();

         or

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

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} {Derek Banas Videos}


Multi-dimensional Arrays

Multi-dimensional arrays are arrays-of-arrays. Example: a two-dimensional array is an array of one-dimensional arrays.

   int someArray[][];  // someArray  will reference an array whose elements
                       // are of type:   array-of-int

   /*
    * create a 4 element array of 4 element int arrays
    */
   someArray = new int[4][];        // create a 4 element array
   for (int i = 0; i < 4; i++)
      someArray[i] = new int[4];

   int[0][0]  int[0][1]   int[0][2]   int[0][3]
   int[1][0]  int[1][1]   int[1][2]   int[1][3]
   int[2][0]  int[2][1]   int[2][2]   int[2][3]
   int[3][0]  int[3][1]   int[3][2]   int[3][3]

   /*
    * create a 4 element array of variable length int arrays
    */
   a = new int[4][];
   for (int i = 0; i < 4; i++)
      a[i] = new int[i+1];

   int[0][0]
   int[1][0]  int[1][1]
   int[2][0]  int[2][1]  int[2][2]
   int[3][0]  int[3][1]  int[3][2]  int[3][3]

   The EXPR  a[i]  accesses the  i'th   one-dimensional array.

   The following code snippet creates a 2x3 table of Foo objects.

      Foo[][] foo = new Foo[2][3];
      for (int i = 0; i < foo.length; i++) 
         for (int j = 0; j < foo[i].length; j++)
            foo[i][j] = new Foo();

   or

      Foo[][] foo = new Foo[2][];
      for (int i = 0; i < foo.length; i++)  {
         foo[i] = new Foo[3];
         for (int j = 0; j < foo[i].length; j++)
            foo[i][j] = new Foo();
      }

Excluding some mathematical and scientific computing, multi-dimensional arrays rarely exceed two dimensions.

MultiArrays.java

{TopOfPage} {Oracle.com::API Specification | Tutorial} {Derek Banas Videos}


class Vector

class Vector is data structure found in the java.util package that is used to store a variable number of object variables (pointers).

A vector object is useful when you have a collection of objects, but don't how many objects need to be stored.

Some of the more commonly used methods:
   int size();
      //determines the number of elements in the vector

   boolean isEmpty();
      //returns true if the vector has no elements; false otherwise

   void addElement(Object obj);  
      //adds the  obj  to the end of the vector

   boolean contains(Object obj);
      //searches the vector for  obj

   Object elementAt(int index);
      //0-based index of the element to retrieve [0 <= index < size()]

   boolean removeElement(Object obj);
      //removes the 1st occurrence of  obj  from the vector
      //returns true of obj found; false otherwise
      //if obj removed, all remaining elements are shifted down

   void removeElementAt(int index);
      //0-based index of the element to remove
In many cases, when you get an element from a vector, you will typecast it to the appropriate type.
   Date d = new Date();
   Vector v = new Vector();

   v.insertElementAt(d, 0);
      //insert Date object as the 1st element

   Object o = v.firstElement();
      //get the 1st element from the vector

   d = (Date)o;
      //convert the object pointer returned from  firstElement
      //to its appropriate type...

Oracle.com::class Vector<E>

TestVector.java

Via Oracle.com: "Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector."

class ArrayList is "roughly equivalent to Vector, except that it is unsynchronized." [via Oracle.com]

Oracle.com::class ArrayList<E>

ArrayListDemo.java

{TopOfPage} {Oracle.com::API Specification | Tutorial} {Derek Banas Videos}


The instanceof Operator

The instanceof binary operator (i.e. has two operands) is used to test if an object variable is an instance of a specific class. The operator evaluates to true or false.

   void foo(Object o) {
      if (o instanceof String)
         System.out.println("the Object is type String");
      else if (o instanceof StringBuffer)
         System.out.println("the Object is type StringBuffer");
   }

The left operand is either an object variable or an array element, while the right operand must be a class name, interface name, or array type.

{TopOfPage} {Oracle.com::API Specification | Tutorial} {Derek Banas Videos}


Home Previous Next