CSci 151: Foundations of computer science II
Home Syllabus Assignments Tests

Review 9: Java review: Questions

9.1.1.

How does a class variable (declared static) differ from an instance variable?

9.1.2.

Consider the following Java method.

public void printTwiceAll(List lines) {
    for(Iterator it = lines.iterator(); it.hasNext(); ) {
        System.out.println(2 * Integer.parseInt(it.next()));
    }
}

For each of the following identifiers in this fragment, choose which of the items at right best describes it. (Answers may repeat.)

a. System
b. out
c. println
d. parseInt
e. it
f. next
A. keyword
B. class
C. instance method
D. class method
E. local variable
F. instance variable
G. class variable
9.1.3.

Given the two classes below, what will main print?

public class Worker {
    private String job;

    public Worker(String val) {
        job = val;
    }
    public void setJob(String val) {
        job = val;
    }
    public String getJob() {
        return job;
    }
}
public class Main {
    public static void main(String[] args) {
        Worker you = new Worker("student");
        Worker me = new Worker("professor");
        Worker it = you;
        you = me;
        me.setJob("millionaire");
        System.out.println(it.getJob());
        System.out.println(you.getJob());
        System.out.println(me.getJob());
    }
}
9.1.4.

Define a class named Averager for tracking the average of a sequence of numbers. The class should include the following methods.

Averager()

(Constructor) Constructs an object for tracking the average of a sequence of numbers. Initially, the sequence is empty; the average of an empty sequence is 0.0.

void add(double value)

Updates this averager to include value among its sequence.

double getAverage()

Returns the average of the current sequence.

Note that Averager does not need to remember all the values it is given; to do its job, it only needs to track the total of the numbers seen, and the number of numbers seen.

The following method illustrates how another class might use your Averager class.

public static void run() {
    Averager avg = new Averager();
    System.out.println(avg.getAverage()); // prints "0.0"
    avg.add(5.0);
    avg.add(8.0);
    System.out.println(avg.getAverage()); // prints "6.5"
    avg.add(8.0);
    System.out.println(avg.getAverage()); // prints "7.0"
}
9.1.5.

Define a class named Point to represent a point in two-dimensional Cartesian space. The point class should include the following methods.

Point()

(Constructor) Constructs a point at location (0, 0) in the Cartesian plane.

Point(double xcoord, double ycoord)

Constructs a point at location (xcoordycoord) in the Cartesian plane.

void translate(double dx, double dy)

Moves the point by (dxdy). In traditional Cartesian coordinates, this would move it dx units to the right and dy units up.

double distanceTo(Point other)

Computes the distance to other from the point asked. For example, if x is the point (0, 0) and y is the point (3, 4), then x.distanceTo(y) should return sqrt((0-3)² + (0-4)²) = 5.

The following method should work as indicated using your class.

public class PointTest {
    public static void main(String[] args) {
        Point origin = new Point();
        Point pt = new Point(3, 4);

        System.out.println(pt.distanceTo(origin)); // prints 5.0

        pt.translate(2, 8); // translates to (5,12)
        System.out.println(pt.distanceTo(origin)); // prints 13.0
    }
}
9.1.6.

Write a class definition Interval for representing an interval of numbers. The class should incorporate the following methods.

Interval(double a, double b)

(Constructor) Constructs an object representing the range of numbers between a and b, inclusive. The constructor may assume that a < b.

void add(double x)

Extends this interval, if necessary, so that x is included within this interval.

boolean contains(double q)

Returns true if this interval contains the number q.

The below program fragment illustrates how a different class might make use of your class.

Interval range = new Interval(4, 10);
System.out.println(range.contains(2)); // displays false
System.out.println(range.contains(4)); // displays true
System.out.println(range.contains(6)); // displays true
range.add(2);
System.out.println(range.contains(1)); // displays false
System.out.println(range.contains(2)); // displays true
System.out.println(range.contains(3)); // displays true
9.2.1.

Define the term inheritance as it applies to Java classes, and explain how one can specify inheritance in Java code.

9.2.2.

Given the three classes below, what will main print?

public class Rectangle {
    private int height;
    private int width;

    public Rectangle(int h, int w) {
        height = h;
        width = w;
    }
    public String getName() {
        return "Rectangle";
    }
    public void printData() {
        System.out.println(getName()
            + " " + width + "x"
            + height);
    }
}
public class Square extends Rectangle {
    public Square(int dim) {
        super(dim, dim);
    }
    public String getName() {
        return "Square";
    }
}

