My exams tend to have three to six questions. They are closed book, closed notes. I prefer to ask questions with objective answers. Mainly, I will ask you to draw diagrams, describe what happens when a piece of code is executed, and to write code. You will have the entire class period to finish the exam. Midterms emphasize the material covered since the last midterm. Final exams are comprehensive. The exam questions are mostly based on the homework, text, and lectures.
There are three levels of understanding. From lowest to highest they are:
Level 1: Ability to understand explanations of others
Level 2: Ability to solve new problems
Level 3: Ability to explain material to others
You need to attain level 2 in order to pass the exam. This means you have read and understood your notes, reviewed your homework, and reviewed previous exams (level 1).
Beyond that, you have invented and solved variations of the problems discussed in class. (Level 2).
To attain Level 3, form a study group and take turns explaining the material to each other. If someone in the group gives a lazy or bad explanation, let him have it!
I tend to give away a lot of information in the review
session.
Know the definitions of the following concepts:
M0: processors and the fetch-execute cycle, primary memory (RAM), secondary memory (disk drives, CD drivess, etc.), I/O devices (keyboard, monitor, modem, ports, etc.), binary instructions and data.
M1: Examples of operating systems, file systems (files and directories), command shell prompts, shell commands (dir, cd, etc.)
M2: Examples of high level languages, compilers, the Java virtual machine
M3: Examples of computer application domains
What does the Java compiler (javac) do?
What does the Java Virtual Machine (java) do?
What is in a .class file? How are .class files created? Located?
A running program processes and stores data. The individual data items are called values. Examples of values include numbers, text, records, and collections. Of course values can be nested inside of other values. For example, campusClubs might be the name of a collection of collections of student records containing the student's name (text) and GPA (number).
Values can be classified according to their types:
Primitive Types
boolean, char, int, double, etc.
Reference Types
object (String, Rectangle, JFrame,
Double, etc.)
array
A variable is a named container in memory that holds a primitive value or a reference (a.k.a. address or pointer) to an object or array. We can use box-and-pointer diagrams to depict variables. For example, executing the declaration:
Account savings = new Account(100);
creates a variable named "savings" containing a reference to a new instance of the Account class which contains a variable (i.e., a field or instance variable) named balance and containing a number (i.e., the amount of money in the account). Here's a box-and-pointer diagram depicting the situation:
The most important kinds of values in an object-oriented program are objects. An object is a value that encapsulates (i.e., contains) variables. The variables contained in an object are called fields or instance variables. For example:
savings.balance
savings.password
savings.holder
We can also send a message to an object. For example:
savings.deposit(100.25, "Joe Smith", "*******")
When an object receives a message it performs some task. These tasks are called methods. A method may update an instance variable, return some information to the sender, or send a message to another object and wait for the reply.
A class is a template for creating objects. The objects created from a class are called instances of the class. A package is a named collection of related classes and sub-packages. A package may represent a class library (java, java.util, java.awt, java.awt.geom, etc.) or a sub-system (ui, business, dbase, etc.).
package.subpackage.class.object.method(inputs);
class Account {
private double balance;
private String holder = null;
private String password = null;
public Account(String holder,
String password) {
this.holder = holder;
this.password = password;
balance = 0;
}
private void validate(String usr,
String pswd) {
if (!holder.equals(usr) ||
!password.equals(pswd)) {
System.err.println("invalid
id or password");
System.exit(1);
}
}
public void deposit(double amt,
String usr, String pswd) {
validate(usr, pswd);
this.balance = this.balance -
amt;
}
public void withdraw(double amt,
String usr, String pswd) {
validate(usr, pswd);
if (this.balance < amt) {
System.err.println("insufficient
funds");
System.exit(1);
}
this.balance = this.balance - amt;
}
public double getBalance(String
usr, String pswd) {
validate(usr, pswd);
return balance;
}
}
A statement is the smallest unit of code that can be executed.
A statement is specified by its syntax (form) and its semantics (behavior when executed).
A nested statement contains sub-statements. Of course a sub-statement may contain sub-sub-statements and so on and so on until we reach simple statements that contain no nested sub-statements.
There are three major types of statements: declarations, expressions, and commands.
When executed, a declaration introduces a new value[1] and gives it a name. For example the following declaration introduces a new class named "Radio":
class Radio {
double station;
void tune(double newStation) { station
= newStation; }
}
The declaration contains two sub-declarations: the declaration of a variable named station and the declaration of a method named tune.
Consider the following statements:
int count = 10;
count = count - 1; // now count = 9
The first statement is a declaration that introduces a new variable named count that holds integers. The declaration also initializes this variable to 10.
The second statement is an assignment command. It updates the value stored in count. More specifically, the new value will be one less than the old value.
Attempting to update an undeclared variable is an error:
count = 9; // Error: count hasn't been declared yet!
int count = 10;
An expression produces a value when it is executed. Here are some examples:
Math.sqrt(x * x + 12)
(x - 6) < Math.PI
(isAuthorized(user) || isValid(user)) && amount <= balance
There are two types of commands: data control and sequence control.
Executing a data control command copies a value from one location in memory to another. Data control commands include assignment commands, input commands, and output commands. Here are some examples:
response = keyboard.nextDouble(); // input command
result = Math.sqrt(response); // assignment command
System.out.println(result); // output command
Normally, the processor's fetch-execute cycle executes statements in order of their appearance. Executing a sequence control command allows us to alter this simple pattern. There are four types of sequence control commands: blocks, conditionals, iterations, and escapes.
A block is a sequence of statements (declarations, expressions, and commands) that is regarded as a single command:
{STATEMENT; STATEMENT; ... STATEMENT;}
Blocks are useful for representing multi-step tasks such as the body of a method or loop. Variables declared in a block are only visible from the point of declaration to the end of the block.
if (CONDITION) CONSEQUENCE; else ALTERNATE;
while (CONDITION) TASK;
Escape commands allow us to jump to another part of the program. The following countDown method contains six escapes:
class LaunchMissle {
int count = 10;
int status = AOK;
void countDown() {
while(0 <= count) {
count = count - 1;
updateStatus();
if (status == HURRY) break;
if (status == AOK) continue;
if (status == ABORT_COUNT) return;
if (status == ABORT_LAUNCH) System.exit(1);
}
blastOff();
}
// etc.
}
From java.lang
Math
System
Double
Integer
String
From java.util
Date
Scanner
From java.awt
Graphics
Graphics2D
Color
Point
Rectangle
From java.awt.geom
Point2D.Double
Line2d.Double
From javax.swing
JFrame
JComponent
1. Assume the following declarations have been executed:
int x = 10;
String state = "
What values are produced when the following expressions are executed:
2 * x + 3
2 * (x + 3)
x/3
x%3
x/0
(double)x
5 < x && x < 6 || x % 2 == 0
Math.ceil(-Math.PI)
Math.floor(-Math.PI)
Math.trunc(-Math.PI)
1e-20 < 0
state.index('a');
state.length()
state.substring(4, 7)
state.replace('a', 'x')
state == "
state.equals("
state.compareTo("
String.valueOf(x)
state + 18 + 49
state + (18 + 49)
2. Assume the following declarations have been executed:
int count = 10, row = 0, col = 0;
What output is produced when the following commands are executed:
{
if (true)
if (false)
System.out.println("x");
else System.out.println("y");
System.out.println("z");
}
while(count <= 10) {
if (count % 2 == 0)
System.out.println(count);
count = count + 1;
}
while(0 < count) {
if (count % 2 == 0)
System.out.println(count);
count = count + 1;
}
while(row < 5) {
while(col < row) {
System.out.print("*");
col = col + 1;
}
row = row + 1;
System.out.println();
}
while (0 < count) {
count = count - 1;
if (count % 2 == 0) continue;
if (count < 3) break;
System.out.println(count);
}
while(0 < count) {
switch(count) {
case 0: case 2: case 4:
System.out.println(count);
case 3: case 5:
System.out.println(-count); break;
case 6: case 7: case 8:
System.out.println("skip");
default:
System.out.println("ok");
}
count = count - 1;
}
3. Assume the following declarations have been executed:
class Money {
int cents;
Money(double dollars) {
cents = 100 * dollars;
}
// etc.
}
class Account {
Money balance;
Account(double dollars) { balance = new
Money(dollars); }
// etc.
}
Draw a box and pointer diagram showing the objects and variables created when the following declarations are executed:
Account savings = new Account(100.35);
Account checking = new Account(84.293);
4. How are static fields and methods different from non-static fields and methods? Give examples of how static fields and methods are typically used. Why does the main method need to be static?
5. Describe in detail what happens when the following commands are executed in a command shell:
javadoc Demo.java
javac Demo.java
java Demo
6. What is the difference between a parameter and an argument. Give an example.
7. A palindrome is a word or phrase that is spelled the same forward and backward. Here are some examples of palindromes:
Rotator
Mom
Yreka Bakery
abcdcba
A man a plan a canal
Doc note I dissent a fast never prevents a fatness I diet on cod
Implement a palindrome tester:
class PalindromeTester {
public static boolean
isPalindrome(String phrase) {
// ???
}
}
Remember, it's just the spelling that counts. It doesn't matter if letters are upper or lower case. Blank spaces also don't matter.
8. Implement a Circle class that satisfies the following test driver:
class TestCircle {
public static void main(String[] args)
{
Point center = new Point(2, 3);
int radius = 10;
Circle c = new Circle(center,
radius);
double area = c.getArea();
double circumference =
c.getCircumference();
// etc.
}
}
9. Unlike center and radius, area and circumference are derived attributes of a circle. They can both be computed from the radius. Should they be computed in the constructor and stored in fields or should we save memory and re-compute them each time the corresponding getter methods are called? How do things change if circles are mutable-- in other words, what if there are also setter methods that allow the user to change the center and radius of a circle?
10. Implement a Calculator class that satisfies the following test driver:
class TestCalculator {
public static void main(String[] args)
{
Calculator calc = new Calculator();
calc.setResult(Math.PI);
calc.cos();
calc.square();
double result = calc.getResult(); //
= square(cos(pi)) = 1
calc.setResult(4);
calc.exp();
calc.log();
calc.sqrt();
result = calc.getResult(); // =
sqrt(log(e^4)) = 2
// etc.
}
}
11. Initially, a character in a computer game has a name and 100 health points. He gains 3 health points each time he drinks a medicine bowl. He looses 10 health points each time he takes a blow from another character. A character's health cannot exceed 100 or be less than 0. A character is dead when his health is 0. He can't drink or fight if he's dead. Implement a Character class. Provide a method that allows users to increment the character's health by specifying the number of medicine bowls drunk. Provide a method that allows users to decrement the character's health by specifying the number of blows endured in a fight. Provide a method that allows a character to inflict a specified number of blows on another character.
12. Implement a test driver for your Character class.
13. Assume s1 through s5 are arbitrary statements, and assume the following declarations have been executed:
class A {
public int u = 100;
private int v = 200;
}
class B {
private int x;
public void meth1(int y) {
s1;
{
int z = 10;
s2;
}
s3;
}
public meth2(int a) {
s4;
s5;
}
}
Fill in the following table. Under each statement write Y to indicate that the variable is visible by the statement and N to indicate that it is not.
Variable s1 s2 s3 s4 s5
a
u
v
x
y
z
14. Assume the public interfaces for the following classes have been declared:
// instances represent declarations, expressions, and commands:
class Statement {
// executes this statement:
public void execute() { }
}
// A program is a list of statements:
class Program {
// = true if there is a next statement
to execute:
public boolean hasNext() {
return false; // for now
}
// returns the next statement to be
executed
public Statement next() {
return null; // for now
}
// = true if a runtime error occurs:
public boolean errorDetected() {
return false; // for now
}
}
Complete the implementation of the following class:
// instances represent computer processor units:
class Processor {
public void load(Program p) { }
public void fetchExecuteCycle() { }
}
How large (in bytes) is a value of type short? int? long? char? boolean? double? float?
Recall that t <: s means t is a subtype of type s. That implies values of type t can masquerade as values of type s. What are all of the subtype relationships among the types mentioned above? (Note, if s <: t <: u, you do not need to mention that s <: u.)
Describe the errors you see in this program:
public class Buggy {
private int f1 = 3.14;
private char f2 = "q";
private Double f3 = 3;
private static final String s =
"Hello!";
public void meth1(int x, int y) {
int var = 10;
s = s + "World";
return x + y + var;
}
public void meth2() {
System.out.println(var + 10);
}
}
The device tester class tests the Device class:
public class DeviceTester {
public static void main(String[] args)
{
Device d = new Device(2.3);
long x = d.blah(23,
"cow");
d.foo();
String s = d.arf(false, 'x');
}
}
Write a public interface for the Device class.
Here's a public interface, write a tester class for it:
public class MadDog {
public MadDog(double a, double b,
double c);
public double bite(String x);
public float snarl(int w, char f);
public String bark(String m);
}
Assume the following interface:
public class Averager {
public void addScore(double score);
public double getAverage();
public int getNumScores9();
}
Here's a tester class:
public class TestAverage {
public static void main(String[] args)
{
Averager avg = new Averager();
avg.addScore(1);
avg.addScore(2);
avg.addScore(3);
System.out.println(avg.getAverage());
System.out.println("Expected:
2.0");
}
}
Know the differences between main memory and secondary memory. These differences include speed, capacity, and volatility. What is a cell? What is an address?
Know the following terms: bit, byte, kilobyte (kb), megabyte (mb), gigabyte (gb), terabyte (tb).
Know what a processor is. Be able to define the Fetch-Execute cycle.
The processor's instruction set is called machine language.
Know how to translate binary numbers into signed or unsigned decimal integers.
Know what a file system is. What is a directory? A drive? Be able to give examp0les of operating systems.
Know the difference between a compiler and an interpreter.
Know the difference between machine language and a high-level language.
Be able to give examples of at least five high-level languages.
What is the purpose of the import statement?
A token is a string of characters containing no whitespace characters. A name is a token consisting only of letters, digits, and the characters '_' and '$'.
A name can be the name of a package, class, object, method, type, or variable
Classify each name in the Java command:
java.lang.System.out.println(Math.PI);
How is a static method different from a non-static method? Give an example from the Java library of a static and non-static method.
What output is produced when the following statements are executed:
for(int i = 0; i < 10; i++) {
for(int j = 0; j < i; j++) {
System.out.println(10 * i + j);
}
}
for(int i = 0; i < 20; i++) {
if (i % 2 == 0) continue;
if (i == 9) break;
System.out.println(i);
}
if (false)
if (false) System.out.println("A");
else System.out.println("B");
System.out.println("C");
Finish the following class:
class ArrayUtils {
static boolean search(Object[] vals,
Object val) {...}
static Comparable max(Comparable[]
vals) {...}
static double search(Measurable[] vals)
{...}
}
Finish the following class:
class ArrayUtils2 {
// squares each entry
static double[] square(double[] nums) {
... }
// sums entries
static double add(double[] nums) { ...
}
// replaces every 5th entry by 0
static double[] filter(double[] nums) {
... }
}
Assume you are given an experimental Java compiler. It's not clear if primitive values are passed by reference or by value. Write a program that prints "by-value" or "by-reference" depending on which parameter passing mechanism is used.
Is there any difference in the behavior of these two statements:
if (filter != null && filter.approve(item)) {
// process item
}
if (filter.approve(item) && filter != null) {
// process item
}
Given a viewer, create a component that displays:
Note that the position and size of the component (i.e., the bounding box) will be specified by the viewer. So be sure to provide fields and constructors for this. For example, the above rings have position (10, 10) and height = 40, width = 60.
Assume the following declarations:
Interface Movable {
void move(Point p);
}
class Animal implements Movable {
void move(Point p) { ... }
void bite() { ... }
}
class Car implements Movable {
void move(Point p) { ... }
void honk(Passenger p) { ... }
}
class Cat extends Animal {
void purr() { ... }
}
Movable x = new Cat();
Draw a UML diagram.
Which statements are legal:
x.purr();
((Car)x).honk();
(Cat)x.bite();
x.move(new Point(3, 4));
x = new Car();
Translate into UML:
A zoo has many cages. Each cage holds an animal. Bears and cats are types of animals. Lions and tigers are types of cats. Black bears and brown bears are types of bears.
Translate into Java:
[1] In addition to numbers, objects, and arrays, computer scientists also consider variables, classes, references, types, and methods to be values. This reduces their world to just two concepts: values and statements.