Second Summer 2002


Miscellaneous Items: Quizzes, Exams, and Such.
I include here a heterogenous collection of information that should help prepare for exams.

Possible Final Exam Short Answer Items

  1. What is the difference between a Java applet and a Java application?

    A Java applet is a Java program that is executed using a Web browser. Usually, the bytecode form of the Java applet is pulled across the Internet from another computer and executed locally. A Java application is a Java program that can stand alone. It does not require a Web browser in order to execute.

  2. What is the relationship between a high-level language and machine language?
    What is Java bytecode?

    High-level languages allow a programmer to express a series of program instructions in English-like terms that are relatively easy to read and use. However, in order to execute, a program must be expressed in a particular computer's machine language, which consists of a series of bits basically unreadable by humans. A high-level language program must be translated into machine language before it can be run.

    Java bytecode is a low-level representation of a Java source code program. The Java compiler translates the source code into bytecode, which can then be executed using the Java interpreter. The bytecode might be transported across the Web prior to being executed by a Java interpreter that is part of a Web browser.

  3. What is a variable?

    A variable is a place to store a value. It is the name we give to a memory location. When we refer to the variable name, we are referencing the value stored at the corresponding memory location.

  4. Name two specific purposes of the + operator.

    The + operator can be used for arithmetic addition and for string concatenation.

  5. What is a Java constant? How is it different from a Java variable?

    A Java constant is declared like a variable, except the final modifier is used. The value of a constant cannot be changed, unlike a variable whose value can be changed as needed.

  6. Explain the concept of operator precedence.

    Operator precedence determines how an expression gets evaluated. It is a set of rules that establishes which operators get evaluated first and how operators within the same precedence level evaluate.

  7. What is an infinite loop? Specifically what causes it?

    An infinite loop is a repetition statement that never terminates. Specifically, the body of the loop never causes the condition to become false.

  8. What is the difference between an object and a class?

    A class is a blueprint of an object. It defines the variables (instance variables, that is) and methods that will be a part of every object that is instantiated from it. But a class reserves no memory space for instance variables. Each object has its own data space, and therefore its own state.

  9. What are constructors used for? How are they defined?

    Constructors are special methods in an object that are used to initialize the object when it is instantiated. A constructor has the same name as its class, and it does not return a value.

  10. Explain the difference between an actual parameter and a formal parameter.

    An actual parameter is the value or variable sent to a method when it is invoked. A formal parameter is the corresponding variable in the definition of the method; it takes on the value of the actual parameter so that it can be used inside the method.

  11. How is information passed back from a method?

    An explicit return statement can be used to define the value that is returned from a method. The type of the return value must match the type specified in the method definition.

  12. How are overloaded methods distinguished from each other?

    Overloaded methods are distinguished by having their own signature, which includes the number, order, and type of the parameters. The return type is not part of the distinguishing signature.

  13. Describe the following:

  14. What is the difference between break and continue statements?
    When should they be used?

    A break statement will terminate the execution of the body of the switch or loop. A continue statement begins the next iteration of the loop in which it is contained.

  15. Explain the concept of array bounds checking. What happens when a Java array reference has an index value that is not valid?

    Whenever a reference is made to a particular array element, the index operator ensures that the value of the index is greater than or equal to zero and less than the size of the array. If it is not within the valid range, an ArrayIndexOutOfBounds exception is thrown.

  16. How is an array of objects created?

    An array of objects holds references to the object type specified as the array element. The array of object references and the element objects are instantiated separately.

  17. What are the advantages of using a Vector as opposed to an array? What are the disadvantages?

    A Vector object can dynamically grow and shrink as needed. A disadvantage of the Vector class is that it copies a significant amount of data in order to insert and delete elements, and this process is inefficient.

  18. Describe the Java coordinate system.

    The Java coordinate system is used to reference any drawing surface. The top-left corner represents coordinate (0, 0). The x axis increases to the right and the y axis increases down.

  19. Describe the relationship between a parent class and a child class.

    A child class is derived from a parent class using inheritance. The methods and variables of the parent class automatically become a part of the child class, subject to the rules of the visibility modifiers used to declare them.

  20. How does inheritance support software reuse?

    Because a new class can be derived from an existing one, the characteristics of the parent class can be reused without the error-prone process of copying and modifying code.

  21. Why would a child class override one or more of the methods of its parent class?

    A child class may prefer its own definition of a method in favor of the definition provided for it by its parent. In this case, the child overrides the parent's definition with its own.

  22. What is the super reference important to a child class?

    The super reference can be used to call the parent's constructor, which cannot be invoked directly by name.

  23. What is the defining characteristic of a class hierarchy?

    Any derivation in a class hierarchy should represent an is-a relationship. That is, the child is a more specific version of the parent. If this relationship does not hold, then inheritance is used improperly.

  24. What is polymorphism?

    Polymorphism is the ability for a reference of one class to refer to an object of another. In Java, a reference to a parent class can be used to refer to an object of the child class.

  25. How is overriding related to polymorphism?

    When a child class overrides the definition of a parent's method, two versions of that method exist. If a polymorphic reference is used to invoke the method, the specific version of the method that gets invoked is determined by the type of the object being referred to, not by the type of the reference variable.

  26. What is the difference between a class and an abstract class?

    A class can be instantiated; an abstract class cannot. Abstract classes often contain abstract methods that do not have implementations.

  27. What is the difference between a class and an interface?

    A class can be instantiated; an interface cannot. A class implements an interface by giving a definition for each method defined in the interface.

  28. What is the difference between an abstract class and an interface?

    An abstract class may have some methods defined. An interface contains no defined methods. Neither can be instantiated. A class can implement many interfaces, but can only be derived from a single abstract class.

  29. What is the purpose of an interface?

    An interface is used to define a common set of methods and constants for classes that are often contained in different class hierarchies.

  30. What is a package?

    A package is a language construct used for grouping classes with interdependent or similar characteristics. A package can be imported into a program as a unit.

  31. What is the primary difference between a window and a panel?

    A window is not attached to another container while a panel must be. The user can move a window from one point to another on the screen.

  32. What is an event?

    An event is a situation that arises in software, often in response to a user action such as a mouse button click. A program can be written to process and respond to particular events.

  33. What is a container?

    A container is a Java component that can contain other components. It is used to organize and display a graphical user interface.

  34. What is a layout manager?

    A layout manager controls the format and relative positions of the components in a GUI. Each Java container is governed by a layout manager.

  35. What is the component hierarchy?

    The order in which you put components in containers defines a component hierarchy. Careful planning of the component hierarchy can facilitate high-quality GUI development.

  36. Why would you use a Label instead of a TextField?

    A Label cannot be modified by the user by typing over it, whereas the contents of a TextField can be modified if it is made editable. If you don't want the user to change a value, you don't even want to hint that there may be a possibility. Using a TextField could give the user the wrong idea.

  37. What is the basic model for GUI programs?

    There are three elements: the GUI with its components presented in a particular manner, the listeners that are ready to respond to events, and the rest of the program code that handles the rest of the processing for your particular application.

  38. Why are there many different GUI components?

    There are many GUI components because there are many ways to interact with a system. Some components are particularly well suited to certain types of interactions. It is the challenge of the interface developer to design the user interface for maximum ease and functionality.

  39. Write a recursive definition of a valid Java identifier.

    Left as an exercise to the reader...

  40. What is recursion? What is recursive programming?

    Recursion is the act of defining something in terms of itself. Recursive programming allows a method to call itself, solving a smaller version of the problem each time, until the terminating condition is reached.

  41. Write a recursive definition of xy (x to the power of y), where x and y are integers and y > 0.

    See problem 39.

  42. What is infinite recursion?

    Infinite recursion has no terminating condition or one that is improperly specified. The recursive path is followed forever. In a recursive program, infinite recursion will often result in an error that indicates that available memory has been exhausted.

  43. When is a base case needed for recursion?

    A base case is always required to terminate recursion and begin the process of returning through the calling hierarchy. Without the base case, infinte recursion would result.

  44. Is recursion necessary?

    Recursion is not necessary. Every recursive algorithm can be written in an iterative manner. However, many problem solutions are much more elegant and straightforward when written recursively.

  45. When should recursion be avoided?

    Avoid recursion when the iterative solution is simpler and more easily understood. Recursion has the overhead of multiple method calls and is sometimes (altough very rarely) not entirely intuitive.


