Computer Programming II

COP 3337

Spring Semester 2019

Read this first!

Online notes are in MS Word '97 format.
Sample programs are .java files.
All programs have been tested and contain no syntax or logic errors.

Additional files - including all assignments - will be posted throughout the semester.

Table of Contents

Got Java?

   Java Software (Essential) - Also known as The Java SE Development Kit or JDK

  1. Click the link above, then scroll down and click the link for "Java SE development Kit 8u192"
  2. Accept the licensing agreement
  3. Choose the version for your operating system
  4. After downloading, double-click on the file icon to install
  5. Note that there are two links for Windows - one for 32-bit Windows and another for 64-bit. The 32-bit version will run on all Windows. To see what version of Windows you have, click the Start button, then Control Panel > System and Security > System

Note: You must install Java before installing NetBeans

   NetBeans IDE (Essential)

Click the link above, choose your preferred language and platform, and then click the Download button under the "Java SE" column

   Java Language Documentation, in HTML Format (Strongly Recommended)

Click the link above, then scroll down and under "Additional Resources," click the Download button for Java SE 8 Documentation

Click here to view the documentation online

Top               Home

Textbook Resources - Big Java, 6th Edition - Early Objects

Recommended: The "e-book," (download + online version of the book) which provides valuable "hands-on" resources with instant feedback,
including short programming exercises and practice quizzes.

Also available in loose-leaf and bound paperback formats. All formats available in FIU Bookstore or from Wiley

    Big Java 6 Home Page
  • Student Companion Site and access instructions
  • Source code for all sample programs (in downloadable .zip format)
  • Bug List - all known errors in the book
  • Tech support and help

    Answers to Review Exercises - 6th Edition
All Chapters

    Answers to Review Exercises - 5th Edition
[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]

Top               Home

Before Beginning (Class policies, etc)

   "Placement" Assignment - Optional
Will be explained in class
CD-Data.txt - input file

   How to be Successful in This Class
A word to the wise...
   Class Policies
Class policy regarding late assignments, makeup tests, partial credit, Incompletes, academic honesty, etc
   Submitting Your Assignments
What you need to know regarding turning in your assignments
   Appealing Assignment Grades
FIU policy on what to do if you feel an assignment was graded erroneously
   How to Create a "Zip" File
   Using NetBeans
Top               Home

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

   Programming Style
Conventions for creating readable code
   Java "Documentation Comments"
When a class contains Java "documentation comments" you can run the javadoc utility program to create HTML "help" pages for that class. These pages will have the same format as the official Java Language Documentation from Oracle
   Using the javadoc Utility Program
How to run the javadoc utility in NetBeans
   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
When related classes are stored in packages, they are easily reused via the import statement
Top               Home

2.) Java's ArrayList Class (Review) Ch.7, Sec. 7.7

   Powerpoint - Chapter 7 (The ArrayList Class Only)
   Intro to ArrayLists
Array and ArrayList concepts and terminology, advantages of lists, when to use an ArrayList, list items and list indices, basics of list processing, ArrayList methods, "overflowing the bounds" of a list, and "generic" ArrayLists
   ArrayLists and Primitive Types
To store values of a primitive type (e.g. int), we create an ArrayList of the associated "wrapper" class (e.g. Integer)
The DataList class has an instance variable that is an ArrayList-of-Integer, and computes the average, maximum, and standard deviation for any number of test scores - test class for the DataList class

   ArrayLists of Objects - a Complete Example of List Processing | |

BankAccount objects have an account number and a balance that can be modified by deposits and withdrawals

The Bank class has an instance variable that is an ArrayList-of-BankAccount, which maintains a list of accounts (i.e., BankAccount objects). The class has methods that

  1. return the total on deposit in all accounts
  2. return the number of accounts that have a specified minimum balance
  3. return the BankAccount object (i.e., a pointer to it) with the largest balance
  4. search the list of accounts and return the BankAccount object (i.e., a pointer to it) that has a specified account number, which is exactly what happens when you insert your debit into an ATM

The test class creates a Bank object and several BankAccount objects which are added to the list, and then calls the methods of the Bank class

   Random Numbers
Java's Random class makes it easy to generate random numbers - floating-point numbers, ints, and ints within a specified range. Random booleans too!
Top               Home

3.) Data Files and I/O Review (Chapter 11, Sections 11.1, and 11.2)

   The Scanner Class
Scanner class methods and using a Scanner object for interactive input and for extracting the individual "tokens" from a String
Demonstrates Scanner methods next(), nextInt(), and nextDouble()
   Working with Data Files in Java
