CSCM41 Programming in Java 2016/17
Messages
 The solution of the second coursework is available.
General information
 The url of this page is http://cs.swan.ac.uk/~csoliver/ProgrammingJava201617_Jj1AoYIgC1/index.html .
 First week (3/10/2016  7/10/2016):
 General preparations:
 Get access to the Linx lab: Faraday Tower 500.
 The main task is to get used to the environment (knowing your
password, etc.).
 Specific Tasks:
 Get your access information (username and password)
from your email.
 Check that your login works.
 Access the course home page, and store the link.
 Browse the course home page, and get a bit familiar with it.
 Buy the book.
 One lecture Tuesday 14:00  15:00 in Glyndwr M.
 From 10/10/2016 to 16/12/2016:
 Tuesday, 14:00  15:00, lecture in Glyndwr A.
 Thursday, 11:00  13:00, "lecturelab" session in the Linux lab
(Faraday tower 500).
 Thursday 17:00  18:00, "exerciselab" session (Linux lab).
 The role of the lecturelab sessions:
 In these sessions a mixture of teaching and programming
practice takes place.
 We might not make use of all sessions.
 The role of the exerciselab sessions:
 Active participation in all exercise lab session is awarded 10% of
the overall module marks.
 For each exercise lab sessions tasks are distributed.
 During the exercise lab session, work on these tasks is expected.
 "Active participation" means that during the whole lab session
reasonable work related to the module is performed, typically related
to the current tasks, but possibly also related to previous tasks,
or to other questions or problems (of course, related to the module).
 There are no tests (or exams) in the labs. Every student present for
the full time and doing reasonable work gets acknowledged his/her
active participation.
 Assessment:
 10% is allocated to active participation in the exercise lab
sessions.
 Two courseworks are handed out, each worth 20%.
 The remaining 50% is the January exam.
 The exam is based on what we did in the lectures, the lab sessions,
and the coursework.

Liam McNabb liammcnabb@gmail.com
is the postgrad demonstrator.
The textbook
 This module is based on the book
 "Introduction to Programming in Java"
 from Robert Sedgewick and Kevin Wayne,
 AddisonWesley 2007 (ISBN13 9780321498052).
 It is strongly recommended that you buy this book
(for example at the Campus book shop).
 The book's home page is
here .
 Additional to the book, at this web page a lot of useful information
is available.
 Here is Chapter 1 as pdffile.
 In this module we cover the essentials from the first three chapter.
Slides and material for the lectures
The additional programs you find here .
 Week 1:
 Tuesday (4/10/2016) 1415: Preparations
 And Section 1.1
First programs .
 Week 2:
 Tuesday (11/10/2016): Section 1.2
Basic types .
 Thursday (13/10/2016):
 We write 3 programs together.
 Empty program:
class Empty {
public static void main(String[] args) {}
}
 HelloWorld:
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
 HelloWorld with name provided as argument:
class UseArgument {
public static void main(String[] args) {
System.out.print("Hello, ");
System.out.print(args[0]);
System.out.println("!");
}
}
 HelloWorld with three further names:
class UseThree {
public static void main(String[] args) {
System.out.print("Hello, ");
System.out.print(args[0]);
System.out.print(", ");
System.out.print(args[1]);
System.out.print(", ");
System.out.print(args[2]);
System.out.println("!");
}
}
 Here some remarks.
 Week 3:
 Tuesday (18/10/2016): Completing Section 1.2
Basic types .
 Thursday (20/10/2016):
 We look at the program "IntOps" in detail (
here is
the code).
 There are many problems with this program, and we try to write a
"perfect" version of it.
 We learn:

final
for declaring constants: Don't use
int a = Integer.parseInt(args[0]);
but
final int a = Integer.parseInt(args[0]);
for a variable whose value shouldn't be changed anymore (i.e., we
have a constant).
 The
length
variable to be used with
args
for finding out how many commandline arguments
were entered:
args.length
is an integer, namely the number of commandline arguments.

if
for conditional execution: Via
if (args.length <= 1)
System.err.println("ERROR[IntOpsI]: Two arguments are needed (two numbers).");
else
...
we output an errormessage in case we do not have two commandline
arguments.
 Here