Tue Jan 26 1999
A201 Mini-Review Exam

Available time: 30 min.

Total points: 6 x 5 = 30

Work as fast as you can without being careless. Good luck and do well!

Please write your name or username here: _________________________________

Note: solutions appear in blue.

1. Finish the code below such that arrays a and b are merged into array c, by alternating elements from the two arrays.

For example if a is

1 4 16 5 ...
and b is
9 2 1 10 ...

then c would be

1 9 4 2 16 1 5 10 ...

Note that the sizes of a, b and c have been chosen conveniently.

public class Interleave {
  public static void main(String[] args) {
    int[] a = new int[100]; 
    int[] b = new int[100]; 
    int[] c = new int[200]; 
    for (int i = 0; i < a.length; i++) { 
      a[i] = (int)(Math.random() * 100 + 1);     
      b[i] = (int)(Math.random() * 50 + 1);      
    } 
    for (int i = 0; i < a.length; i++) {
      c[2*i] = a[i]; 
      c[2*i + 1] = b[i]; 
    } 
    // c should contain a and b interleaved here
  }    
}

2. Transform the following piece of code into one that does the same thing but makes use of a switch.

Assume that i is an int in the following set {1, 2, 3, 4, 5, 6}.

if ((i % 6 == 0) && (i % 2 == 0))
  System.out.println("Message One");
else
  System.out.println("Message Two"); 
Hint: there are at least two different ways to do it, but the easiest way is to remember that a switch can make the selection on a boolean expression. You could then use this information to translate the if in the most straightforward way.

switch ((i % 6 == 0) && (i % 2 == 0)) {
  case true: System.out.println("Message One");
             break; 
  default:   System.out.println("Message Two");
             break; 
}

3. Assume that you place this code in a file Exam.java and then you compile and run it.

What's the output that this program produces?

public class Exam {
  public static void main(String[] args) { 
    Example a = new Example("A"); 
    Example b = new Example("B"); 
    a.alpha(); // a.box is printed (A: 0) 
    b.alpha(); // b.box is printed (B: 0) 

    b.beta(3); // no output but b.box is set to 3
    a.beta(1); // no output, a.box is set to 1

    b.alpha(); // b.box is printed (B: 3) 
    a.alpha(); // a.box is printed (A: 1) 
  } 
}

class Example {                           Output is: 
  int box; 
  String name;                               A: 0 
  Example (String givenName) {               B: 0 
    box = 0;                                 B: 3 
    name = givenName;                        A: 1 
  } 
  void alpha() {
    System.out.println(name + ": " + box); 
  } 
  void beta(int value) {
    box += value; 
  } 
}
Use the space on the right to record your answer.

4. Transform the code below from its do-while implementation into an implementation that uses a for loop.

int i = -3, sum = 0, limit = (int)(Math.random() * 10 + 1);
do {
  sum += i;
  i += 1;  
} while (i < limit); 
System.out.println("Sum is: ", sum); 
Hint: what happens if (instead of initializing i to -3) we initialize it with a very large value, say 100. You will note that limit is an integer number between 1 (inclusive) and 11 (exclusive). What is the value printed for sum if i starts off being very big already?