public class Main {
    public static void main(String[] args) {
        Square s = new Square(20);
        Rectangle r = s;
        System.out.println(s.getName());
        System.out.println(r.getName());
        s.printData();
        r.printData();
    }
}
9.3.1.

Suppose that List is an interface, and ArrayList is an implementation of that interface. Both List and ArrayList contain size and add methods.

For each of the following fragments, would it compile as written? (At least one of them would.) For each of the other(s), explain why not and how you could repair it so it would compile.

a.
boolean isEven(List l) {
    return l.size() % 2 == 0;
}

void run() {
    List l = new List();
    if(isEven(l)) {
        // ...
b.
boolean isEven(List l) {
    return l.size() % 2 == 0;
}

void run() {
    List l = new ArrayList();
    if(isEven(l)) {
        // ...
c.
boolean isEven(ArrayList l) {
    return l.size() % 2 == 0;
}

void run() {
    List l = new ArrayList();
    if(isEven(l)) {
        // ...
d.
boolean isEven(String s) {
    return s.length() % 2 == 0;
}

void run() {
    List l = new ArrayList();
    l.add("a string");
    if(isEven(l)) {
        // ...
9.3.2.

Java has both interface and abstract class types, and it prevents users from creating objects of either directly. Instead, objects of these types must be instances of an implementation (in the interface's case) or a subclass (in an abstract class's case).

Neglecting differences in terminology and syntax (e.g, using implements for an interface rather than extends as with an abstract class), how are the two concepts different? That is, why would a programmer choose one or the other?

Review 9: Java review: Solutions

9.1.1.

A class variable exists at only one place in memory, no matter how many objects of that class are created; in some sense it is shared by all instances of the class. With an instance variable, every object of the class has its own value for that variable.

9.1.2.
a. System B. class
b. out G. class variable
c. println C. instance method
d. parseInt D. class method
e. it E. local variable
f. next C. instance method
9.1.3.
student
millionaire
millionaire
9.1.4.
public class Averager {
    private double total;
    private int count;

    public Averager() {
        total = 0.0;
        count = 0;
    }

    public void add(double value) {
        total += value;
        count++;
    }

    public double getAverage() {
        return total / count;
    }
}
9.1.5.
public class Point {
    private double x;
    private double y;

    public Point() {
        x = 0.0;
        y = 0.0;
    }

    public Point(double xcoord, double ycoord) {
        x = xcoord;
        y = ycoord;
    }

    public double distanceTo(Point other) {
        return Math.sqrt(Math.pow(x - other.x, 2.0)
            + Math.pow(y - other.y, 2.0));
    }

    public void translate(double dx, double dy) {
        x += dx;
        y += dy;
    }
}
9.1.6.
public class Interval {
    private double lo;
    private double hi;

    public Interval(double a, double b) {
        lo = a;
        hi = b;
    }

    public void add(double x) {
        if(x < lo) lo = x;
        if(x > hi) hi = x;
    }

    public boolean contains(double q) {
        return lo <= q && q <= hi;
    }
}
9.2.1.

A Java class can be written to inherit all the instance methods and instance variables of another class using the keyword extends.

public class MyClass extends SuperClass {

Without any further code, any methods defined in SuperClass will now be defined identically for MyClass also.

9.2.2.
Square 20x20
Square 20x20
Square
Square
9.3.1.
  • a. This would not compile, since List is an interface, and so we cannot create a List object (as with new List()). To fix this, we need to retrieve a string from the list (perhaps via a get method).

    List l = new ArrayList();
    
  • b. This would compile.

  • c. This would not compile, since isEven expects an ArrayList, and the type of the l variable is a List. We can fix this by casting l into an ArrayList before calling isEven:

    if(isEven((ArrayList) l)) {
    

    It also works if we simply revert to a.

  • d. This would not compile, since isEven expects a String, and the parameter passed is an ArrayList. If we actually want to pass a String from the ArrayList to isEven, then we would need to use the get method.

    if(isEven(l.get(0))) {
    
9.3.2.

Unlike abstract classes, Java interfaces cannot include any instance variables, and all methods must be abstract (i.e., they cannot have implementations defined). If we want our type to define instance variables or default behaviors for methods, then, we must choose an abstract class.

An alternative answer is that abstract classes suffer under Java's restriction that each class can extends only one other class. Thus, if we want to allow a class to be a subclass of another class but implement our type also, we need to use interfaces.