Computer Programming II

COP 3337

Spring Semester 2008

Read this first!

NOTE:

Students must bring printed copies of all class handouts and sample programs to class.

Class handouts are in MS Word '97 format.
Sample programs are plain text .java files and can be downloaded and run.
(Programs have all been tested and contain no syntax or logic errors.)

Additional files may be posted throughout the semester.

This web page is intended to supplement the textbook Big Java by Cay Horstmann.


Table of Contents


Got Java?

   Java 2 Software (Essential) - 51.76 MB

Also known as the Java 2 Development Kit (JDK), from Sun Microsystems (freeware)

  1. After you follow the link above, make sure you scroll down and click the Download button to the right of the heading "JDK 5.0 Update 14"
    • Make sure you get the JDK and not the JRE!
    • Do not click the "Get the JDK Download" link at the top of the page!

  2. Click the Windows Offline Installation, Multi-language link to begin the download (unless you are running Linux)

   NetBeans 6.0 IDE (Essential) - 21 MB

Click the Download button under the Java SE column
Note: You must install the Java 2 software (above) before installing NetBeans

   Java Documentation (Strongly Recommended) - 44.05 MB

Also from Sun, the official Java 2 Language Documentation, in HTML format

Follow the link above, scroll down to the heading "J2SE 5.0 Documentation "and click the Download button

Top               Home


Before Beginning (Class policies, etc)

   How to be Successful in This Class
A word to the wise...
   Class Policies
Official class rules regarding late assignments, makeup tests, partial credit, etc., and School of Computer Science policy on Incompletes and Academic Honesty
   Using the NetBeans IDE
Top               Home


Textbook Resources - Big Java, Third Edition

    Source Code for Programs in the Textbook
Right-click the link above and choose "Save Target As..." (or "Save Link As...") to download a "zip" file of all the programs in the book

    Answers to Review Exercises
       [Ch. 1] [Ch. 2] [Ch. 3] [Ch. 4] [Ch. 5] [Ch. 6] [Ch. 7] [Ch. 8]
       [Ch. 9] [Ch. 10] [Ch. 11] [Ch. 12] [Ch. 13] [Ch. 14] [Ch. 15]
       [Ch. 16] [Ch. 17] [Ch. 18] [Ch. 19]

    Bug List
Author's list of all known errors in the book
    Help with IDE's
How to use all major Java IDE's, including NetBeans, Eclipse, and JCreator
    Big Java
Link to the home page for the book
Top               Home


1.) Style and Documentation Standards for Java Programs (Appendix A)

   Programming Style
Conventions for creating readable code
   Internal Documentation
Internal documentation consists of comments - included in your Java code - that explain what you are doing and how you are doing it. This is an absolute necessity in the real world where a programmer may be called upon to debug or modify code written by someone else
   Java "Documentation Comments"
When a class contains Java "documentation comments" you can run the javadoc utility to create a neat set of HTML "help" pages for that class
   Using the javadoc Utility Program
How to use the javadoc utility to automatically generate HTML "help" pages your classes. These pages will have the same format as the official Java Language Documentation from Sun Microsystems
Top               Home


2.) Data Files and I/O Review (Sections 19.1 and 19.2)

   Using the Scanner Class for Interactive Input
Basics of interactive input and introduction to the new Java 1.5 Scanner class
   InputDemo.java
Demonstrates Scanner methods next(), nextInt(), and nextDouble()
   Working With Data Files in Java
Basic file concepts and how to read and write text files in Java programs
   FileIO.java
Basic input and output of text files. Uses Scanner methods hasNext() and nextLine() to read lines of text until end-of-file. For each line read, the individual tokens are extracted via Scanner methods hasNext() and next() , and written to an output file. The output file is created using the FileWriter and PrintWriter classes

   Assignment #1 - Review (ArrayLists)
Garage.dat (Data file for this assignment)

   Review Program - List Processing
BankAccount.java | Bank.java | BankTester.java
The Bank class contains a list of BankAccounts (using an ArrayList) and demonstrates list processing. The BankTester class reads data until eof using Scanner, creates BankAccount objects using the data, adds the objects to the Bank, and calls the Bank class methods

   Align.java (optional)
Easy-to-use class for formatted output
   Align.html (optional)
"Help" pages for the Align class, generated by javadoc
   Formatted Output (optional)