int = -3, sum = 0, limit = (int)(Math.random() * 10 + 1); 
sum += i; 
for (i += 1; i < limit; i += 1) 
  sum += i;
5. Write the code that given an array of ints, a, as in the example below, produces the sSum, the sum of all products between each one of the elements of the array and the element that is its symmetrical with respect to its position in the array (that is, it is located as far from the end of the array as the element is located from the beginning of the array).

For example, if a is of length 5 and looks like this

4 5 1 8 2
then sSum will be
4*2 + 5*8 + 1*1 + 8*5 + 2*4 

Here's the code that needs to be finished as described:

public class ConvolutedSum {
  public static void main(String[] args) {
    int[] a = new int[100];
    for (int i = 0; i < a.length; i++) 
      a[i] = (int)(Math.random() * 30 + 1);
    int sSum = 0; 

    for (int i = 0; i < a.length; i++) 
      sSum += a[i] * a[a.length - i - 1]; 

    System.out.println("sSum = " + sSum); 
  }
}

Another Sample Exam: (Thursday March 4, 1999)

Write your name or username here: ___________________________________

Work as fast as you can without being careless. Good luck and do well!

Answers are in blue.


1. (5 points) Consider the following 'deja vu' class.

class A { 
  public      A()      { n = 0;                 } 
  public      A(int a) { n = a;                 } 
  public void f()      { n++;                   } 
  public void g()      { f(); n = 2 * n; f();   }
  public int  h()      { return n;              } 
  public void k()      { System.out.println(n); }   
  private int n; 
}
With the class above determine what the following program prints.
public static void main(String[] args) {
  A b = new A(3); 
  A c = b;
  b.g(); 
  c.f(); 
  A e = new A(2 * b.h() + c.h()); 
  e.k(); 
}
It prints 30. Try it, trace it in Cafe.

Note that references c and b will point to one and the same object.


2. (1 point) To restrict access to a static member to the class itself:
use the final keyword
use the private keyword
do not use a keyword at all for the member
a static member cannot be restricted this way

3. (1 point) Which word is not a Java keyword?
integer
double
float
default

4. (1 point) Which keyword is not used to control access to a class member?
public
protected
private
default

5. (2 points) What is wrong with this class definition?
class Avg { 
  public static void main(String[] args) {
    double a = 5.1; 
    double b = 20.32; 
    double c = 32.921; 
    System.out.println(findAvg(a, b, c));
  } 

  double findAvg(double a, double b, double c) { 
    return (a + b + c) / 3.0; 
  }
}
How can you fix it so that it works when you invoke main()?
turn findAvg into a public method
turn findAvg into a static method
turn findAvg into a private method
turn findAvg into a void method

6. (5 points) Implement a class Account. An account has Pass a value into a constructor to set an initial balance. If no value is passed the initial balance should be set to $0. Charge a $5 penalty if an attempt is made to withdraw more money than available in the account. Write your answer in the space below:
class Account {
  private double balance;
  public void add(int amount) {
    balance += amount; 
  } 
  public double withdraw(int amount) {
    if (amount > balance) { 
      balance -= 5; 
      return -5; 
    } else {
      balance -= amount; 
      return amount; 
    } 
  } 
  public double inquire() {
    return amount; 
  } 
}

7. (2 points) Suppose that class D inherits from B.

Strike out the assignments that won't compile.

B b = new B(); 
D d = new D();
b = d;
d = b;
d = new B();  
b = new D(); 

8. (3 points) Define a class Calculator whose instances will be able to compute (recursively) the nth element of the following recurrence:
J(1) = 1
J(n) = 2*J(n/2) - 1, if n > 1 is even, and
J(n) = 2*J((n-1)/2) + 1, if n > 1 is odd
The instance method should be called j.

Use % to determine if the number is even or odd.

class Calculator {
  int j(int n) {
    if (n == 1) return 1;
    else if (n % 2 == 0) return 2 * j(n / 2) - 1; 
    else return 2 * j((n - 1)/2) + 1; 
  } 
}

9. (6 points) You've implemented your own Vector class. Write the code for the four methods listed below and specify only the instance variables that your code works with.
boolean contains (Object obj)
Returns true if the object is among the values stored in the vector, or false otherwise.
Object elementAt (int index)
Returns the object at the specified index position.
boolean isEmpty ()
Returns true if the vector contains no objects, or false otherwise.
int size ()
Returns the number of objects currently stored in the vector.
class Vector {

  Object[] storage = new Object[0]; 

  int size() { return storage.length; } 

  boolean contains(Object obj) {
    for (int i = 0; i < storage.length; i++) 
      if (storage[i] == obj) 
        return true; 
    return false; 
  } 

  Object elementAt(int index) {
    if (index > 0 && index < this.size()) 
      return storage[index];
    else return null; 
  } 

  boolean isEmpty() {
    return (size() == 0); 
  } 

  // ... 

}

10. (3 points) Consider the following classes B and D:

class B {
  public B() { System.out.println("B()"); } 
  public B(int n) { System.out.println("B(" + n + ")"); } 
}

class D extends B {
  private B b; 
  public D() { System.out.println("D()"); } 
  public D(int n) {
    super(n); 
    b = new B(2*n); 
    System.out.println("D(" + ( -n ) + ")"); 
  } 
}
What does the following program print and why?
class Tester {
  public static void main(String[] args) {
    D d = new D(10); 
  }
}
As in homework 6:
B(10)
B(20)
D(-10)

11. (2 points) What is the result of attempting to compile and run the following code?

class Ex {
  public static void main(String[] args) {
    Fx f = new Fx(); 
  }
  Ex(int i) { 

  }
}