Explains file types and access methods, throws clauses, using the Scanner class to read from input files, using the FileWriter and PrintWriter classes to write to output files, and closing a file | | 8BallAnswers.txt
A digital version of the classic prognosticating device. The test class uses a Scanner object to read the answers from input file 8BallAnswers.txt until end-of-file. The Magic8Ball class reviews ArrayLists and random numbers

   The Bank Program - Data File Oriented
The Bank program from the previous unit has been modified so that the test class reads the account data from the input file BankData.txt, and the printList() method of the Bank class writes it to an output file | | | BankData.txt

   Assignment #1 - The ArrayList Class
garage.txt - input file

   Algorithms, Pseudocode, and Stepwise Refinement
Where methods come from
   Formatted Output - the printf Method
How to use printf to control the width of the output field, number of decimal places shown, right or left justification, etc
Top               Home

4.) The Java Array (Chapter 7)

   Powerpoint - Chapter 7 (Arrays Only)
   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
Shows a class with an array instance variable, the length instance variable, basic array traversals using a for statement, and sorting an array using the selection sort algorithm. Also reviews generating random ints
   Arrays Class Methods
Static Arrays class methods fill, sort, binarySearch, equals, and copyOf
Simple examples of the major Arrays class methods in action
Shows how to use a counter to keep track of the number of elements used in an array, which is how the size() method of the ArrayList class is implemented. Also shows how to "resize" an array if it becomes full, and a linear search
   The Binary Search
The binary search is much more efficient than the linear search, but can only be done on a sorted array
Maintains a list of ints in ascending order. New ints are inserted at the proper index so there is never a need to sort the list. To insert a new value into an array at a specified index - let's call it i - must resize the array if full and must move all values at indices >= i "down" one position to make room. To remove a value from an array, must move all values at greater indices "up" one position to overwrite it. This is exactly what happens in ArrayList methods add(index,object), remove(index), and remove(object)

   Multi-Dimensional Arrays
In Java, a two-dimensional array is a one-dimensional array of one-dimensional arrays. That is, an array where each element points to another array. However, we think of it as a table, with rows and columns
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 - input file for VoteCounterTest
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)
Top               Home

5.) Designing Classes (and more) (Chapters 8 and 12)

   OOP Terms, Concepts, and Advantages
Information Hiding, Encapsulation, Reusability, and promoting software extensibility via Inheritance and Polymorphism
   Object-Oriented Design
Analyzing a problem and designing a solution in an object-oriented manner
   Class Exercise
A familiar problem statement we will use as a class exercise in Object-Oriented Design
   Some Class and Program Design Guidelines
Cohesion good, coupling bad! (Side effects bad, too!)
   The Assignment Statement in Java
What Java's "=" operator means
Using "=" with objects
   Parameter-Passing Mechanisms
In Java, all method parameters are passed "by value." This means that the method parameter is a copy of the corresponding argument...
Program demonstrates how object variables - which in Java store object references - are always passed by value
   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
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
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
   Cloning an Object
To enable users of a class to make copies of objects, the class should override the clone method of the Object class
Shows how to override clone() and how to call the overridden method
   Static Class Members
Static "class variables" and static methods, explained
   The this Reference
What this is, how it is used, and when it must be used
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

6.) Interfaces and Polymorphism (Chapter 10)

   Powerpoint - Chapter 10 (Interfaces and Polymorphism)
   Introduction to Interfaces
Interface concepts, syntax, and rationale, and how to write classes that implement (i.e., "realize") an interface
What it is and how it promotes software extensibility. "Early binding" vs. "late binding" and how late binding enables polymorphism
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 polymorphic method calls

   The Measurable system features an interface with abstract methods, two classes that implement it, and a class that depends only on the interface and not on any of the implementing classes. Note that all objects added to the DataSet are treated as the interface type, Measurable, regardless of the actual class of the object. This is crucial - the Measurable interface describes any class whose objects can be measured | - two classes that implement Measurable - computes the average and maximum for any number of Measurables. Depends only on the interface - test class for the DataSet class
MeasurableUML.xls - Unified Modeling Language diagram for the Measureable system

   Newer version of the Measurable system. The Measurable interface now has a static method and a default method along with abstract method getMeasure(). Requires Java 8 or newer - the updated interface | - implementing classes are unchanged from previous version - modified to show new features of interfaces - calls static method getAverage and default method isGreaterThan - test class
UML diagram is the same as for the previous version, above

   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
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
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" - The interface - A class that depends on Measurer - Test class has an inner class that implements Measurer
MeasurerUML.xls - UML diagram for the Measurer system

   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 two cases, the solution is to create another class that implements the Comparator interface
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

