CS 122 - Spring 2019

Please check back periodically. During the course of the term, I will add reading assignments, suggest study questions to help you prepare for class, and upload handouts. The reading assignments below should be completed before class. I recommend that you bring your book to class, because we may go over some examples in the book.

Labs are on Thursdays.

Monday, January 14 Here is the syllabus.

Please read section 1.1 in the textbook, our first look at Java programs.

Why do we write computer programs?

The goal of this course is for us to think in ways that are logical, organized and precise. We begin by considering the problem-solving procedure. In other words, the design and implementation of solutions. What is a programming language: what elements to we expect to find to help us write programs?

Here is the example code from class.

Wednesday, January 16 Section 1.2 - Data types

Here is the example code from class.

Lab #1 The lab handout is here.

Labs will be done on our server, cs.furman.edu. The purpose of this lab is to learn how to use the Linux operating system to manage our files, and to create and run Java programs. We will look at how Java uses command-line arguments as input into a computer program.

Friday, January 18 Section 1.2 - Data types (continued)

Here is the example code from class.

Wednesday, January 23 Section 1.3 - Control flow: making choices and loops

Here is the example code from class.

The if statement, while loop, and for loop
If and while are similar to what you saw in Python.
Pay close attention to the components of Java's for loop.
The while loop and for loop are theoretically equivalent, but for loops are much more common.

Style points: Curly braces are optional if the body has only one statement.
You should vertically align the curly braces.
You should indent by 2 or 3 spaces. Don't hit the tab key to indent.

In loops, you often see the operators ++ and -- to add/subtract 1.

Nested loops, e.g. to print rows and columns

Study examples on pp. 61-69.
Test if a number is prime. Find the sum of the digits. Find the sum of its divisors.

Here is your first homework assignment, due Tuesday 1/29.

Lab #2 The lab handout is here.
Friday, January 25 Section 1.3 - Control flow (continued)

Here is the example code from class.

Switch statement
Do-while loop
Break and continue
Mistakes with loops

You should practice with the exercises at end of section 1.3.

Monday, January 28 Section 1.4 - Arrays

Here is the example code from class.

Steps to remember: declare, allocate space, initialize, use

Often we declare and allocate space at the same time. You should know the size of your array before you begin using it. Here is a typical array declaration (10 integers). The procedure is so common it's worth memorizing:
int [] a = new int [10];

Java's array may remind you of Python's list. Some important differences:

  • An array's size is fixed.
  • The elements of an array are the same type.
  • It's easy to create a multi-dimensional array.

Almost any useful task on an array will need a loop.

2-d arrays are very common.

I forgot to mention that when you use "new" to allocate space for an array, this automatically sets all the elements to zero.

Wednesday, January 30 Section 1.4 - Arrays (continued)

Here is the example code from class.

Let's do some practice problems from the book.... We did #5, 15, and 33.

Lab #3

Here is the lab handout.

Practice with arrays

Friday, February 1 Section 1.5 - I/O

Here is the example code from class.

How to perform standard input and output. Today we'll focus on input.
Scanner and StringTokenizer

Here is your second homework assignment, due Wednesday 2/6.

Monday, February 4

Here is the example code from class.

Error checking of input. What if the user enters invalid input?

Try/catch to avoid run-time errors with input

File input: FileInputStream and FileNotFoundException

Wednesday, February 6

Here is the example code from class.

Standard output: formatted output with System.out.printf().

File output: PrintStream and FileNotFoundException

Redirecting standard I/O at the command line.

Here is your third homework assignment, due Wednesday 2/13.
I'd like to clarify something: This game only plays one hand. After announcing the result, the program should halt. The end of the handout actually shows two separate runs of the program.

Lab #4 Here are the files you need for today's lab.

Practice with I/O

Friday, February 8 Creating image output

Here is the example code (handouts) from class.

Monday, February 11 I have decided that rather than jumping into chapter 2, we should instead spend this week going over two more basic ideas in Java: the String and ArrayList. We will look at Strings today and ArrayLists on Wednesday.

In Java, the String is not a primitive type - it is a "class". For our purposes, this means that there are many built-in methods that can be applied to strings.

The real focus today is on commonly used String methods.
length(), charAt(), indexOf(char), lastIndexOf(char), substring(begin, end), equals(another_string), compareTo(another_string), toLowerCase(), toUpperCase()

