Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Study Guide

know the two reasons for having wrapper classes (be able to treat a primi- tive-type value as an object;
provide useful static fields and methods)

Understand casting be- tween numeric types

the fact that char is a numeric type

Autoboxing and unboxing


Name: NetID:

Prelim 1
CS 2110, 3 October 2019, 5:30 PM

1 2 3 4 5 6 7 Total
Question Name Short OO Recursion Loop Exception new-
answer invariants handling exp
Max 1 42 20 14 8 12 3 100
Score
Grader
The exam is closed book and closed notes. Do not begin until instructed.
You have 90 minutes. Good luck!
Write your name and Cornell NetID, legibly, at the top of the first page, and your Cornell
ID Number (7 digits) at the top of pages 2-7! There are 6 questions on 7 numbered pages,
front and back. Check that you have all the pages. When you hand in your exam, make sure
your pages are still stapled together. If not, please use our stapler to reattach all your pages!
We have scrap paper available. If you do a lot of crossing out and rewriting, you might want
to write code on scrap paper first and then copy it to the exam so that we can make sense of
what you handed in.
Write your answers in the space provided. Ambiguous answers will be considered incorrect.
You should be able to fit your answers easily into the space provided.
In some places, we have abbreviated or condensed code to reduce the number of pages that
must be printed for the exam. In others, code has been obfuscated to make the problem more
difficult. This does not mean that it’s good style.

Academic Integrity Statement: I pledge that I have neither given nor received any unau-
thorized aid on this exam. I will not talk about the exam with anyone in this course who has
not yet taken prelim 1.

(signature)

1. Name (1 point)

Write your name and NetID, legibly, at the top of page 1. Write your Student ID Number (the 7
digits on your student ID) at the top of pages 2-7 (so each page has identification).
Cornell ID Number (7 digits):

2. Short Answer (42 points)

(a) 6 points. Below are three expressions. To the right of each, write its value.
" "
1. 2 + 3 + "abc" + 1 + 4 Sabc 14

2. "abc".substring(0,1).indexOf('b')

3. new Integer(10000) == new Integer(10000)

(b) 8 points. Circle T or F in the table below.

(a) T F Because of automatic conversion, int x= 1.0; is valid Java.


(b) T F It’s possible to overload methods by swapping arguments of di↵erent types,
e.g. foo(int x, char y) and foo(char y, int x).
(c) T F a[a.length] refers to the last item in the array a.
(d) T F An object whose class implements Comparable can be stored in a variable of
type Comparable.
(e) T F The method int getLength(String x) { return x.length(); } can
throw a NullPointerException.
(f) T F A static method m can be called only from other static methods.
(g) T F Access modifier private denies access to unrelated classes but allows
superclasses to access the variable or method.
(h) T F A class cannot have more than one constructor.

(c) 3 points. Does the code to public abstract class Vehicle {


the right compile? If not, explain public abstract void makeNoise();
why. Give your answer directly below.
Specifications have been removed to public void numDoors() {
make it easier to see the code. System.out.println("I have 4 doors");
}
}

public class Porsche extends Vehicle {


@Override public void numDoors() {
System.out.println("I have 2 doors");
}
}

2 of 7
Cornell ID Number (7 digits):

(d) 3 points To the right, class S has one field public class S {
and a constructor. Consider this new-expression: private int a= 2;

new S() public S() {


System.out.println(a);
Below, write what evaluation of this new-expression int a= 5;
prints. a= this.a + 1;
System.out.println(a);
System.out.println(a + this.a);
}
}

(e) 8 points. Implement function isReverse according to its specification below. Do not use
recursion. Do not create any more Strings.