class Fx extends Ex { 

}
The code does not compile because the Ex class does not define a no-args constructor.
The code does not compile because the Fx class does not define a no-args constructor.
The code does not compile because there is no code in the Ex(int i) constructor.
The code compiles and runs succesfully.

12. (3 points) Consider the following code:

class Ex {
  public static void main(String[] args) {
    Fx f = new Fx(5); 
  }
  Ex() { 
    System.out.println("Ex, no-args"); 
  }
  Ex(int i) { 
    System.out.println("Ex, int"); 
  }
}

class Fx extends Ex { 
  Fx() { 
    super(); 
    System.out.println("Fx, no-args"); 
  }
  Fx(int i) { 
    super(i); 
    this(); 
    System.out.println("Fx, int"); 
  }
}
What is the result of attempting to compile and run it?
The messages "Ex, int", "Fx, no-args", and "Fx, int" appear in the standard output.
The messages "Ex, no-args", "Ex, int", "Fx, no-args", and "Fx, int" appear in the standard output.
The code does not compile because the Fx(int i) constructor is not defined legally.
The code does not compile because the Fx() constructor is not defined legally.

13. (3 points) Consider the following code:

class Ex {
  public static void main(String[] args) {
    Fx f = new Fx(5); 
  }
  Ex() { 
    System.out.println("Ex, no-args"); 
  }
  Ex(int i) { 
    System.out.println("Ex, int"); 
  }
}

class Fx extends Ex { 
  Fx() { 
    super(); 
    System.out.println("Fx, no-args"); 
  }
  Fx(int i) { 
    this(); 
    System.out.println("Fx, int"); 
  }
}
What is the result of attempting to compile and run it?
The messages "Ex, int", "Fx, no-args", and "Fx, int" appear in the standard output.
The messages "Ex, no-args", "Fx, no-args", and "Fx, int" appear in the standard output.
The code does not compile because the Fx(int i) constructor is not defined legally.
The code does not compile because the Fx() constructor is not defined legally.

14. (1 point) The legal expression for an if statement is

an integer
a boolean
either an integer or a boolean
none of the above

15. (1 point) You should place all of your low-level graphics rendering code in:
update()
paint()
repaint()
main()

16. (1 point) The AWT passes your paint() method an instance of class:
Frame
Container
Graphics
Component

17. (1 point) Which of these defines a valid main() method that can be used to start a program?
public static void main(String args) { }
public static void main(String[]) { }
public static void main(String[] args) { }
public static void main(args) { }

18. (1 point) What will appear in the standard output when you run the Tester class?
class Tester {
  int var;
  Tester (double var) { this.var = (int)var; }
  Tester (int var)    { this("hello"); }
  Tester (String s)   { this(); System.out.println(s); }
  Tester ()           { System.out.println("good-bye"); }
  public static void main(String[] args) {
    Tester t = new Tester(5);
  }
}
nothing
hello
5
hello followed by good-bye
good-bye followed by hello

19. (3 points) By default integer values are of type int, and floating point values are of type double. However, you can force an integer value to be a long by placing an L after it. You can also force a floating-point value to be a float by placing an F after it.

Knowing this, consider the following program:

class Example {
  public static void main(String[] args) { 
    Example e = new Example(); 
    e.test(5);
  } 

  int test(int i) { 
    System.out.println("int");
    return 1; 
  }

  void test(long i) {
    System.out.println("long"); 
  } 
}
What is the result of attempting to compile and run it?
The program does not compile because the compiler cannot distinguish between the two test() methods provided.
The program compiles and runs but nothing appears in the standard output.
The program compiles and runs and "int" appears in the standard output.
The program compiles and runs and "long" appears in the standard output.

20. (3 points) Remember that the signature of a method does not include the return type, only the name of the method, and the number and type of its arguments. Also, unlike an overloaded method, the return type for an overridden method must match the superclass's return type for that method.

Recalling this, consider the following program:

class Over { 
  public static void main (String[] args) {
    Under u = new Under();
    u.test();
  }

  int test() {
    System.out.println("Over");
    return 1;
  }
}

class Under extends Over {
  short test() { 
    super.test();
    System.out.println("Under");
    return 1;
  }
}
What is the result of attempting to compile and run it?
The code does not compile.
This code compiles and runs and displays Over followed by Under.
This code compiles and runs and displays Under followed by Over.

21. (2 points) Given these class definitions
class Superclass { }
class Subclass extends Superclass { }
and these objects
Superclass a = new Superclass();
Subclass b = new Subclass();
which of the following explains the result of the statement:
a = b
Illegal at compile time
Legal at compile time but possibly illegal at runtime
Definitely legal at runtime

22. (2 points) Given these class definitions
class Superclass { }
class Subclass1 extends Superclass { }
class Subclass2 extends Superclass { }
and these objects
Superclass a = new Superclass();
Subclass1 b = new Subclass1();
Subclass2 c = new Subclass2();
which of the following explains the result of the statement:
b = (Subclass1)c;
Illegal at compile time
Legal at compile time but possibly illegal at runtime
Definitely legal at runtime

23. (2 points) Given these class definitions
class Superclass { }
class Subclass extends Superclass { }
and these objects
Superclass a = new Superclass();
Subclass b = new Subclass();
which of the following explains the result of the statement:
b = a;
Illegal at compile time
Legal at compile time but possibly illegal at runtime
Definitely legal at runtime

24. (2 points) Given these class definitions
class Superclass { }
class Subclass extends Superclass { }
and these objects
Superclass a = new Superclass();
Subclass b = new Subclass();
which of the following explains the result of the statement:
b = (Subclass)a;
Illegal at compile time
Legal at compile time but possibly illegal at runtime
Definitely legal at runtime