Examples: Traversing the characters of a string.
"Tokenizing" when you know the exact location of the token.
Counting words of a certain length.

If you want to read more about strings, the complete documentation is available in the API documentation under the heading java.lang.String.

Special notes: We never use relational operators like == to compare strings.
And since the String class gives us so many built-in methods, we never need to use arrays of char.
Note the syntax of these string methods. We say s.length(), not length(s)

Here is the code example from today's class.

Here is a collection of review questions for Friday's test.
I didn't write solutions to the questions, but I would be happy to help you during office hours if you would like to go over your answers, or if you are stuck on a problem.

Wednesday, February 13 Here is a handout on some basic facts about the ArrayList.

The ArrayList in Java is very similar to the concept of the list in Python. Unlike the Java array, an ArrayList can grow and shrink. We don't need to know the maximum size when we create one.

However, for technical reasons, the cells of an ArrayList cannot contain primitive type. But they can contain Strings. So, it's useful for us to use ArrayLists of Strings. An example is reading the lines of a text file.

Useful functions to be familiar with:
size(), add(element), add(index, element), get(), remove()

With all of this talk about arrays and ArrayLists, one should note that there are times when using them may be unnecessary. If we need to read an input file containing a lot of numbers or words, this does not mean that we must store all the data in some big collection. Let's consider examples of when arrays or ArrayLists are (not) needed.

Lab #5

Here is the lab handout.

String practice

Friday, February 15 Test #1 at our regular class time
Monday, February 18 The next 2 weeks are going to be about chapter 2 in the book.
How to write our own functions (static methods) in Java.

Page 194 shows a typical example of a program that uses a function.
You should be familiar and comfortable with the terminology on page 196.
More examples of short functions are shown on pages 199 and 209.
Page 200 discusses variable scope. What does this mean?

What is a function? Why do we write functions in a computer program? What are some useful tasks we might want to have performed by a function?

Pass by value versus pass by reference. Pass by reference occurs with arrays. Note this passage on page 208: "when you pass an array as an argument to a method, the method has an opportunity to reassign values to the elements in that array."

Wednesday, February 20 Let's do some practice problems at the end of section 2.1.

Section 2.2 introduces us to the idea of organizing code into more than one source file.

Here are the example programs from today's class.

Here is your fourth homework assignment, due Friday 3/1. Please note that for both programs, your output needs to be in alphabetical order.

Lab #6

Here are the files you need for lab.

Static methods

On Thursday, I will be out of the office for most of the day. I will be at a conference in Spartanburg. I will also be late to lab. Please show your work to the lab aide if you finish before I come to the lab.

Friday, February 22 Here are the example programs from today's class.

We begin section 2.3 on recursion!

Monday, February 25 Briefly review the definition of recursion.

Consider the exp() function in Formula3.java. Why does it have two recursive calls? Does this make the function inefficient?
As an example, how we can efficiently compute a36?

Let's practice writing some recursive functions. Here is the class handout.

Wednesday, February 27 Using recursion to define a set of strings. Here is the class handout.

Lab #7 Recursion

Here is the lab handout, and here is the source code that you need to modify.

Friday, March 1 You have seen that a set of strings (i.e. "language") can be defined recursively. What are some examples? Let's see how can we exploit this in a program:
  • The acceptance problem: given an input string, does it satisfy a recursive definition of a language?
  • Recursively generating text: creative writing by computer. We could even make a grammar to tell stories, similar to Mad Libs. People have even written fake research papers this way.

Here is the source code of the class examples.

Monday, March 11 To review, what are the two ways we can accomplish repetition in programming? How do they work?

An important problem-solving technique is to combine recursion with backtracking. This is used when we need to search for a path, or to create something step-by-step and many alternatives exist at each step. You can think of backtracking as recursion that handles "mistakes".

As you study the examples, you should pay close attention to the structure of the recursive function. For instance, there will usually be a loop containing possibilities to consider. After making a selection, we call ourselves recursively. After the recursive call, we see if it led to a solution. If not, we need to try the next iteration of the loop. And if we are out of possibilities, this is when we backtrack!

Examples: Solving a maze, the 8 Queens problem and the Knight's Tour problem.

Here is the outline of solving the maze. We start by calling solve(0, 0).

  • done = false
  • if (blocked), return false
  • if (at the exit), return true :)

  • mark this square as being tried
  • done = solve(go up)
  • if (not done), try the next direction
  • if (done), mark the successful path --> cascade returns