Java's NumberFormat class makes it easy to print floating-point numbers rounded to any number of decimal places, or formatted as currency
   GUI_Example.java (optional)
Intro to some components of Java's "Swing" class: Input and Message (output) dialog boxes, and the JTextArea (a scrollable, output window of a specified number of rows and columns)
Top               Home


3.) The Java Array (Sections 7.1 and 7.5 - 7.7)

   Intro to the Java Array
Basic array concepts, array elements and indices (i.e., subscripts), array vs. ArrayList, array declarations and initializations, traversing an array, and the length instance variable
   Random Numbers
Java's Random class makes it easy to generate random numbers - floating-point numbers, integers, and integers within a specified range
   ArrayDemo.java
Shows a class with an array instance variable, the length instance variable of the array class, basic array traversals using a for statement, and sorting an array using the selection sort algorithm. Also, generating random integers
   Arrays Class Methods
Static Arrays class methods fill, sort, binarySearch, and equals, and System method arraycopy
   ArraysMethodsDemo.java
Shows major methods of Arrays class and System method arraycopy
   PartiallyFilled.java
Shows how to use a counter to keep track of the number of elements used in a partially-filled array. Also shows how to "resize" an array if it becomes full, a linear search, and the Java 1.5 Scanner class
   The Binary Search
The binary search is much more efficient than the linear search, but can only be done on a sorted array
   VoteCounterTest.java
The VoteCounter class has a 2-Dimensional array instance variable and uses nested for statements to traverse the array both by rows and by columns. Also shows how to use the Java 1.5 Scanner class to read from data files and from the keyboard
   Votes.data
Data file read by VoteCounterTest program (above)
   Irregular2D.java
Since a 2D array is really a 1D array of 1D arrays, each "row" can have a different number of "columns" (i.e., different elements can point to arrays of different sizes)

   Assignment #2 - Multi-Dimensional Arrays
Top               Home


4.) Designing Classes (and more) (Chapter 8)

   OOP Concepts
Classes and objects, instance variables and memthods, class implementation vs. class interface, reusability, information hiding, encapsulation, inheritance, polymorphism, etc.
   Object-Oriented Analysis and Design
How to analyze a problem in an object-oriented manner and design an object-oriented solution
   Some Class and Program Design Guidelines
Cohesion good, coupling bad! (Side effects bad, too!)
   Stepwise Refinement (aka: "Method Decomposition")
The answer to the time-honored question, "Where do methods come from?"
   ParamPasser.java
Simple program demonstrates how primitive-type arguments are always passed by value (as are all arguments in Java)
   ParamPasser2.java
Program demonstrates how object variables --- which in Java store object references--- are always passed by value
   The Assignment Statement in Java
What Java's "=" operator means
   AssignmentDemo.java
Using "=" with objects
   SendInTheClones.java
To enable users of a class to make copies of objects, the class should override the clone method of the Object class
   Method Overriding
We override methods inherited from a superclass in order to provide a more appropriate implementation for objects of the subclass
   The toString Method
Overriding toString lets you use an object variable where Java expects to find a string, e.g., as the argument to print or println. The string returned by toString is then used in place of the object
   Testing for Equality
Explains Java's "==" operator and the equals() method
   NoOverriding.java
Shows that "==" when applied to objects compares the object references and not the actual objects "pointed to." Also shows the behavior of the inherited (i.e., not overridden) toString and equals() methods
   YesOverriding.java
Shows how to override method equals() so that it indicates whether the objects themselves --- and not the object references --- are equal. Also shows how toString is typically overridden
   Static Class Members
Static "class variables" and static methods, explained
   StaticDemo.java
Demonstrates class variables vs. instance variables, and static methods
   The this Reference
What this is, how it is used, and when it must be used
   TimeTester.java
Shows how this is used to access instance variables and call methods, to avoid "shadowing" caused by name conflicts, to enable a method to return a reference to the object for which it was called (enabling "chaining" of method calls), and to allow one constructor to call another constructor of the same class
Top               Home


5.) Interfaces and Polymorphism (Chapter 9)

   Packages
When related classes are stored in packages, they are easily reused via the import statement
   Introduction to Interfaces
Interface concepts, syntax, and rationale, and how to write classes that implement (i.e., "realize") an interface
   Polymorphism
What it is and how it promotes software extensibility. "Early binding" vs. "late binding" and how late binding enables polymorphism

   Animal.java