25. (2 points) What will happen when you attempt to compile and run the following program
class Test {
  public static void main() {
    System.out.println("hello");
  }
}
by passing the Test class to the Java interpreter?
The program does not compile because main() is not defined correctly.
The program compiles but when you try to run the interpreter complains that it cannot find the main() method it needs to run
The program compiles but you cannot run it because the class is not declared as public
The program compiles and runs without an error but does not display anything in the standard output
The program compiles and displays hello in the standard output when you run it


26. (3 points) Tie together the Violin and Guitar classes presented below with a superclass, and make Violin unable to be subclassed. Use Java's abstract and final keywords where appropriate.

class Violin {
  int numStrings;
  void play() {
    System.out.println("mmm"); 
  } 
}

class Guitar {
  int numStrings;
  void play() {
    System.out.println("twang"); 
  } 
}

Remember the Shape example (textbook p. 243)?

It's a similar idea:

abstract class StringedInstrument {
  int numStrings;
  abstract void play(); 
}
 
final class Violin extends StringedInstrument {
  void play() { 
    System.out.println("mmm"); 
  } 
}
 
class Guitar extends StringedInstrument {
  void play() { 
    System.out.println("twang"); 
  } 
}  

27. (3 points) Change the following class definition for Employee
class Employee {
  int id; 
  Employee(int id) {
    this.id = id; 
  } 
}
as follows: Use the keywords private, public and static, as necessary.

This is like the Body problem in lecture notes 9.

Here's one possible answer to this exercise.

We change the defintion by replacing the original constructor with a new constructor that also manages the employees' id numbers with the help of a class variable id_counter.

public class Employee {
  private static int id_counter = 1; 
  private        int id; 
  public Employee() { 
    id = id_counter++; 
  } 
  public int getID() {
    return id; 
  } 
}

28. (2.5 points) Consider the following code:
class President {
  int born; 
  President(int born) {
    this.born = born; 
  }
}

class Washington extends President { 
  
} 

class Tester { 
  public static void main(String[] args) { 
    Washington w = new Washington(); 
    System.out.println(w.born);
  }
}
What will happen if you attempt to compile the three classes and run the Tester class?
The code will compile with no problems.
The println() method will display 0 to the standard output.
The compiler will complain that Washington doesn't have a default constructor.
The compiler will complain that President does not have a no-arg constructor.

29. (2.5 points) Consider the following code:
class First { 
  String test() {
    return "First"; 
  }
  public static void main(String[] args) {
    First f = new Second(); 
    System.out.println(f.test()); 
  }
}

class Second extends First {
  String test() { 
    return "Second"; 
  }  
}
What will happen when you attempt to compile and run it?
The First class will not compile because the object reference f in test() is used illegally.
The Second class will not compile because test() is not overridden legally.
The code will compile and run and "Second" will appear in the standard output.
The code will compile and run and "First" will appear in the standard output.
The code will compile and run but nothing will appear in the standard output.

30. (3 points) Here's a class named Bridge:
class Bridge {
  int length; 
  Bridge(int length) {
    this.length = length;
  } 
}


Modify this class definition to construct a new Bridge instance without explicitly supplying the bridge's length, like this:
Bridge b = new Bridge();
The default length for a bridge is, say, 10.

The no-args constructor is only supplied for you if you have not defined another constructor.

In this case, since there is already another constructor defined, you have to supply the no-arg constructor by writing it explicitly:

class Bridge {
  int length; 
  Bridge(int length) {
    this.length = length;
  } 
  Bridge() {
    this(10); 
  } 
}