The 8 queens problem: Is there some way to place 8 queens on a chess board so that no one can get captured? Assume there are no other pieces on the board, just the queens. There are over 4 billion ways to arrange them. Don't use brute force to try all of them! Also, it would be wasteful to write 8 nested loops, one for each queen. Let's use backtracking.

  • Place one queen in the first column.
  • Place the next queen in the next column, in a place safe from attack.
  • If not able to place this queen, back up! It means the previous combination of choices does not produce a solution. We're stuck.
  • In the code look for: pre- and post-condition, base case, and examining the value of done when we backtrack.
  • How would we change the program to find ALL solutions?
Wednesday, March 13 Finish backtracking examples. How can we verify our answers?
How deep can recursion practically go? This tells us how big of a problem we can tackle with recursion.
Towers of Hanoi: Begin by considering small instances of the problem. Then, how do we move n disks from peg A to peg C, if we know how to move n-1 disks?

Example code: limit and Hanoi.

Here is your fifth homework assignment, due Wednesday 3/20.

Lab #8 Recursively generating text.

Here are the files you need for the lab.

Friday, March 15 Begin chapter 3: Object data types, as opposed to primitive types.

Read section 3.1.
Examples: String and Color classes.
Section 3.1 also has a nice review of I/O on page 353.
Pay close attention to "Properties of reference types" on pp. 362-368.

The most important feature of Java is that it is an object-oriented programming language. There are two kinds of data types: primitive types, and classes. Classes are either pre-definied in the Java API (run-time library), or we can create classes ourselves. Here is an example program that features object-oriented programming.

Monday, March 18 Section 3.2 - creating our own data types

We will practice creating our own classes. Just reading about object-oriented programming doesn't do it justice.

  • Each object of the class should have what attributes? Think about what sets one object apart from others.
  • Constructors: default, initial-value, copy
  • Get and set methods for each attribute.
  • toString() - what should the string representation of an object look like? If the representation is complex, using StringBuilder can make the code more efficient. Visually pleasing strings can be created with String.format() which functions like System.out.printf(). But remember that toString() by itself doesn't print anything!
  • equals()
  • Other methods specific to this class.

Note the difference between an instance method versus a static method that you saw earlier. Take equals() as an example. Suppose we are in a main() method and we have two room objects, r1 and r2. We want to know if these objects are "equal". How should we do it? If equals() is a static method, then we would say Room.equals(r1, r2). But if equals() is an instance method, then we say r1.equals(r2). In practice, we prefer instance methods.

Example: Account

Wednesday, March 20 Let's design (but maybe not implement) some classes.
  • A time class to keep track of hours and minutes. How do we add 6h13 + 2h27? When we write the sum() method, we'll call the copy constructor in order to store our answer.
  • A fraction (rational number) class.
  • Classes for a playing card and a deck of cards. This is an example of class aggregation, because one type of object is contained in another.
  • Climate data is published daily (high temperature, low temperature, and amount of precipitation). We can summarize data for a whole month.

Do you understand the difference between a static method and an instance method?

toString() often uses String.format() and/or StringBuilder.

Constants are declared "public static final". What do these words mean?

Here is your sixth homework assignment, due 3/27.

Lab #9 Let's create classes in Java. The lab also features a class relationship called aggregation.

The lab handout and input file can be found here.

Friday, March 22 Please read pp. 446-457 on inheritance.

Be careful not to redeclare attributes inside a constructor.

Let's finish the class examples from Wednesday.

Another relationship that can exist between between classes is inheritance: One class is a more specialized version of the other, or we like an existing class but would like to add more functionality to it. The purpose of inheritance is to allow classes to share some attributes and operations so we don't duplicate code.

How to remember the difference between aggregation and inheritance:
Aggregation means "has a": a Team has Players.
Inheritance means "is a": a Bird is an Animal.

Monday, March 25 Interfaces and inheritance.

See handouts for details.

Here is an outline of object-oriented concepts.

Here are some review questions for test 2.

Wednesday, March 27 Polymorphism and comparators.

Polymorphism means that an object can change its class by calling a different constructor. Polymorphism is a feature of both interfaces and inheritance.

Comparators are very useful when you want to sort a collection of objects.

Lab #10 Writing your own comparators.

The files you need for the lab are here.

