Computer Programming II

COP 3337

Fall Semester 2020

Read this first!

Online notes are in MS Word '97 format.
Sample programs are .java files.
All programs have been tested and certified error-free.

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 to "Java SE 8u261" and click the JDK Download link
  2. Choose the version for your operating system. Note that there are two links for Windows - one for older 32-bit Windows (Windows x86) and another for 64-bit (Windows x64). 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
  3. After downloading, double-click on the file icon to install

Note: You must install Java before installing NetBeans

    NetBeans IDE 8.2 (Essential)

   NOTE: Do NOT use any version other than 8.2!
   Otherwise, the Graders will not be able to open your project and you will not receive credit!

  1. Click the link above
  2. When redirected to the Apache NetBeans page, scroll down to Older releases and click the [Find out more] button
  3. Scroll all the way down to Pre-Apache NetBeans versions and click the link to version 8.2
  4. 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)

  1. Click the link above
  2. Scroll down to "Java SE 8u261"and click the Documentation Download link in the right-hand column
  3. Click the link to download the documentation (docs)

Click here to view the documentation online

Top               Home


Textbook - Big Java, Early Objects (7th ed)

    Big Java 7 Home Page
  • Source code for all sample programs (in zip format)
  • Bug List - all known errors in the book

    Answers to Review Exercises - 7th Edition
All Chapters

    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)

   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

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

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
   Packages
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)
   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)
   DataList.java
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
DataListTest.java - test class for the DataList class

   ArrayLists of Objects - a Complete Example of List Processing

BankAccount.java | Bank.java | BankTester.java | BankAccount.html | Bank.html

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 BankAccount objects. The various methods are excellent examples of list processing (i.e. accessing each object on the list in turn and doing something with it)

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!

   Assignment #1 - The ArrayList Class
NumberTile.java | Hand.java | Board.java | TileGame.jave | TileGameTester.java - class "skeletons" to be used
Sample Output

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
   InputDemo.java
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

   Magic8Ball.java | Magic8BallTester.java | 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
BankAccount.java | Bank.java | BankTester2.java | BankData.txt

   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 (The Java Array)
   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
   ArrayDemo.java
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
   ArraysMethodsDemo.java
Simple examples of the major Arrays class methods in action
   PartiallyFilled.java
Shows how to use a counter to keep track of the number of elements used in an array, when not all elements may be used. Also, how to "resize" an array if it becomes full and a linear search
   OrderedList.java
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 at index i, must resize the array if full and move all values at indices >= i "down" one position to make room. This is exactly what is done in ArrayList method add(index,object)
- To remove a value, must move all values at greater indices "up" one position to overwrite it. This is exactly what happens in ArrayList methods remove(index) and remove(object)

   Assignment #2 - Arrays
NumberTile.java | Hand.java | Board.java | TileGame.jave | TileGameTester.java - class "skeletons" to be used
Sample Output

   The Binary Search
The binary search is much more efficient than the linear search, but can only be done on a sorted array
   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
   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
Votes.data - input file for VoteCounterTest

   Assignment #3 - 2D Arrays
A heuristic for the Knight's Tour - Optional

   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)
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!)
   Algorithms, Pseudocode, and Stepwise Refinement
Where methods come from
   The Assignment operator in Java
What Java's "=" operator means
   AssignmentDemo.java
When you assign one object variable to another, you do NOT wind up with two equal objects. Since object variables store object references (addresses) and not the objects themselves, what you get is two pointers to the same object
   Parameter-Passing Mechanisms
In Java, all method parameters are passed "by value." I.e. The method parameter is a copy of the corresponding argument
   ParamPasser2.java
Shows that object variables - which store object references - are always passed by value and what this means as far as modifying the argument in the method
   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
We override toString to return a String representation of an object. Bonus: whenever Java finds an object variable where it expects to find a string, e.g., as the argument to print, println, printf, the toString method will be called implicitly (automatically)
   Testing for Equality
Java's "==" operator vs 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
   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


6.) Interfaces and Polymorphism (Chapter 10)

   Powerpoint - Chapter 10 (Interfaces and Polymorphism)
   Introduction to Interfaces
Interface concepts, syntax, and rationale. 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 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 the key to using interfaces as it allows new classes to be added to the system without no modification of existing software

Measurable.java - the Measurable interface describes any class whose objects can be measured
BankAccount2.java | Coin.java - two classes that implement Measurable
DataSet.java - computes the average and maximum for any number of Measurables. Depends only on the interface
DataSetTest.java - test class for the DataSet class
MeasurableUML.xls - Unified Modeling Language diagram for the Measureable system

   Assignment #4 - Interfaces and Polymorphism

   As of Java 8, interfaces may have static and default methods in addition to the abstract methods, as shown in this modified version of the Measurable interface. ***OPTIONAL***
Measurable.java - the updated interface
BankAccount2.java | Coin.java - implementing classes are unchanged from previous version
DataSet.java - modified to show new features of interfaces - calls static method getAverage and default method isGreaterThan
DataSetTest.java - test class

   Upcasting, Downcasting, and All-Around-the-Town-Casting
Upcasting an object of an implementing class to the interface type is always a safe operation, so Java will do it implicitly. Downcasting from the interface type back to the native class type is dangerous, so an explicit type cast is required
   Java's Comparable Interface