31. (3 points) Given this class definition
class Railroad {
  String name; 
  Railroad() {
    System.out.println("Union Pacific"); 
  } 
  Railroad(String name) {
    this.name = name; 
  } 
}
How could you adjust the second constructor (the one that takes a String parameter) so that it also displays the message Union Pacific when it is invoked. (You can't use any print or println statement in the body of the second constructor but you can use/call the first constructor).

You can invoke the no-args constructor in the Railroad class using this().

Almost like we did in the previous problem:

class Railroad {
  String name; 
  Railroad() {
    System.out.println("Union Pacific"); 
  }
  Railroad(String name) {
    this();  
    this.name = name; 
  } 
}


Additional open-ended practice items for an older exam.

Solutions are in blue.

1. What's wrong with this class definition? Fix it so that it works when you invoke main(). (The desired behaviour is that the program print the average of the three numbers in a, b, and c,).

class Avg {
  public static void main(String[] args) {
    double a = 5.1; 
    double b = 20.32; 
    double c = 32.921; 
    System.out.println(findAvg(a, b, c)); 
  }

  double findAvg(double a, double b, double c) {
    return (a + b + c) / 3.0; 
  }
}

The static method main attempts to invoke the non-static method named findAvg(). Since there is no instance of Avg (the class we're writing) to use to invoke findAvg(), this is a compile time error. To fix this we could either make findAvg() a class method (that is, static) or create an instance of Avg and use that when invoking findAvg().

2. Tie together the Violin and Guitar classes presented below with a superclass, and make Violin unable to be subclassed. Use Java's abstract and final keywords where appropriate.

class Violin {
  int numStrings;
  void play() {
    System.out.println("mmm"); 
  } 
}

class Guitar {
  int numStrings;
  void play() {
    System.out.println("twang"); 
  } 
}
Remember the Shape example (textbook p. 243)?

It's a similar idea:

abstract class StringedInstrument {
  int numStrings;
  abstract void play(); 
}

final class Violin extends StringedInstrument {
  void play() { 
    System.out.println("mmm"); 
  } 
}

class Guitar extends StringedInstrument {
  void play() { 
    System.out.println("twang"); 
  } 
} 

3. Change the following class definition for Employee

class Employee {
  int id; 
  Employee(int id) {
    this.id = id; 
  } 
}
as follows: Use the keywords private, public and static, as necessary.

This is like the Body problem in lecture notes 9.

Here's one possible answer to this exercise.

We change the defintion by replacing the original constructor with a new constructor that also manages the employees' id numbers with the help of a class variable id_counter.

public class Employee {
  private static int id_counter = 1; 
  private        int id; 
  public Employee() { 
    id = id_counter++; 
  } 
  public int getID() {
    return id; 
  } 
}

4. Can an abstract method be final? Can an abstract method be static?

No, on both accounts. An abstract method must be overridden by a subclass, but final methods cannot be overridden. You cannot override a static method either (there's no this, or super since there is no current object responding to a static method) so a static method cannot be abstract.

5. Here's a class named Bridge:

class Bridge {
  int length; 
  Bridge(int length) {
    this.length = length;
  } 
}
Modify this class definition to construct a new Bridge instance without explicitly supplying the bridge's length, like this:
Bridge b = new Bridge();
The default length for a bridge is, say, 10.

The no-args constructor is only supplied for you if you have not defined another constructor.

In this case, since there is already another constructor defined, you have to supply the no-arg constructor by writing it explicitly:

class Bridge {
  int length; 
  Bridge(int length) {
    this.length = length;
  } 
  Bridge() {
    this(10); 
  } 
}

6. Given this class definition

class Railroad {
  String name; 
  Railroad() {
    System.out.println("Union Pacific"); 
  } 
  Railroad(String name) {
    this.name = name; 
  } 
}
How could you adjust the second constructor (the one that takes a String parameter) so that it also displays the message Union Pacific when it is invoked. (You can't use any print or println statement in the body of the second constructor but you can use/call the first constructor).

You can invoke the no-args constructor in the Railroad class using this().

Almost like we did in the previous problem:

class Railroad {
  String name; 
  Railroad() {
    System.out.println("Union Pacific"); 
  }
  Railroad(String name) {
    this();  
    this.name = name; 
  } 
}

7. Write a program that calculates the first ten squares (1, 4, 9, etc.) and places each entry in an array of integers. Then, create a new array and copy the values from the old array into the new array. At the end of your program, write out all entries in the second array to verify that your program worked. Both arrays should have length 10.

Here's the relevant part:

int[] a = new int[10]; 
int[] b = new int[10];
for (int i = 1; i <= 10; i++) a[i-1] = i * i;
for (int i = 1; i <= 10; i++) b[i-1] = a[i-1]; 
for (int i = 1; i <= 10; i++) 
  System.out.println(
    "b[" + (i - 1) + "] = " + i + " * " + i + " = " + b[i - 1]
  ); 
8. What's wrong with this class? Why won't it compile?
class Oops {
  public static void main(String[] args) {
    int i = 10;
    int j = 12; 
    
    if ((i < j) || (i = 3)) {
      System.out.println("hello"); 
    } 

    System.out.println(i); 
  } 
}
Note: there is exactly one error in the program.

The expression

i = 3;
in the if test is the problem.

Even though this expression will never be evaluated in this case (since i is less than j in our program) the assignment i = 3; does not yield a boolean.

In fact, its result is an integer (an int, the value of i after the assignment) in our case, 3.

Since an integer is not a legal argument for the || operator, this code will not compile.

9. The following program prints "i is 10". Why?

class Or {
  public static void main(String[] args) {
    int i = 10; 
    int j = 12; 

    if ((i < j) || (i = 3) > 5) {
      
    }

    System.out.println("i is " + i); 
  } 
}
This program writes
i is 10
Since the first expression in the if test:
i < j
is true, the second part of this test:
(i = 3) > 5
is not evaluated.

If it were, the value of i would be set to 3.

What if we initialize i to 20 instead?

Since the first expression in the if test:

i < j
is now false the output of the program will be:
i is 3

OK, I see there's some redundancy. But, nevermind.


Please do not attempt to start answering these questions on this page as there is no submit button at the bottom of this page and therefore no direct link to QuizSite.

Log into QuizSite directly for that. The questions below are simply listed here for your reference.


Question 1.
What is wrong with this class definition?

class Avg { 
  public static void main(String[] args) {
    double a = 5.1; 
    double b = 20.32; 
    double c = 32.921; 
    System.out.println(findAvg(a, b, c));
  } 

  double findAvg(double a, double b, double c) { 
    return (a + b + c) / 3.0; 
  }
}

How can you fix it so that it works when you invoke main()?


turn findavg into a public method
turn findavg into a static method
turn findavg into a private method
turn findavg into a void method


Question 2.
What happens if you try to compile code that looks like this:
class MyString extends String { 

}

The code compiles successfully.
The code does not compile because you have not defined a main() method.
The code does not compile because String is abstract.
The code does not compile because String is final


Question 3.
If you have the following class definitions
abstract class Shape { 
  abstract void draw(); 
}

class Square extends Shape {

}
What happens if you try to compile them?

Everything compiles succesfully
Shape compiles, but Square does not compile
Square compiles, but Shape does not compile
Neither Shape nor Square compiles


Question 4.
If you have the following class definitions
abstract class Shape { 

}

class Square extends Shape {

}
What happens if you try to compile them?

Everything compiles succesfully
Shape compiles, but Square does not compile
Square compiles, but Shape does not compile
Neither Shape nor Square compiles


Question 5.
To restrict access to a static member to the class itself:

use the final keyword
use the private keyword
do not use a keyword at all for the member
a static member cannot be restricted this way


Question 6.
Which word is not a Java keyword?

integer
double
float
default


Question 7.
Which keyword is not used to control access to a class member?

public
protected
private
default


Question 8.
What is the result of attempting to compile and run the following code?
class Ex {
  public static void main(String[] args) {
    Fx f = new Fx(); 
  }
  Ex(int i) { 

  }
}

class Fx extends Ex { 

}

The code does not compile because the Ex class does not define a no-args constructor.
The code does not compile because the Fx class does not define a no-args constructor.
The code does not compile because there is no code in the Ex(int i) constructor.
The code compiles and runs succesfully.


Question 9.
Consider the following code:
class Ex {
  public static void main(String[] args) {
    Fx f = new Fx(5); 
  }
  Ex() { 
    System.out.println("Ex, no-args"); 
  }
  Ex(int i) { 
    System.out.println("Ex, int"); 
  }
}

class Fx extends Ex { 
  Fx() { 
    super(); 
    System.out.println("Fx, no-args"); 
  }
  Fx(int i) { 
    super(i); 
    this(); 
    System.out.println("Fx, int"); 
  }
}
What is the result of attempting to compile and run it?

The messages "Ex, int", "Fx, no-args", and "Fx, int" appear in the standard output.
The messages "Ex, no-args", "Ex, int", "Fx, no-args", and "Fx, int" appear in the standard output.
The code does not compile because the Fx(int i) constructor is not defined legally.
The code does not compile because the Fx() constructor is not defined legally.


Question 10.
Consider the following code:
class Ex {
  public static void main(String[] args) {
    Fx f = new Fx(5); 
  }
  Ex() { 
    System.out.println("Ex, no-args"); 
  }
  Ex(int i) { 
    System.out.println("Ex, int"); 
  }
}

class Fx extends Ex { 
  Fx() { 
    super(); 
    System.out.println("Fx, no-args"); 
  }
  Fx(int i) { 
    this(); 
    System.out.println("Fx, int"); 
  }
}
What is the result of attempting to compile and run it?

The messages "Ex, int", "Fx, no-args", and "Fx, int" appear in the standard output.
The messages "Ex, no-args", "Fx, no-args", and "Fx, int" appear in the standard output.
The code does not compile because the Fx(int i) constructor is not defined legally.
The code does not compile because the Fx() constructor is not defined legally.


Question 11.
Consider the following code:
class One {
  static int instVar1 = 1;
  static int instVar2;
  public static void main(String[] args) {
    int localVar3 = 3;
    System.out.println(instVar1 + instVar2 + localVar3);
  }
}
What is the result of trying to compile and run it?

4
0
The code does not compile because localVar is not initialized correctly.
The code does not compile because instVar2 is not initialized at all.


Question 12.
How can you initialize an array of three boolean values to all true?

boolean[] b = new boolean[3];
boolean[] b = {true, true, true};
boolean[3] b = {true, true, true};
boolean[] b = new boolean[3]; b = {true, true, true};


Question 13.
The legal expression for an if statement is

an integer
a boolean
either an integer or a boolean
none of the above


Question 14.
Given the following code snippet:
char c = 'a';
switch(c) {
  case 'a': System.out.println("a"); break;
  default: System.out.println("default");
}
What will happen if you attempt to compile and run the code that includes this snippet?

The code will not compile because the switch statement does not have a legal expression.
The code will compile and run but nothing will be written to the standard output.
The code will compile and run and the letter "a" will be written to the standard output.
The code will compile and run and the word "default" will be written to the standard output.


Question 15.
Given the following code snippet:
int i = 3;
if (i < 5)
  if (i < 3)
    System.out.println("< 3");
else
  if (i > 2)
    System.out.println("> 2");
else
  System.out.println("other");
What will apear in the standard output?

"< 3"
"> 2"
"other"
nothing

Note: this is a tricky question, be careful with it.


Question 16.
By default integer values are of type int, and floating point values are of type double. However, you can force an integer value to be a long by placing an L after it. You can also force a floating-point value to be a float by placing an F after it.

Knowing this, consider the following program:

class Example {
  public static void main(String[] args) { 
    Example e = new Example(); 
    e.test(5);
  } 

  int test(int i) { 
    System.out.println("int");
    return 1; 
  }

  void test(long i) {
    System.out.println("long"); 
  } 
}
What is the result of attempting to compile and run it?

The program does not compile because the compiler cannot distinguish between the two test() methods provided.
The program compiles and runs but nothing appears in the standard output.
The program compiles and runs and "int" appears in the standard output.
The program compiles and runs and "long" appears in the standard output.


Question 17.
Remember that the signature of a method does not include the return type, only the name of the method, and the number and type of its arguments. Also, unlike an overloaded method, the return type for an overridden method must match the superclass's return type for that method.

Recalling this, consider the following program:

class Over { 
  public static void main (String[] args) {
    Under u = new Under();
    u.test();
  }

  int test() {
    System.out.println("Over");
    return 1;
  }
}

class Under extends Over {
  short test() { 
    super.test();
    System.out.println("Under");
    return 1;
  }
}
What is the result of attempting to compile and run it?

The code does not compile.
This code compiles and runs and displays Over followed by Under.
This code compiles and runs and displays Under followed by Over.


Question 18.
What Math methods, invoked like this:
Math.method(x);
would return the value -5 given the value of x to be -4.5?

round()
ceil()
floor()
all of the above
round() and floor() only


Question 19.
Given this line of code:
String s = "Penguin";
What will be assigned to c if you execute:
char c = s.charAt(6)

'n'
'i'
Nothing will be assigned because charAt() will respond with a StringIndexOutOfBoundException


Question 20.
You should place all of your low-level graphics rendering code in:

update()
paint()
repaint()
main()


Question 21.
The AWT passes your paint() method an instance of class:

Frame
Container
Graphics
Component


Question 22.
Which of these defines a valid main() method?

public static void main(String args) { }
public static void main(String[]) { }
public static void main(String[] args) { }
public static void main(args) { }


Question 23.
How can you access the word "Blue" from the following command-line invocation of main():
java Red Blue Green Blue Red

args[1]
args[3]
args[2]
args[4]
both args[1] and args[3]


Question 24.
What will appear in the standard output when you run the Tester class?
class Tester {
  int var;
  Tester (double var) { this.var = (int)var; }
  Tester (int var)    { this("hello"); }
  Tester (String s)   { this(); System.out.println(s); }
  Tester ()           { System.out.println("good-bye"); }
  public static void main(String[] args) {
    Tester t = new Tester(5);
  }
}

nothing
hello
5
hello followed by good-bye
good-bye followed by hello


Question 25.
What will happen when you compile and run this program:
class Array {
  public static void main(String[] args) {
    int length = 100;
    int[] d = new int[length];
    for (int index = 0; index < length; index++)
      System.out.println(d[index]);
  }
}

The code will not compile because the int[] array is not declared correctly.
The code will compile but will throw an IndexArrayOutOfBoundsException when it runs and nothing will appear in the standard output
The code will display the numbers 0 through 99 in the standard output, and then throw an IndexOutOfBoundsException
The code will compile but the println() method will throw a NoSuchMethodException
This code will work fine and display 100 zeroes in the standard output.


Question 26.
Given these class definitions
class Superclass { }
class Subclass extends Superclass { }
and these objects
Superclass a = new Superclass();
Subclass b = new Subclass();
which of the following explains the result of the statement:
a = b

Illegal at compile time
Legal at compile time but possibly illegal at runtime
Definitely legal at runtime


Question 27.
Given these class definitions
class Superclass { }
class Subclass1 extends Superclass { }
class Subclass2 extends Superclass { }
and these objects
Superclass a = new Superclass();
Subclass1 b = new Subclass1();
Subclass2 b = new Subclass2();
which of the following explains the result of the statement:
b = (Subclass1)c;

Illegal at compile time
Legal at compile time but possibly illegal at runtime
Definitely legal at runtime


Question 28.
Given these class definitions
class Superclass { }
class Subclass extends Superclass { }
and these objects
Superclass a = new Superclass();
Subclass b = new Subclass();
which of the following explains the result of the statement:
b = a;

Illegal at compile time
Legal at compile time but possibly illegal at runtime
Definitely legal at runtime


Question 29.
Given these class definitions
class Superclass { }
class Subclass extends Superclass { }
and these objects
Superclass a = new Superclass();
Subclass b = new Subclass();
which of the following explains the result of the statement:
b = (Subclass)a;

Illegal at compile time
Legal at compile time but possibly illegal at runtime
Definitely legal at runtime


Question 30.
What will happen when you attempt to compile and run the following program
class Test {
  public static void main() {
    System.out.println("hello");
  }
}
by passing the Test class to the Java interpreter?

The program does not compile because main() is not defined correctly.
The program compiles but when you try to run the interpreter complains that it cannot find the main() method it needs to run
The program compiles but you cannot run it because the class is not declared as public
The program compiles and runs without an error but does not display anything in the standard output
The program compiles and displays hello in the standard output when you run it


Question 31.
Consider the following program:
class Tester { 
  public static void main(String[] args) {
    Groucho g = new Groucho(); 
    g.speak("There's a tomato in every automaton."); 
  }
}

abstract class Person {
  abstract void speak(); 
} 

class Groucho extends Person {
  void speak(String s) {
    System.out.println(s); 
  } 
}
What will happen if you try to compile and execute the Tester class?

The program will compile and when run display "There's a tomato in every automaton" in the standard output.
The program will compile and when run will not display anything.
The code will not compile because speak() is abstract and there is no method matching this method's signature in the Groucho class.
The code will not compile because Tester does not inherit from Groucho.


Question 32.
Consider the following code:
class President {
  int born; 
  President(int born) {
    this.born = born; 
  }
}

class Washington extends President { 
  
} 

class Tester { 
  public static void main(String[] args) { 
    Washington w = new Washington(); 
    System.out.println(w.born);
  }
}
What will happen if you attempt to compile the three classes and run the Tester class?

The code will compile with no problems.
The println() method will display 0 to the standard output.
The compiler will complain that Washington doesn't have a default constructor.
The compiler will complain that President does not have a default constructor.


Question 33.
Consider the following code:
abstract class President {
  int born; 
  President(int born) {
    this.born = born; 
    System.out.println("born: " + born); 
  }
}

class Washington extends President { 
  Washington(int born) {
    super(born); 
  }   
} 

class Tester { 
  public static void main(String[] args) { 
    Washington w = new Washington(1732); 
  }
}
What will happen if you attempt to compile the three classes and run the Tester class?

The code will compile and "born: 1732" will appear in the standard output.
The code will compile but nothing will appear in the standard output.
The code will not compile because President is abstract.
The code will not compile because there is no default, no-args constructor for Washington.
The code will not compile because there is no default, no-args constructor for Washington.


Question 34.
Consider the following code:
class First { 
  String test() {
    return "First"; 
  }
  public static void main(String[] args) {
    First f = new Second(); 
    System.out.println(f.test()); 
  }
}

class Second extends First {
  String test() { 
    return "Second"; 
  }  
}
What will happen when you attempt to compile and run it?

The First class will not compile because the object reference f in test() is used illegally.
The Second class will not compile because test() is not overridden legally.
The code will compile and run and "Second" will appear in the standard output.
The code will compile and run and "First" will appear in the standard output.
The code will compile and run but nothing will appear in the standard output.


This is the end of the list of multiple choice items that you can use to prepare for the midterm exam. To practice with these items go into QuizSite. If you have any other questions please let us know.


Last updated: Jul 31, 2002 by Adrian German for A201