is the improved version.
 The following material is for more advanced students,
while if you are new to programming, then leave it for later.
 There are further serious problems with input handling:
overflow and noninteger input. They can be handled using the
following constructions.

Integer.MIN_VALUE
and
Integer.MAX_VALUE
for finding out the range of int's.

try ... catch
for error handling via catching
exceptions.
 Finally we have problems with the structure of the code: too
many nested ifthenelse make the code messy, and it would be good
if we had also conditional variable initialisation:
 The
System.exit
function allows early return with
an exitcode.
 Conditional expressions allow to have several cases in the
initialisation of variables.
 Here
is the fully improved version.
 Week 4:
 Tuesday (25/10/2016): Section 1.3
Program flow
(
if
statement and while
loop).
 Thursday (27/10/2016):
 Completed Section 1.3
Program flow
(
for
loop and Gambler
program).
 Loops are very important, so please make sure you understand
this section.
 And understand the
Gambler
program in detail!
 Here some remarks and corrections.
 Week 5:
 Tuesday (1/11/2016): Section 1.4
Arrays (inclusive printing a
random card).
 Thursday (3/11/2016):
 Completing Section 1.4
Arrays
(
Deck
for card shuffling, CouponCollector
and SelfAvoidingWalk
).
 Week 6:
 Tuesday (8/11/2016):
 Section 1.5
Input and output .
 See
here
for the inputoutput library we will use from now on.
 You can either copy the .javafiles from this library to the
directory with your programfiles, or you can precompile the library
(by "javac *"), and then just copy the .classfiles.
 Additional material you find
here.
 Thursday (10/11/2016):
 Please enter all programs (still) by hand (no copyandpaste).
 This session completes the part on the basics of programming
(variables, expressions, basic types, loops, conditions, arrays).
 In the remainder of the module we will accelerate the speed.
 First