This file contains the Animal interface and a few classes that implement it
   The SeniorCitizenMacDonald Class
The S.C.Mac class "depends on" the Animal interface, but cares not about the specific classes that implement it. So new classes can be added to the system with no modification of S.C.Mac. Shows polymorphism

   Assignment #3 - Interfaces and Polymorphism

   These CH files show an interface, classes that implement it, and polymorphism
Measurable.java - An interface
DataSet.java - a class that depends on the Measurable interface
BankAccount2.java - a class that implements the Measurable interface
Coin.java - another class that implements Measurable
DataSetTest.java - test class

   Converting Between Types
Converting to an interface type from a class that realizes the interface is always a safe operation. Converting in the other direction is not, so an explicit cast is required...
   The Comparable Interface
Objects of a class that implements the Comparable interface may be compared to one another, based on their "natural order." You get to say what the natural order is when you implement the compareTo method
   Rational.java
A class to represent Rational numbers (i.e, any number that can be expressed as a fraction). The class implements the compareTo method to order Rationals by their decimal values. Also overrides toString and equals, and shows how to call one constructor from another of the same class
   RationalSortAndSearch.java
A test class for the Rational class. Shows how to call compareTo, and how you can use the Arrays class sort and binarySearch methods with arrays of objects of any class, as long as that class implements Comparable
   Inner Classes
An inner class is a class defined inside another class

   These CH files show how to use an inner class to implement a "strategy interface"
Measurer.java - The interface
DataSet2.java - A class that depends on Measurer
DataSetTest2.java - Test class has an inner class that implements Measurer

   The Comparator Strategy Interface
Suppose you want to compare objects of a class that does not implement Comparable. If you don't own the class, then you can't make it implement Comparable. Or suppose that a class does implement Comparable but you want to provide an alternate way to order the objects of the class. In these cases you need to implement the Comparator interface, as an inner class
   ComparatorTest.java
Implements Comparator and its compare method to enable comparisons of Rectangle objects. Also shows overloaded versions of Arrays class methods sort and binarySearch
Top               Home


6.) Inheritance and Polymorphism (Chapter 10)

   CompositionDemo.java
Class composition is where one class has an instance variable - commonly called a "member object" - that is an object of another class. This has nothing to do with inheritance, but it is another way to reuse an existing class. Shows how the member object is initialized by calling its constructor from the constructor of the "containing" class
   Inheritance
Superclasses and subclasses, ways to differentiate a subclass from its superclass, keywords extends and super, calling the superclass constructor from the subclass constructor, and calling superclass methods for subclass objects

   These CH files demonstrate "subclassing" and inheritance
BankAccount.java - The superclass
SavingsAccount.java | CheckingAccount.java - Two subclasses of BankAccount
AccountTest.java - Test class for the BankAccount hierarchy

   Abstract Classes and Methods
Definition, purpose, and syntax requirements of abstract classes and methods
   More on Inheritance
Protected access control, more on method overriding, and the final word on the final keyword

   Assignment #4 - Inheritance and Polymorphism
Top               Home


7.) Java Collections and The ArrayList and LinkedList Classes (Sections 7.2 - 7.4 and 15.1)

   Intro to Java Collections
Interface List is derived from interface Collection, and classes ArrayList and LinkedList implement the List interface. Explains Collection method iterator(), and iterator methods hasNext, next, and remove. Also, List methods add, addFirst, addAll, get, set, size, remove, clear, contains, isEmpty, and subList. Also, how to convert a fixed-size array to a List
   CollectionDemo.java
Demonstrates the major List and Iterator methods
   ArrayAsList.java
Uses asList() to get a "list view" of an array and then applies List methods get() and set()
   The Enhanced for Statement (aka: the "for each" statement)
To access each object in a collection or array, we can use the "enhanced for" statement, which requires a bit less coding than the familiar for statement
   LinkedListDemo.java
Demonstrates Collections methods sort, reverse, shuffle, binarySearch, min, and max, and Arrays class method asList. Also shows how to use the value returned by binarySearch to insert an object in its proper place in a sorted list. Also, the "enhanced for" statement
   ListIteratorDemo.java
Shows List method ListIterator, and ListIterator methods hasNext, next, hasPrevious, previous, and remove
Top               Home