Friday, March 29 Test #2 during the regular class period. Good luck!
Monday, April 1 Chapter 4 is about data structures. The ArrayList is not the only way to think about how your data is aggregated! We will follow a 2-step process.
  1. Design and implement our own data structure: a data type that stores many of the same sort of data. Sometimes this step is unnecessary because the Java API has exactly the data structure functionality we want.
  2. Once the data structure has been implemented, create an application that uses it. And when you use the data structure, you are no longer concerned with how it was implemented.
If you are designing a program that needs to maintain a collection of data, you need to ask: How do we want to aggregate the data? As an illustration, let's create our own type of collection called a Bag, which will model a shopping bag or a bag of candy at Halloween.

The Bag class will rely on some underlying representation, such as an ArrayList. We want the bag to contain "Items." Then, we consider desired operations on the bag.

The files supporting the bag data structure can be found here.

Wednesday, April 3 How do you implement a linked list? Let's consider doubly linked lists. A linked list has a head and a tail. How to insert a node into a linked list, and how to delete a node.

Linked list handout.

An example implementation can be found here.

Lab #11 Let's experiment with Java's Hashtable data structure. It works the same way as the dictionary in Python. While an ArrayList requires us to index data using numbers 0,1,2,3,..., the Hashtable allows us to index by any key value type we want, such as a string.

The files you need for the lab are here.

Here is an example program that uses the Hashtable class. You may want to glance at this program to see how the syntax works.

Friday, April 5 Overview of stacks and queues (sections 4.3 and 4.4). Handout

Stack applications: balanced parentheses, postfix expressions

Here is an example implementation of a stack class. It also contains 2 main programs: Paren.java balances parentheses and Driver.java evaluates a postfix expression using a stack.

Here is your seventh homework assignment, due Monday, 4/15.

Monday, April 8 Let's practice writing arithmetical expressions in four different ways: as a binary tree, and in prefix, infix, and postfix notation. Given an infix expression, can we draw the tree? Given a tree, can we figure out its linear representations?

We know we can use a stack to evaluate a postfix expression. What about a prefix expression?

If time permits, let's look at the problem of converting an expression directly from infix to postfix using a stack: Worksheet

Wednesday, April 10 Review purpose of stack and queue.

Can we evaluate a prefix expression?

How can we directly convert an infix expression to postfix using a stack? Practice with the handout you received on Monday.

Lab #12 Convert from infix to postfix. Complete the implementation in this source file here.
Friday, April 12 Implementation of stacks and queues. How would you design a stack or queue data structure, if your programming language didn't already have one? (e.g. Java has a built-in Stack class, but not Queue.)

Real computer memory operates as an array, so let's implement a stack using an array.

Here is an example implementation and demo of using a queue.

Monday, April 15 Review the steps of creating a data structure. Sometimes it's convenient to have a helper class, such as a Comparator or Iterator.

Iterators are especially nice when you have a non-linear data structure. How do you create and use an iterator? Using an iterator is analogous to how we have traversed a file, tokenizer, and enumeration. Using an iterator is simple. So, let's focus our attention on how to write an iterator class.

The graph data structure: example implementation here.

Wednesday, April 17 What is an iterator? Why do some data structures need one?

In the graph class, the neighbor iterator allowed us to visit all of the neighbors of one vertex. How can we visit all of the vertices in the graph? For example: Breadth-first search and depth-first search. Practice with these graphs.

Here is your eighth homework assignment, due Tuesday 4/30. The input file you need is here.

Lab #13 Graph implementations.

The instructions for the lab can be found here. The existing Graph implementation can be found here.

Wednesday, April 24 Let's look at some conventional sorting methods, such as selection sort, insertion sort, bubble sort and exchange sort.

It will be interesting to compare them for efficiency.

Lab #14 Some simple sorting algorithms.

The instructions and files you need for the lab can be found here.

Friday, April 26 Merge sort and radix sort.

During the last 10 minutes of class, you will be asked to fill out a survey about how you feel about your programming knowledge. This survey will help the CS department in our future course planning.

Monday, April 29 Review for final exam.

Here are some additional review questions. You should also look over all previous handouts in the course.

Friday, May 3 Final exam at 8:30 in our usual classroom. Good luck!
Tuesday, May 7 This is the last day that I can accept late submissions of homework #8. It's based on the deadline I must meet to turn in grades.


Here is the online documentation for the Java API, the run-time library of built-in functions that are very useful in Java.

Don't forget that our textbook also has its own Web site, with summaries of the sections and additional practice problems. You can find it here.