/** Return true if b is the reverse of c and false otherwise.


* Precondition: b and c are not null */
public static boolean isReverse(String b, String c) {

(f ) 6 points. Write five (5) distinct test cases based on the specification of isReverse given in
part (e) above (black box testing). We don’t need formal assertEquals calls. Just specify what a
and b are in each case and state what the function should do/return in each case (exception, true,
or false).

3 of 7
Cornell ID Number (7 digits):

(g) 8 points. Consider the declarations to the right. interface I1 { }


These statements are syntactically correct and compile:
interface I2 { }
B b= new B(); I1 i1= b;
Suppose these two statements are followed by the four class A implements I1 {}
statements below. For each, circle yes if it compiles and
no if it doesn’t, and also blot out completely the uncircled class B extends A
word (this may help in grading). implements I1, I2 {}
no yes String s= i1.toString();
no yes I2 k= b;
no yes I2 k2= i1;
no yes I2 k3= (I1) i1;

3. Object-Oriented Programming (20 points)


(a) 10 points. To the right is the beginning class Animal {
of class Animal, with two fields and method private String name;
addToDiet (which you don’t have to write). // list of things it eats, not null
Below, complete the constructor and method private ArrayList<String> diet;
equals.
Note: use new ArrayList<>(); to create a /** Add nF to this Animals diet. */
new ArrayList object. public void addToDiet(String nF){...}

/** Constructor: instance with name name and empty diet. */


public Animal(String name){

/** Return true if this and ob are objects of the same


* class and have the same name. */
public boolean equals(Object ob){

4 of 7
Cornell ID Number (7 digits):

(b) 10 points. To the right is the beginning class Rabbit extends Animal {
of class Rabbit, which extends class Animal of // how high it jumps
part (a). It has one field. Below complete the private int height;
constructor, method addToDiet, and method
equals, all of which go in class Rabbit.

/** Constructor: rabbit with name name, empty diet, jumps h */


public Rabbit(String name, int h) {

/** Add nF to the diet only if it is "carrot". */


@Override public void addToDiet(String nF) {

/** Return true if this and ob are objects of the same class
* and have the same name and height. */
@Override public boolean equals(Object ob){

}
}

4. Recursion (14 Points)

(a) 4 points Method F to the right calculates /** Return Fibonacci number n.
Fibonacci numbers. Below, write the calls made in * Precondition: 0 <= n. */
evaluating the call F(3) in the order they are called, public static int F(int n) {
starting with F(3) if (n == 0 || n == 1) return 1;
return F(n-1) + F(n-2);
}

5 of 7
Cornell ID Number (7 digits):

(b) 10 points. To the right, we show the lower left part of a


grid, but of course it extends further to the right and up to any (0, 2) (1, 2) (2, 2)
point (x, y) with 0  x and 0  y. An ant standing at any point
(x, y) can take a step Right to (x + 1, y) or Up to (x, y + 1). Suppose (0, 1) (2, 1)
the ant starts at (0, 0). How many di↵erent ways can the ant travel
to (x, y)? (0, 0) (1, 0) (2, 0)
Example, for (x, y) = (2, 1) there are three paths:
1: (Up, Right, Right), 2: (Right, Up, Right), 3: (Right, Right, Up).
Complete method numPaths, below. Use recursion and no loops.
/** Return the number of paths that an ant starting at (0, 0)
* can take to reach (x, y), taking steps to the Right or Up.
* Precondition: 0 <= x, 0 <= y.
* Example, if x = y = 0, return 1. If (x, y) = (2, 1), return 3. */
public static int numPaths(int x, int y) {

5. Loop Invariants (8 points)

To the right are the precondition and post- m n


condition of a loop (with initialization) that Pre: b ?
stores in s the product of b[m..n].
m n
(a) 2 points Below, write initialization Post: b s = product of these
that truthifies the loop invariant. You need
not declare variables.
m k n
Inv: b ? s = product of these

(b) 2 points Write the loop condition B so that the loop terminates properly when B is false.
Do not write a while loop; just write the loop condition.

(c) 4 points Write the repetend so that it makes progress toward termination and keeps the
invariant true. Do not write a while loop; just write the repetend.

6 of 7
Cornell ID Number (7 digits):

6. Exception handling (12 Points)

Consider method mystery. Function s.toString() returns the value of s. To the right of the
method are four calls on mystery. Under each write (1) the output printed by the call (on one line
is OK), including any exception that is not caught, and (2) the value returned by the call (if there
is one).

public static int mystery(String s) { (a) 3 points mystery("3");


try { Output: Return:
s= s.toString();
System.out.println("B");
int k= Integer.parseInt(s);
System.out.println("C"); (b) 3 points mystery(null);
int[] b= {50, 49, 49, 48}; Output: Return:
return b[k];
} catch (NumberFormatException e) {
System.out.println("D");
throw new RuntimeException(); (c) 3 points mystery("10");
} catch (NullPointerException e) { Output: Return:
System.out.println("E");
return -1;
} catch (Throwable e) {
System.out.println("F"); (d) 3 points mystery("mystery");
} Output: Return:
return -2;
}

7. New-expression (3 Points)

Write the 3-step algorithm for evaluating the new-expression new ABC(5) .

7 of 7
Name: NetID:

Prelim 1, Questions
CS 2110, 27 September 2018, 5:30 PM

1 2 3 4 5 6 Total
Question Name Short Exception Recursion OO Loop
answer handling invariants
Max 1 34 8 16 31 10 100
Score
Grader

The exam is closed book and closed notes. Do not begin until instructed. This handout
contains the questions; you will answer the questions on the accompanying answer handout.

You have 90 minutes. Good luck!

Write your name and Cornell NetID, legibly, at the top of every page of the answer
handout! There are 6 questions on 5 numbered pages, front and back. Check that you have
all the pages. When you hand in your exam, make sure your pages are still stapled together.
If not, please use our stapler to reattach all your pages!

You can use the back of the last page of this question handout as scrap paper. We have scrap
paper available. If you do a lot of crossing out and rewriting, you might want to write code
on scrap paper first and then copy it to the exam so that we can make sense of what you
handed in.

Ambiguous answers will be considered incorrect. Your answers should fit easily into the space
provided.

In some places, we have abbreviated or condensed code to reduce the number of pages that
must be printed for the exam. In others, code has been obfuscated to make the problem more
difficult. This does not mean that it’s good style.

1. Name (1 point)

Write your name and NetID, legibly, at the top of every page of the answer handoout.

1 of 5
Name: NetID:

2. Short Answer (34 points)

(a) 6 points. This question appears fully on the answer sheet.

(b) 5 points. This question appears fully on the answer sheet.

(c) 7 points. Use classes Animal and Cow below to answer the question on the answer sheet.

public abstract class Animal {


public Animal(){
System.out.println("I am an animal!");
}

public void makeSound() {


System.out.println("@#&*%!");
}
}

public class Cow extends Animal {


String farm;

public Cow(String farm) {


super();
this.farm= farm;
System.out.println("I am a cow from " + farm + "!");
}

public void makeSound() {


System.out.println("Moo!");
}
}

(d) 6 points. Implement function isEqual whose specification is given on the answer sheet. Here
are examples:

char[] array1 = {'g', 'r', 'i', 'e', 's'};


char[] array2 = {'r', 'g', 'i', 's', 'e'};
isEqual(array1, "gries") ==> true
isEqual(array1, "Gries") ==> false
isEqual(array2, "gries") ==> false

(e) 6 points. This question appears fully on the answer sheet.

(f ) 4 points. This question appears fully on the answer sheet.

2 of 5
Name: NetID:

3. Exception handling (8 Points)

On the answer handout, write the output to the console for the three statements foo(-1,-1);,
foo(0,0);, and foo(1,1);. Procedure foo is given below.

public static void foo(int a, int b) {


System.out.println("1 ");
int res= a / (b * 5);
try {
System.out.println("2");
if (b == 0 || b == -1) throw new IllegalArgumentException();
System.out.println("3");
a= b / (b-1);
System.out.println("4");
}

catch (ArithmeticException e) {
System.out.println("5");
if (b == 1) throw new RuntimeException();
System.out.println("6");
}

catch (Exception e) {
System.out.println("7");
}

System.out.println("8");
}

4. Recursion (16 Points)

(a) 8 points Recursive function hailstone is given below. Execute the following three calls,
and for each write down on the answer handout what is printed. But on each, stop after 4 println
statements have been executed.

public static void hailstone(int n) {


if (n > 0) {
System.out.println(n);
if (n != 1) {
if (n % 2 == 0) // n is even, halve it
hailstone(n / 2);
else // n is odd, times by 3 and add 1
hailstone(3*n + 1);
}
}
}

3 of 5
Name: NetID:

(b) 8 points The answer handout contains a recursive procedure comify; complete its method
body. You can use function p, given below. You must use recursion; do not use a loop!

/** = n but with leading 0's, if necessary, to have at least 3 chars.


Precondition: 0 <= n */
public static String p(int n) {
if (n < 10) return "00" + n;
if (n < 100) return "0" + n;
return "" + n;
}

5. Object-Oriented Programming (31 points)

Below is abstract class Chef, which is used throughout this problem:

public abstract class Chef {


private String name; // Name of chef

/** Constructor: Chef with name n. */


public Chef(String n) {name= n;}

/** Return a representation of this Chef —their name. */


public String toString() {return name;}

/** Return true if chef is busy and false otherwise */


public boolean isOccupied() {... Assume implemented ...}

public abstract boolean canMakeFood();

public abstract void makeFood();

/** Return a negative int, 0, or positive int depending on whether


* this chef’s name comes before, is the same as, or comes after
* ob’s name, in dictionary order. Throw a ClassCastException
* if ob is not a Chef. */
public int compareTo(Object ob) {
...
}

4 of 5
Name: NetID:

(a) 5 points Recall that interface Comparable declares abstract function compareTo(Object ob).
This function is declared in class Chef. On the answer sheet, complete its body and explain one
other necessary change to class Chef so that it implements interface Comparable.

Two hints are given on the answer handout.

(b) 12 pts Class BakingChef on the answer handout extends Chef. On the answer sheet,
(1) Complete the body of the constructor.
(2) Complete the return statement in function canMakeFood, assuming the two boolean variables
are assigned properly (you do not have to do this).
(3) Complete the body of procedure makeFood.

(c) 5 points On the answer sheet, complete the body of function toString, which is to be added
to class BakingChef. The result should contain the name of the chef and the size of the inventory.
You could just return those two values with a space between them.

(d) 9 points Class CakeChef (on the answer sheet) is a subclass of BakingChef. It has three
syntax errors, so it doesn’t compile. On the answer sheet, Identify the three syntax errors.

6. Loop Invariants (10 points)

Below are the precondition, postcondition, and invariant of a loop that swaps the negative values
in b[h..k] to the end of b[h..k]. Note that h is not necessarily 0, k is not necessarily b.length 1, and
both h and k should not be changed. You do not have to be concerned with declaring variables.
h k
Precondition: b ?
h t k
Postcondition: b >= 0 <0

h u t k
Invariant: b ? >= 0 <0

On the answer sheet, complete questions (a), (b), and (c).

5 of 5

You might also like