ShowArgs.java is
a little program helping you to understand the array of strings
args
, and how it gets its value; understand the
following:
> java ShowArgs jj k ll " b n " \" ""
[Ljava.lang.String;@6deee615
6
0 : "jj"
1 : "k"
2 : "ll"
3 : " b n "
4 : """
5 : ""

Post/preincrement
are demonstrated by this little program:
Increment.java.

RandomSeq.java
is a simple example programs which outputs N (pseudo)random numbers
to standard output.

Average.java
shows how to read an arbitrary stream of numbers from standard
input and computing their arithmetic mean.
 This program is improved over the book version by
 using more expressive code,
 checking for empty inputs,
 handling of input errors,
 and also allowing "arbitrarily" long input sequences (for all
practical purposes).

PlotFilter.java reads
(all from standard input)
 first four floatingpoint numbers for min x/yvalues and max
x/yvalues,
 and then an arbitrary sequence of points, specified by their
x,y coordinates (as floatingpoint numbers),
drawing each point when read.

SinFunction.java plots
the function sin(4x)+sin(20x) for 0 <= x <= pi.
 Have a look at the error handling, which uses errorcode
constants specified at classlevel.
 Note also that the constants "4" and "20" are not hardcoded.
 The commandline argument N is the number of points except the
first point, used to plot the function by connecting them.
 If N is not large enough, then the output can be very misleading.
 Week 7:
 Tuesday (15/11/2016):
 Section 2.1
Functions .
 Thursday (17/11/2016):
 Practising functions (see Section 2.1
Functions ).
 Six programs have to be completed, filling the positions marked
with "XXX":
 Write a function
max(a,b)
, computing the maximum
of two integers:
 Write a function
max(a,b,c)
, computing the maximum
of three integers:
 Write a function
max(a,b,c,d)
, computing the maximum
of four integers:
 Write a function
max(a)
, computing the maximum
of an array of integers:
 Write a function
create(n)
, creating an integer
array of length n, filled with 0, 1, ..., n1:
 Write a function
print_message(name)
, outputting
"Hello, name!":
 Week 8:
 Tuesday (22/11/2016):
 Section 2.2
Libraries and Clients .
 Thursday (24/11/2016):
 Section 3.1
Data types .
 The following are additional exercises, with solutions provided.
 First an exercise for writing functions; write class
"SimpleBernoulli" containing the following functions:
 Function "bernoulli", taking a floatingpoint number p from 0 to
1 as argument, and returning a boolean which is true with
(pseudo)probability p.
 Function "bernoulli_r", taking as arguments p as above and N, an
integer, performing N random coin flips, and returning the number of
heads.
The main program reads N and p from the commandline, and prints
the result of bernoulli_r(p,N). How many coinflips can be performed
within a few seconds?
Here is the
solution
.
 Now come exercises for using libraries
Libraries and Clients .
Three programs have to be completed, filling the positions marked
with "XXX", and one program has to be written from scratch.
 Write a program
Statistics
, taking a list of
floatingpoint numbers as arguments and printing their count,
their minimum and maximum, their sum, and their average, each on a
new line. Use the library StdStats.
Here is the
solution
. By the way, that's easy, but it has also disadvantages, namely?
 Using StdRandom.discrete:

Template
 Complete function "count" which
 takes an array a of probabilities (as does
StdRandom.discrete) and an integer N as arguments,
 performs N (pseudo)random draws of natural numbers
0, ..., a.length1 according to the probabilities in
a,
 counts for each of these natural number how often they occur,
and returns an array with these counts.
 Complete function "output".
 Run the program with some N, so that executions takes a few
seconds.

Solution
 Write a program
RandomPoints
which draws N
random points according to a Gaussian distribution:
 Write a program
Bernoulli
which experimentally
computes the relative frequency of 0 <= i <= N heads for N fair
coin flips, and compares it with the approximation by the
Gaussian distribution:
 Week 9:
 Thursday (1/12/2016), first part of first hour:
 Completing using other classes ("constructors" and "methods")
Data types .
 Two programs have to be completed, filling the positions marked
with "XXX":
 Write a program
AlbersSquares
which shows two
colours using two squares:
 Write a program
Grayscale
to convert a
colourpicture to a gray scale:
 Thursday (1/12/2015), second part of first hour:
Discussing the solution of the first coursework.
 Week 10:
 Tuesday (6/12/2016):
 We consider first the question of "public" versus "private":
Section 3.3
Designing data types .
 Thursday (8/12/2016):
 First hour: Section 3.2
Creating data types .
 Plus a quick intro into "identify versus equality":
EqualityIssues (only learning the principal role of
method "equals", and how to write an equalscheck for arrays).
 Week 11:
 Tuesday (13/12/2016)
 Revision and exampreparation
lecture .
 Thursday (15/12/2016):
 Understanding
null
, and JavaObjects in general:
 An "object" in Java is a special thing. Therefore I refer to it
as "Javaobject".
 Objects of primitive data type (int's, boolean's, double's,
char's, and some more) are NOT Javaobjects.
 The speciality of Javaobjects is that, unlike int's for
example, you never have them "in your hands"  only
pointers.
 A variable for a Javaobject is a pointer.
 That is, it is a memory address!
 There is a special exceptional ("singular") memory address,
namely "null", which stands for something which is NOT THERE.
 Study the demoprogram
NullString carefully!
 We have another look at
EqualityIssues , now considering the fine print (the
"obscure cases").
 Understanding "passbyvalue" and "passbyreference":
 What is the output of
PassByValue
?
 And which of the variables (arguments of function
update
and others) can be made final?
The solution is provided
here
.
 Aliasing:
 What is the output of
PotentialProblem
?
 What is the output of
PotentialProblem2
?
 What is the output of
PotentialProblem3
?
Understand that aliasing can not occur in the first two examples,
whatever we do, since the data types used for variable x are
immutable. And understand why using a "proper class", i.e.,
an array here, provided the additional level of indirection in the
third example so that aliasing finally occurs.
Exercise lab sessions
Remark: If some answer is already given, then understand why
this is the correct answer.
 Week 2 (13/10/2016):
 Recall the program "UseArgument.java" from the book:
 If you have already written it, rewrite it
from scratch, not using notes!
 Otherwise you find it above (material for Lectures Week 2): enter
it and understand it.
 Now write the version "UseThree".
 It is called with, e.g.,
> java UseThree X Y Z
and it outputs
Hello, X, Y, Z!
 It's really important that you get the syntax into your fingers.
 Do the Exercises from Section 1.1 (see
here at the
bottom, Exercises 1  5).
 If you wish to prepare for the lecture (otherwise, do this exercise
later!), enter the program
public class LeftAssociative {
public static void main(String[] args) {
final int a = Integer.parseInt(args[0]);
final int b = Integer.parseInt(args[1]);
System.out.println(a + " + " + b + " = " + a + b); // not what is meant
System.out.println(a + " + " + b + " = " + (a + b));
System.out.println(a + b + " + " + "13" + " = " + (a + b + 13)); // understand this
}
}
 Play around with it, and understand what it is doing.
 The key is to understand that we have variables of two types,
int
and String
, and that automatic conversions
are performed from int
to String
if needed.
 Week 3 (20/10/2016):
 Consider the exercises from Section 1.2 (see
here
Exercises 1  23).
 Exercises 1.2.1  1.2.14 are about understanding expressions.
 Write little programs which compute the expressions, possibly
for all inputs (especially in the case of boolean expressions).
 If you wish to write a new program, consider 1.2.14  1.2.23.
 If you wish to prepare for the lecture, enter the three programs from
the lecture/book (Flip, PowersOfTwo, Sqrt), run them with all sorts of
different arguments, understand the outcome.
 Especially try to crash the programs (missing or
strange inputs, very large or very small numbers, ...).
 Week 4 (27/10/2016):
 Write a program which reads two integers and prints them out sorted
in ascending order.
 Write another program which reads three integers and prints them
out sorted in ascending order.
 Write better versions of "TenHellos.java" (printing "Hello World!"
ten times), using first a whileloop and then a forloop. Which
is better?
 Consider exercises 1.3.1  1.3.7 from the book (see
here);
perhaps first considering exercises 1, 3, 4 (perhaps writing a complete
program), 6 (again perhaps writing programs to testing your answer)
and 7.
See here
for solutions. Additional exercises:
 Write a program which reads an integer N and computes the sum
1 + 2 + ... + N.
 Write a program which reads an integer N and computes the product
1 * 2 * ... * N; choose a suitable data type so that some interesting
computations can be performed!
 Enter the program "Gambler" from the lecture, and play around with
it a bit.
 Improve the output of "Gambler":
 Print out the inputs, with additional explanations.
 Print out the frequency wins/T (where T is the number of
trials).
 Print out the probability stake/goal of winning.
 Print out the expected number of steps (stake)*(goalstake).
 Finally determine the average and the maximum number of steps
it took to finish a trial (that is, the number of steps until cash
either is 0 or goal), and print it out.
 Consider exercises 1.3.8  1.3.31 from the book (see
here).
 Week 5 (3/11/2016):
 Write a program "Deck32" (recall "Deck"), which uses only a deck of
32 cards, where the ranks do not include 2 up to 6.
 Now combine "Deck" and "Deck32" into one program, where via a
commandline argument it is decided whether 32 or 52 cards are to be
used.
 Consider exercises 1.4.1  1.4.9 from the book (see
here).
 Consider exercise 1.4.35 from the book ("Birthday.java", see
here).
 Week 6 (10/11/2016):
 Consider exercises 1.5.1  1.5.3 from the book (see
here):
 Write a program that reads in integers (as many as the user
enters) from standard input and prints out the maximum and minimum
values. Before entering the program, make a sketch on paper.
 Modify this program by rejecting nonpositive entries, asking the
user to reenter the input (until he gets it correct). Before
entering the program, extend the previous sketch. Hint: a whileloop
is appropriate for testing the input values.
 Read N from the commandline and N floatingpoint number from
standard input, and compute their mean value. Create an error message
if not enough numbers were entered. Compute also the standard
deviation as the square root of the sum of the squares of the
differences from these numbers and the average, the whole then divided
by N1. Hint: For this computation you could store the numbers in
an array.
Always test your programs thoroughly!
 Consider exercise 1.5.7 from the book: Read in N from the
commandline plus N1 integers from 1 to N from standard input, assuming
that these numbers are different. Now determine the missing number (from
the interval 1 .. N).
 Additional exercises:
 Consider exercise 1.5.5 from the book:
Write a program LongestRun.java that reads in a sequence of integers
and prints out both the integer that appears in a longest consecutive
run and the length of the run. For example, if the input is
1 2 2 1 5 1 1 7 7 7 7 1 1, then your program should print
Longest run: 4 consecutive 7s.
 Improve
PlotFilter.java
by not asking for the minimum x/y values, but computing them from
the input (so the first four special doubles from standard input are
not needed anymore). Test with
USA.txt, where you
removed the first four numbers.
 Week 7 (17/11/2016):
 Consider exercises 2.1.1  2.1.4 from the book (see
here).
 As additional exercises you can consider 2.1.13, 2.1.14 and 2.1.17.
 Week 8 (25/11/2016):
 If you didn't finish the exercises from last week, then please
finish them now (we are still on functions).
 Consider exercises 2.1.5, 2.1.12, 2.1.18, 2.1.19 and 2.1.20
from the book (see
here).
 For exercise 2.1.18, if for example the input is the array
(1,3,7), then the output should be (0,3/7,1). And if the
input is (10,4,1), then the output should be (0,6/9,1).
 Additional exercises on multidimensional arrays:
 Hardcode a 3 x 3 array of integers with the values
1 2 3
4 5 6
7 8 9
and print it out.
 Write a function
print_array(A)
in a class
PrintArray
which prints out an arbitrary twodimensional
array of integers, rowwise. Handle the general case, where every row
can have a different length. And if nullpointers occur for a row
, then print "[null]", while if the whole array is null, then print
"[[null]]" (no exceptions should be thrown).
 Add a main function to class
PrintArray
which tests
function print_array(A)
.
 Read natural numbers M and N from the command
line, specifying an M x N array of integers. Then read from standard
input (using
StdIn
) rowwise these M*N many integers,
and store them in an array. Finally print them out, using
PrintArray.print_array
.
See here for
solutions.
 Week 9 (1/12/2016):
 See the two exercises above
(writing programs
AlbersSquares
and Grayscale
).
 Further exercises using the data types "Color" and "Picture" from
the lecture (see above):
 Exercise 3.1.2 from the book: Write a program that takes from the
commandline three integers from 0 to 255 (representing red, green
and blue), and then creates and shows a 256by256 picture of that
colour.
 Exercise 3.1.3 from the book: Modify program "AlbersSquares" to
take nine commandline arguments, representing now three colours, and
then draw the 3*2=6 squares showing all the Albers squares with the
large square in each colour and the small square in each different
colour.
 Exercise 3.1.6 from the book: Write a program that takes the name
of a picture file as a commandline input, and creates three images,
one that contains only the red components, one for green, and one for
blue.
 Exercise 3.1.4 from the book:
 Write a program that takes the name of a grayscale picturefile
as a commandline argument, and plots a histogram of the frequency
of occurrences of each of the 256 grayscale intensities.
 Use the library "StdStats" from Section 2.2 (provided
here ).
 Another (simple) arrayexercises:
 Read N from the commandline.
 Create an NxN array A of integers, where the first row contains
0,1,..., the second row contains 1,2,..., and so on.
 Then add all the numbers on the principal diagonal (that is,
A[0,0] + A[1,1] + ...), and print out the result.
 You can easily check whether your program works: the result should
be N*(N1).
 Use one function for creating the array.
 And use another function for computing the diagonal sum.
The solution is
here
.
 Finally we practise using static data members ("static instance
variables"). Write a class
StringExample
:
 Containing (static) constants
size_a
of
value 4 and array a
containing the four strings "AB",
"XYZ", "EFG", "1234".
 We also have
size_b
of value 3, and array
b
containing the three strings "M1", "T3", "y6".
 Furthermore we have a static function
check_a
which
takes one string argument x, and returns integers from 0 to 3 if the
string x occurs in array a
with that index, while
otherwise 1 is returned.
 And in the same vein we have
check_b
.
 Both functions must use a loop for checking the membership in the
respective array.
 The main programs reads pairs of strings from standard input (as
long as standard input has not been closed), and prints out the results
of
check_a, check_b
.
 For example "EFG T3" results in "2 1", and "X y6" results in
"1 2".
Here is
the solution .
 Week 10 (8/12/2016):
 Creating and using a trivial class:
 Write a class
Trivial
, which stores two integers (via
the constructor), and as member functions ("methods") allows to
compute their sum and product, and translation to strings.
 The objects of this class must be immutable.
 Furthermore allow equalitycomparison, where two
Trivial
objects are considered equal if (and only if) the
members are equal independent of their order.
 And finally write a method
multiply
, which takes an
integer as argument, and multiplies the object with this number. Note
that you can't modify the object itself.
 Write then a program
Client
, which reads four
integers from the commandline, creates two objects of type
Trivial
accordingly, and outputs their sums and products
and the objects themselves, and whether the two objects are equal, and
finally outputs the multiplications of the second object with the sum
of the first object.
Here is
the Trivialsolution , and here is the
Client .
 For example via
int[] a = null;
System.out.println(a);
we can see an arrayobject whose value is null
.
Can you create an arrayobject with value null
without
explicitly assigning null
? Study the
solution .
 On "length":
 What is the technical reason that one uses
a.length
for an array, but s.length()
for a string?
 Could there be an underlying designreason?
 See
here
for some demonstration.
 Study "Charge.java" and "Potential.java", understand how it works,
and play a bit around (using for example "charges.txt" as input).
 Study
Turtle.java and the application
Spiral.java ;
play a bit around with it, and write your own clients of class Turtle,
creating some simple turtlegraphics.
 Week 11 (15/12/2016):
 Concluding exercises.
 Additional exercises:
 More on arrays (and static functions):
 Counting random events:
 Write a program (class) "RandomNumbers" which takes two
commandline arguments M and N.
 The program then creates N many random integers in the interval
[1, M], counts how often each of these integers occurs, and then
prints out the relative frequency for each of these M numbers (that is,
the quotient "occurrences / N").
 Your program should work for large N, and thus should not store
the N random numbers computed.
 For the creation of the random integer write a function
random(M)
, which takes M as parameter, and returns a
random integer from 1 to M.
 Hint: you need to use an integerarray of size M for performing
the counting.
Here is
the solution .
 More on modules (or "libraries"):
 Implement the library class StdStats with (just) the static
functions "min", "max" and "mean".
 Write a program "Stats" which is called with floating point
numbers as commandline parameters, and which computes their
minimum, maximum and average, using your library StdStats.
 For example, "Stats 4 5.2" would yield min=4, max=5.2,
mean=4.6.
 Parsing strings (using methods from the
String
class)
 Read a string from the commandline and determine how many
spaceseparated parts it has.
 Modify the solution of the previous part, where now the string is
split at the symbol "@".
 Again, play around with it (what happens when spaces are used?).
 Here is a
solution
which again shows the parts with their indices.
 Parse a string, where you extract all digits from it, adding them
up, returning their sum and the original string without these digits:
 Recursion (we didn't do that section from Chapter 2):
 Enter the program "Htree" from the book.
 Write a modified program "Htree2", which asks for confirmation
before continuing drawing parts of the tree.
 Also print out appropriate messages, so that you can follow in
detail the recursion.
 Run the program for inputs up to 4, and make sure you understand
what's going on!
Here is
a solution .
Coursework
First coursework
 Available on Blackboard.
 Deadline for submission is Tuesday 22/11/2016, 11:00.
 See Debugging notes for some help on how
to handle syntax and runtimeerrors.
 You will obtain a personal email with comments on your program and
your mark (explained).
 A solution is provided.
Second coursework
 Available on Blackboard.
 Deadline for submission is Wednesday 14/12/2016, 11:00.
 You will obtain a personal email with comments on your program and
your mark (explained).
 There will be a solution provided.
Links
 A
Git repository is available, where you can download the source
code repository.
 There you also find C++ versions.
Reading