If your class implements Java's Comparable interface, you can compare objects for the <, <=, >, >=, ==, and != relationships by calling your overridden compareTo method. The comparisons are based on the "natural order" of the objects of your class. You get to say what the natural order is when you implement compareTo
   Rational.java
A class to represent Rational numbers (i.e, any number that can be expressed as a fraction). The class implements Java's Comparable interface and overrides compareTo to order Rationals by their decimal value. The class 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
MeasurerUML.xls - UML diagram for the Measurer system

   Java's 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 you do own the class and it already implements Comparable and overrides compareTo to order objects a certain way but now you want to provide an alternate way to order the objects of the class. In these two cases, the solution is to create a class that implements Java's Comparator interface
   ComparatorTest.java
Defines a RectangleComparator class that implements Comparator and overrides abstract method compare to order objects of Java's Rectangle class by their areas. Also shows overloaded "three argument" versions of Arrays class methods sort and binarySearch. These are used with arrays of objects of classes for which you have defined a "strategy interface" class that implemets Compatator to do the comparisons (for either of the two situations above)
Top              Home


7.) Inheritance and Polymorphism (Chapter 9)

   Powerpoint - Chapter 9 (Inheritance and Polymorphism)
   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 of abstract classes and methods

   Assignment #5 - Inheritance and Polymorphism

   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 a Collection iterator for a Collection and a List iterator for a List and explains the Collection Iterator and ListIterator methods
   CollectionDemo.java
Creates a Collection Iterator object and calls methods hasNext, next, and delete
   ArrayAsList.java
Calls Arrays class method asList() to get a "list view" of an array and then calls List methods get() and set() for the array!
   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
   CollectionsMethodsDemo.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
Calls List method listIterator to create an iterator for a List, and calls 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
   BogusList.java
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)
BogusListTester.java - test class

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

   MyLinkedList.java
Version 2 of the BogusList class. The implementation has been changed to a programmer-defined linked list (not a java.util.LinkedList)
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 #6 - A Generic Linked List Class
Polynomial.java - class "skeleton" to be used
PolynomialTester.java - test class to be used

   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
   Stack2.java
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)
   PostfixEvaluator.java
Uses a stack to evaluate arithmetic expressions in postfix notation
PostfixEvaluatorTest.java - test class
postfix.txt - data file

   Queues
Queue concepts and primitive operations append(), serve(), and isEmpty()
   Queue1.java
A generic Queue class with linked implementation
   Queue2.java
A generic Queue class implemented as a circular array
   QueueDemo.java - test class for either
Top               Home


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

   Powerpoint - Chapter 13 (Recursion)
   Recursion
The basics of recursion. Includes the "Secret of Recursion"

   Triangle.java
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
TriangleTester.java - test class for Triangle.java

   RecursionExamples.java
Assorted recursive methods, some containing arrays. Every one guaranteed different!

   Recursion Homework
For class discussion next class

   Assignment #7 (Recursion)
ArrayRecursion.java - class "skeleton" to be used

   TowersOfHanoi.java
The "Towers of Hanoi" is a classic example of more advanced recursion
   PermutationGenerator.java
Generates all the permutations of a string - a problem for which the recursive solution is easier than the iterative
PermutationGeneratorDemo.java - test class for the PermutationGenerator
   Queens8.java
Another classic example of more advanced recursion, finds all 92 solutions to the "Eight Queens Problem." Demonstrates backtracking

   Queens4.java
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")
   TheUncaught.java
Uses the RuntimeException class to review what happens if an exception is not caught
   BogusExceptionDemo.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
   More on Exception-Handling
Checked vs. unchecked exceptions, creating your own exception classes, exception class constructors, the finally clause, and try-with-resources

   DateTester.java
I wrote the Date class to give Prog I students practice creating and manipulating objects using loops. For the sake of brevity, all methods not necessary for this lesson have been omitted
  • Note the declaration of a new exception class - DateException. To create a Date, the user must enter 3 ints - month, day, and year - separated by spaces. Any attempt to create an illegal Date throws a DateException and passes an exquisitely descriptive string to the constructor. The string is printed in the catch
  • Also note the generic exception handler (i.e. catches superclass Exception) to catch all the standard Java exceptions (e.g. InputMismatchException, NoSuchElementException, IdiotUserException)
  • Note how the try and catch blocks are in a loop so the program continues after an exception is caught. The program cannot be crashed! C'mon! Try it!

   Exception Handling - a Complete Example

BadDataException.java | DataSetReader.java | DataSetTester.java

BadDataException.java defines a new exception class with default and one-argument constructors

DataSetReader.java has a method called readFile() which reads a file and returns an array containing the values read

  • Throws a FileNotFoundException if the file cannot be opened
  • Throws BadDataExceptions if the file is ill-formed in any of a number of ways
  • Shows how to create meaningful error messages for exceptions. Hallelujah!

DataSetTester.java calls method readFile to process the file. Catches all exceptions which may be thrown therein and resumes execution after each

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

   Assignment #8 - Exception Handling
Time.java - class to be used in this assignment
TimeData.txt - data file
Top               Home


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

   Sets
Set concepts and fundamental set operations, Java's Set interface and classes HashSet and TreeSet, and set iterators
   SetTest.java
Demonstrates Set methods add(), remove(), and contains(), and Iterator methods hasNext() and next(), using a Set of Strings
   Hashing
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
   HashSet.java
CH program that implements a hash set similar to Java's HashSet class
HashSetTest.java - simple test class for the HashSet class
Top               Home