8.) Intro to Data Structures: Creating Generic Classes, Linked Lists, Stacks, and Queues (Chapters 15 and 17)

   BogusList.java
A simple generic list class ADT with limited functionality. "Genericity" is implemented in the ancient (pre-Java 1.5) manner - by designing the list to store objects of class Object. Also demonstrates the OOP principle of "information hiding" by providing an iterator to enable clients to traverse the list without having to know any of the implementation details
BogusListTester.java - test class

   BogusList2.java
New, improved version of BogusList class achieves genericity via "type variables"
BogusListTester2.java - test class

   List Primitives
The most basic operations on linked lists: isEmpty(), insertAfter(), and deleteAfter()

   MyLinkedList.java
Yet another version of the BogusList class (#3, but who's counting?). This time, the implementation has been changed to a programmer-defined linked list (not a java.util.LinkedList). Hey kids, learn how to create your own data structures!
MyLinkedListTester.java - test class

   TrailingPointerDemo.java
An old trick is to have two pointers traversing a list simultaneously, with the "trailer" always one node behind the "leader". Then, to delete the node pointed to by the leader, we do a deleteAfter using the trailer...
TrailingPointerDemoTest.java - test class

   Assignment #5
An ordered list class
ordlist.txt (Data file for this assignment)

   Stacks
Stack concepts, operations, and examples
   Stack1.java
A generic Stack class with array implementation and methods push, pop, peek, and isEmpty
StackTester1.java - test class
   Node.java
The generic Node class (see MyLinkedList.java) stored in a separate file. "Friendly" (i.e., "package") access is used so that Nodes are accessible to all classes in the same package, but not to those outside the package
   Stack2.java
Version 2 of generic Stack class has linked implementation
StackTester2.java - test class

   Queues
Queue concepts, operations, and examples
   Queue.java
A generic Queue class with array implementation and methods append, serve, and isEmpty
QueueDemo.java - test class
   Queue2.java
Version 2 of the generic Queue class has linked implementation
QueueDemo2.java - test class
Top               Home


9.) Recursion (see recursion) (Chapter 13)

   Recursion
The basics of recursion. Includes the "Secret of Recursion"
   FactTest.java
The "canonical" example: a class to compute the factorial of a number
   RecursionExamples.java
A bunch of assorted recursive methods, some using arrays. Every one guaranteed different!
   TowersOfHanoi.java
The "Towers of Hanoi" is a classic example of more advanced recursion
   Recursion Homework
For class discussion next class
   BlobCountTest.java
A good example of a problem solved more easily using recursion
   Queens8.java
Another classic example of more advanced recursion, finds all 92 solutions to the "Eight Queens Problem." Demonstrates backtracking

   Assignment #6 (Recursion)
Top               Home


10.) Exception-Handling (Chapter 11)

   Introduction to Exception-Handling
Benefits of exception-handling, the three components of exception-handling: try blocks, the throw statement, and catch blocks, and exception specifications (aka: "throw lists")
   NeverCaught.java
Uses the RuntimeException class to show what happens if an exception is not caught
   SimpleExceptionDemo.java
Shows programmer-defined exception class with default constructor, exception specifications (aka: "throw lists") and the three components of exception-handling: try, throw, and catch. Calls method printStackTrace for the exception object thrown
   ExceptionsExample.java
When an exception is thrown, the stack of method calls is "unwound" looking for a method with a handler for the class of the exception thrown
   FullConstructors.java
Creates a new exception class with default and string-argument constructors. Throws an exception and passes a string to the constructor. When the printStackTrace() method is called for the exception, the string is printed
   More on Exception-Handling
Checked vs. unchecked exceptions, creating your own exception classes, exception class constructors, and the finally clause
   AlwaysFinally.java
Shows that a finally clause is always executed

   Exceptions - a Complete Example

BadDataException.java | DataSetReader.java | DataSetTester.java

BadDataException.java defines a new exception class

DataSetReader.java has a method called readFile() which reads a file and returns an array containing the values read. Various types of exceptions are thrown if the file cannot be found or is ill-formed in any of a number of ways

The test class - DataSetTester.java - catches the exceptions which may be thrown in the DataSetReader class and resumes execution

The data files tested: bad1.dat | bad2.dat | bad3.dat | bad4.dat | good.dat

   Assignment #7 - For "Extra Credit" Only
Exception-Handling
BankAccount.java
Top               Home