7.) Inheritance and Polymorphism (Chapter 9)

   Powerpoint - Chapter 9 (Inheritance and Polymorphism)
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
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 - The superclass | - Two subclasses of BankAccount - Test class for the BankAccount hierarchy

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

8.) Java Collections and The ArrayList and LinkedList Classes (Chapter 15)

   Powerpoint - Chapter 15 (The Java Collections Framework)
   Intro to Java Collections
Interface List is derived from interface Collection, and classes ArrayList and LinkedList implement the List interface. Shows how to create an iterator for a Collection and for a List and explains the major Iterator, List, and ListIterator methods
Demonstrates the major List and Iterator methods
Uses asList() to get a "list view" of an array and then calls 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
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
Shows List method ListIterator, and ListIterator methods hasNext, next, hasPrevious, previous, and remove
Top               Home

9.) Intro to Data Structures: Creating Generic Classes, Linked Lists, Stacks, and Queues (Chapter 16)

   Powerpoint - Chapter 16 (Intro to Data Structures)

   Generic Classes and Methods
Generic classes and methods, type variables (aka: type parameters), constraining type parameters, and the generic Comparable and Comparator interfaces
A simple generic list class ADT with limited functionality. "Genericity" - the ability to store objects of any class - is implemented via "type variables," as it is for classes from the Java Library. Demonstrates the OOP principle of "information hiding" by providing an iterator so that clients may traverse the list without having to know how it is implemented (it happens to be an array but the user has no way of knowing that) - test class

   List Primitives
The most basic operations on linked lists: isEmpty(), insertAfter(), and deleteAfter()
Version 2 of the BogusList class. The implementation has been changed to a programmer-defined linked list (not a java.util.LinkedList) - test class
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... - test class

Stack concepts, operations, and examples
A generic Stack class with array implementation and methods push, pop, peek, and isEmpty - test class
Version 2 of the generic Stack class. Implementation has been changed to a linked list of generic nodes, but interface remains the same (methods push, pop, peek, and isEmpty)
Uses a stack to evaluate arithmetic expressions in postfix notation - test class
postfix.txt - data file

Queue concepts, operations, and examples
A generic Queue class implemented as a circular array, with methods append(), serve(), and isEmpty() - test class
A generic Queue class with linked implementation - test class
Top               Home

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

   Powerpoint - Chapter 13 (Recursion)
The basics of recursion. Includes the "Secret of Recursion"
Computes the area of a triangle composed of square boxes. An easy-to-understand recursive solution to a problem that has an even easier iterative ("non-recursive") solution - test class for
Assorted recursive methods, some containing arrays. Every one guaranteed different!

   Recursion Homework
For class discussion next class
Generates all the permutations of a string - a problem for which the recursive solution is easier than the iterative - test class for the PermutationGenerator
The "Towers of Hanoi" is a classic example of more advanced recursion
A good example of a problem solved more easily using recursion
Another classic example of more advanced recursion, finds all 92 solutions to the "Eight Queens Problem." Demonstrates backtracking
A simplified version of the 8 Queens problem, this one places 4 queens on a 4 x 4 board

Top               Home

11.) Exception-Handling (Chapter 11, Sections 11.4 and 11.5)

   Powerpoint - Chapter 11 (Exception-Handling)
   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")
Uses the RuntimeException class to review what happens if an exception is not caught
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
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
   More on Exception-Handling
Checked vs. unchecked exceptions, creating your own exception classes, exception class constructors, and the finally clause
Defines a class to create and manipulate dates and creates a new exception class - DateException - with default and string-argument constructors. Any attempt to create an illegal Date throws a DateException and passes a descriptive string to the constructor. When the printStackTrace() method is called for the exception, the string is printed. Also has a generic exception handler to catch InputMismatchExceptions. Further, shows how to enclose try and catch blocks in a loop so program can recover and continue when an exception is thrown
Shows that a finally clause is always executed

   Exceptions - a Complete Example | | defines a new exception class 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 - - 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

Top               Home

12.) Advanced Data Structures (Chapter 16) - Optional, Time Permitting

Set concepts and fundamental set operations, Java's Set interface and classes HashSet and TreeSet, and set iterators
Demonstrates Set methods add(), remove(), and contains(), and Iterator methods hasNext() and next(), using a Set of Strings
Explains hash codes, hash functions, hash tables, buckets, and collisions, and why a hash table is an efficient way to manage a large set of data
   Hash Codes
How the hashCode method is defined in Java's String class, and how to define a hashCode method for your classes
CH program that implements a hash set similar to Java's HashSet class - simple test class for the HashSet class
Top               Home