Programming in Java
Supervision 2
Foreword If you comment your code, so will I!
If any of the following is unclear, please let me know.
If
I have a variable ‘word’ of type String. It can have any of the following and only any of the following values: “Rowing”, “is”, “good!” Give the most elegant solution you can to the problem of distinguishing between the values. For example, depending on the value of ‘word’, how could ‘word’ be set to 1 of 3 other words?
Java vignette
State and explain the output of the following code:
public
class Vignette
{
public static
void main(String[] args)
{
double
value = 6.54;
try
{
value
= 1 / 0.0;
}
finally
{
System.out.println(value);
}
value
= 6.54;
try
{
value
= 1 / 0;
}
finally
{
System.out.println(value);
}
}
}
Visibility
If class A has a public method n,
private method m and protected member b of type A, can m
or n
be invoked on the instance b, from within class A?
Equals
State with explanation, the output of this code. Try to work out the output before running it!
public
class DeepCopy
{
public static
void main(String[] args)
{
X
x1 = new X();
X
x2 = new X();
x1.a
= true;
x2.a
= false;
if
((x2 = x1) instanceof X) {System.out.println("Bones");}
x2.a
= false;
if
(x1 == x2) {System.out.println(x1.a);}
x1
= new X();
x1.a
= false;
if
(x1 == x2) {System.out.println("McCoy");}
if
(x1.a = x2.a) {System.out.println("Crisps");}
}
}
public
class X
{
public boolean a;
protected int say = 0;
protected int shout = 0;
public X()
{
}
public void m()
{
System.out.println("X's m");
}
static public void n()
{
System.out.println("X's n");
}
public void o()
{
System.out.println("X's o");
}
public void say()
{
System.out.println(say);
}
public void shout()
{
System.out.println(shout);
}
}
Finally a violation!
Write some code to illustrate 3 different ways in which the presence of the keyword final would causes a compile error.
Inheritance and method & member bindings (again!)
State and explain the output of the following program. Try to work it out before you run it! The files X.java and Y.java are provided.
public
class Bindings
{
public static
void main(String[] args)
{
X
x = new X();
x.m();
x.say();
x.shout();
Y
y = new Y();
y.m();
y.say();
y.shout();
X
z = new Y();
z.m();
z.n();
z.say();
y.n();
z.o();
z.shout();
//z.whisper(); // Doesn't compile
//z.super.o(); // Doesn't compile
}
}
public
class X
{
public boolean a;
protected int say = 0;
protected int shout = 0;
public X()
{
}
public void m()
{
System.out.println("X's m");
}
static public void n()
{
System.out.println("X's n");
}
public void o()
{
System.out.println("X's o");
}
public void say()
{
System.out.println(say);
}
public void shout()
{
System.out.println(shout);
}
}
public class
Y extends X
{
protected int say = 1;
protected int shout = 1;
public Y()
{
}
public void m()
{
System.out.println("Y's
m");
}
static public void n()
{
System.out.println("Y's n");
}
public void o()
{
super.o();
System.out.println("Y's o");
}
public void shout()
{
super.shout
= 2;
super.shout();
System.out.println(shout);
}
public void
whisper()
{
System.out.println(3);
}
}
Vocab Test
Explain what the following java keywords mean and how you would use them.
Type and Base converting
Write a file Convert.java
that reads in a value from the keyboard and only if numbers (0-9) have been
typed in, (rather than textual/whitespace characters) converts this number (in
base 10) to a String that represents the value in base 2. If illegal characters have been entered,
terminate, having stated so.
Hint: You might have to play the detective again and investigate the methods of the classes used in the following skeleton program, in case you need help getting started.
import
java.io.*;
//There
are many ways of doing this!
public
class Convert
{
public static
void main(String[] args)
{
BufferedReader
in = new BufferedReader(new InputStreamReader(System.in));
// try
{
System.out.print("Enter
value: ");
}
// catch
(Exception e) {}
}
private static
String convertToBinary(long num)
{
}
}
Bit manipulation
Extend the file Convert.java further, by carrying out a bit-wise exclusive OR operation on the first and last numerical characters entered. Print out the result in BigEndian format.
Interfaces
Sometimes using interfaces can be useful, as it allows people to initially and quickly define a concrete set of functions. One party can then implement these functions, whilst another makes use of them somewhere else in the program, assuming that they will behave as specified.
Another reason for using interfaces is to provide a form of inheritance, as many different implementations of an interface could exist. Why not just use normal inheritance you ask!? Indeed, why not? A strong argument is that java doesn’t allow multiple inheritance (which could be considered a wise move, as it can get rather complicated!), but it does allow you to implement multiple interfaces and therefore still be able to set up levels of abstraction.
1. For the following provided interface below, give 2 different ideas for how a stack could be implemented but would always meet the specifications given by the interface.
2. Implement one of your ideas in a file Stack.java.
public
interface SortableStackInterface
//This
represents an interface to a Stack data structure, that should be able to store
any object, AS LONG AS
//the
type of the object conforms to the 'SortableObject' interface.
{
public void
push(SortableObject o);
public
SortableObject pop();
public boolean
isEmpty();
public boolean
isFull();
public int
size(); //
Number of items in the stack at the moment
public int
capacity(); // Total capacity of
the stack
public void
clear();
public void
sort(int order); // order is to represent whether
elements are to be sorted ascendingly or decendingly, starting with the
top/head of the stack
public boolean
sorted(int order); // order is to represent whether elements sorted ascendingly
or decendingly, starting with the top/head of the stack
public
SortableObject[] toArray(); // return an array which just contains the items in
the stack, and is just teh right size to do so.
}
Towers of
Using the classes Stack and Disc (provided) implement a program that solves the Towers of Hanoi puzzle.
The basic puzzle is as follows: There are 3 posts. There are N rings of size 1 to N. The game starts with all rings stacked on top of each other, around the first post, in descending order, to form a pyramid. At no point during the game, can a larger ring be on top of a smaller ring. The object of the game is to move one ring at a time (by taking it off the top of the pile around one post, and putting it on the top of a pile around another post) and manage to transfer the entire original column from the first post to the last post.
Starting state Ending state



Your program should accept an initial state. Assume there will always be three posts, but an arbitrary number of discs passed as a cmdline argument. These should always be set up in the correct starting state. The program should then display somehow (text output is sufficient) all of the steps required to complete the puzzle; i.e. a list of “picture” showing all the intermediate states and ending state.
Hint: Use recursion to solve the problem without the largest disc! (and your initiative if necessary!)
Singleton
Sometimes it is sensible to only be able to instantiate one instance of a class. In this case, it is wished to model the solar system. Create classes Star, Sun (a type of Star) and Planet, and ensure that it is only possible to create one Sun. Write a test program to show this in action.
Hints: This
is an example of the Singleton Design Pattern.
The
idea is not to be able to go ‘Sun s = new Sun()’
The ‘new’ keyword effectively calls the constructor of a class
Multiple inheritance with interfaces
In the Interfaces question above, it was chosen to use one interface called SortableStackInterface, rather than two separate interfaces called Sortable and StackInterface. Discuss, briefly, why this might have been done and why it might be better to take the other approach.
A consideration during programming
Sometimes it is wished to use (and even define a custom) set of alternatives. List the pros and cons of using the following methods:
Polymorphism
What is polymorphism. Give an example.
Static – 3 uses,
Explain and give examples of 3 ways in which the keyword static is used in java. These will be with respect to methods, members and initialisation of members.
Nearly there!
Have a go at these past exam paper questions from 2001 and 2005
Paper 1, Question 9, 2001
For each of the following
areas, write brief comments on the way in which Java and its libraries have
been designed to try to prevent programmers from making undetected errors and
to ensure that code runs on all possible brands and models of computer,
yielding the same results in each case.
(a) Programmers who get
mildly confused about syntax or who make typing errors. [4 marks]
(b) Groups of programmers
working on libraries that will form part of some large project. [4 marks]
(c) Numbers, characters,
trig functions and so on. [4 marks]
(d) Opening files, reading
or writing and then closing them.
[4 marks]
(e) Other features of Java
not falling centrally within any of the above categories. [4 marks]
Paper 1, Question 9,
2005
The following code has
been written by a novice Java programmer. You are not required either to understand
or to debug the details of how this code draws some particular pattern (a
“Dragon”).
The programmer finds that
the Java compiler complains. Identify any errors and comment on any issues that
(even if not strictly invalid Java) are liable to cause problems. You are not
required to provide corrections.
***********************************
**
Supervison work for June 6th. **
***********************************
upper
class Dragon extends JApplet throws Exception
{
import javax.swing.*;
public paint(Graphics g)
{
this.g = g;
drawDragon(DRAWDEPTH,100,200,300,200);
}
/**
@title: drawDragon
Function to draw a dragon curve between too points
(x1,y1) and (x2,y2) with depth 'depth'.
*/
void
protected drawDargon(int depth,
int x1,int y1,int x2,int y2)
{
if (x1 < 0 | x2 < 0)
if (y1 < 0) raise new Exception("X & Y
< 0");
else assert("Ok so far");
if (depth = 0) // bottom of recursion
{ g.drawLine(x1,y1,x2,y2);
continue;
int mpx=(x2+x1+y2-y1)/2; /* X coord of a new
point...
int mpy=(y2+y1-x2+x1)/2; ... and Y coord. */
printf("DEBUG: x=
drawDragon(depth-1,mpx,mpy,x1,y1);
drawDragon(depth+1,mpx,mpy,x2,y2);
}
static
secret int DRAWDEPTH=15,
Graphics g;
}
Detective Programming : A Priority Queue for a
Multi-Theaded program
The task here is to create 2 instances of the same class that extend the Thread class. These would be deemed producers of objects of type TimeStampedObject (for which the class is provided). The constructor for this class takes 2 arguments: the ID number of the thread that constructed it, and the current system time. The time should be obtained using the System.nanoTime() function, which is a very accurate current system time.
The two producer objects should repeatedly, forever, create
TimeStampedObjects and pass them, via a shared variable (java.util.concurrent.PriorityBlockingQueue) to the main program.
This main program should
instantiate and start the producers, and then read the queue and print out the
objects send down it, using the getText() method in the TimeStampedObject
class.
The idea is that, even through the
threads might get interrupted halfway through executing, due to a context
switch, the priority queue makes sure that even if an unordered set of objects goes
in, a correctly ordered list will come out and so the timestamps should be
printed out in chronological order!
Good luck!