Name
__________________________ Date: ___/___/____
AP
CS Java - Mr. Merlis Block
___4 - ACE__
the MIDTERM
INSTRUCTIONS: These are AP-style
questions. Read each question
carefully. If you get stuck, KEEP
GOING. You can come back to it
later. There are 25 multiple-choice
questions (2 pts each) and 2 part 2s worth 10 points each.
1. Consider the following method:
public
static double solve(int n)
{
double answer = 1.0;
for(int k = 1; k < n; k++)
answer *= (double)k/(k + 1);
return answer;
}
What
value is returned by a call to method solve?
A.
0.0
B.
the
kth root of n
C.
1/n
D.
1/(n
-1)
E.
(1/2)n
2. Consider the following code segment:
int x = 2;
int y = 4;
x += y;
y += x ;
System.out.println( "x = " + x +
", y = " + y);
What
output is produced by executing this code?
A.
x
= 2, y = 4
B.
x
= 6, y = 6
C.
x
= 6, y = 10
D.
x
= 6, y = 12
E.
x
= 24, y =42
3. Consider the following method:
public
boolean evaluate(boolean p, boolean q)
{
return ((p && q) || !(p || q));
}
What
is returned by evaluate?
A.
evaluate
always returns false
B.
evaluate
returns true when p and q are both true or both false.
C.
evaluate
returns true only when p and q are both true.
D.
evaluate
returns true only when p and q are both false.
E.
evaluate
returns true when either p or q is true and the other is false.
4. Consider the following method:
public
static void fun(String msg)
{
System.out.print(msg);
if(msg.length() < 2)
return;
else
fun(msg.substring(0,
msg.length()/2);
System.out.print(msg);
}
What
would be printed by the call fun("tickleme")?
A.
ticklemeticklemeticklemeticklemeticklemetickleme
B.
ticklemetickti
C.
titicktickleme
D.
ticklemeticktittiticktickleme
E.
ticklemeticktiiititicktickle
5. Which of the following cannot
always be checked by a compiler?
A. The version of a method being invoked.
B. The spelling of keywords.
C. Possible missing punctuation within code.
D. Return values matching method return types.
E. Invocation of a private method from outside
the class.
Questions 6 and 7 refer to
the following method.
private
int n;
public
static boolean check(int[] arr)
{
boolean theCheck = true;
for(int k = 0; k< n-1; k++)
if(arr[k] >= arr[k+1])
theCheck = !theCheck;
return theCheck;
}
6. Which of the following is the best
precondition assuming that we do not wish to generate an exception?
A.
0
<= n < arr.length
B.
n
< arr.length
C.
n
<= arr.length
D.
n
>= 0
E.
No
precondition is necessary.
7. Which of the following is the best
postcondition for method check??
A.
returns
true if there are no duplicates in the first n elements of arr; otherwise,
returns false
B.
returns
true if the (n-1)th element of arr is less than the nth element; otherwise
returns false
C.
returns
true if the first n elements of arr are all the same value; otherwise, returns
false
D.
returns
true if the first n elements of arr are in strictly increasing order;
otherwise, returns false
E.
returns
true if there are an even number of times when an element is at least as large
as its successor among the first n elements of arr; otherwise returns false
8. Consider the following recursive method:
public
static int seq(int x)
{
if(x <= 1 || x == 3)
{
return x;
else
return (seq(x - 1) + seq(x - 2));
}
What
value will be printed by the call seq(5)?
A.
1
B.
3
C.
4
D.
7
E.
11
9. A programmer has mistaken placed a semicolon
at the end of the while statement in the following code fragment. What will be the result of executing the
code?
while(
j < n); // Mistaken semicolon
{
System.out.println(“in loop”);
j++;
}
A.
The
code will behave in the same manner as if the semicolon were not included.
B.
The
machine will get caught in an infinite loop, appearing to do nothing.
C.
The
machine will get caught in an infinite loop, repeatedly printing the message
“in loop”.
D.
Depending
upon the code that precedes this loop within the program, either an infinite
loop will result or the “in loop” message will be printed a single time.
E.
The
code will not compile because of the presence of the semicolon.
10. Consider the following incomplete method that
is intended to return the position in array nums where target is found or -1 if
target is not in the array.
//Precondition:
nums is arranged in increasing order
public
static int binsrch(Comparable[] nums, Comparable target)
{
int low = 0;
int high = nums.length – 1;
int mid;
while( <expression1> )
{
mid = (low + high)/2;
if(nums[mid].compareTo(target) ==
0)
return mid;
else
if(nums[mid].compareTo(target)<0)
<expression2>;
else
<expression3>;
}
return -1;
}
Which
of the following could be used to replace <expression1>,
<expression2>, and <expression3> so that the code works as
intended?
<expression1> <expression2> <expression3>
A. low < high low = mid + 1 high =
mid – 1
B. low <= high low = mid – 1 high =
mid + 1
C. low <= high low = mid + 1 high =
mid - 1
D. low >= high low = mid + 1 high =
mid - 1
E. low > high low = mid + 1 high =
mid – 1
11. Assume that the ArrayList names holds the
following values:
Alyce,
Barbara, Chris, Denny, Ed, Fran, GEne, Henry, Ian, Julie
What values
does this ArrayList hold after executing the following code?
for(int i =
1; i <= 4; i++)
names.remove(i);
A.
Alyce,
Barbara, Chris, Denny, Ed, Fran
B.
Alyce,
Fran, Gene, Henry, Ian, Julie
C.
Alyce,
Chris, Ed, Gene, Ian, Julie
D.
Barbara,
Denny, Fran, Henry, Ian, Julie
E.
Ed,
Fran, Gene, Henry, Ian, Julie
12. Consider the following method, which is
intended to count the number of times a value is doubled before it is at least
as large as a target value:
// precondition: d > 0
public void doubleUp(double d)
{
static final double TARGET = 100.0;
int count;
while(d < target)
{
count = 0;
d *= 2;
count++;
}
System.out.println(count);
}
Of
the following, which best describes the error in doubleUp?
A.
The
static modifier cannot be used with a constant.
B.
A
variable is used without being initialized.
C.
A
double cannot be multiplied by an int.
D.
The
counter is incremented in the wrong place.
E.
A
variable is initialized in the wrong place.
13. In the statement
if(
(x != null) && (x.performanceRating() > THRESHOLD))
{
<do something> }
what prevents a NullPointerException from being
thrown?
A.
Method
overloading
B.
Polymorphism
C.
Inheritance
D.
Short-circuiting
E.
Dynamic
allocation
14. Which expression below is equivalent to the
following?
((x != null) && (x.info.compareTo(z.info) > 0))
A.
((x.equals(null)) || (x.info.compareTo(z.info)
> 0))
B.
((x.equals(null)) &&
(x.info.compareTo(z.info) == 0)
C.
!((x != null) ||
(x.info.compareTo(z.info) >= 0))
D.
!((x == null) &&
(x.info.compareTo(z.info) < 0))
E.
!((x == null) || (x.info.compareTo(z.info)
<= 0))
For questions 15 and 16,
consider the following class:
public class Doohickey
{
private
String myID;
private
double myMass;
public
Doohickey()
/*
implementation not shown */
public
String getID() { return myID; }
public
double getMass() { return myMass; }
public String
toString() { /* missing code */ }
}
15. Which of the following would not be
acceptable as the body for the toString method?
A.
return
myID + “ ” + myMass;
B.
return
(String) myID + “ ” + myMass;
C.
return
getID()+ “ ” + myMass;
D.
return
getID()+ “ ” + getMass();
E.
return
getID().getMass();
16. Suppose that glop is an ArrayList of
Doohickeys. Consider the following code
fragment that is meant to print ou the ID numbers of all Doohickeys whose mass
> 0.
for(int num = 0; num < glop.size(); num++)
{
if(/* missing
code */)
{
System.out.println(glop[num].getID());
}
}
Which of the following expressions will complete the
code fragment correctly?
A. (glop)
Doohickey.get(num).getMass() > 0
B.
((Doohickey) getNum(glop)).getMass() > 0
C.
glop.get((Doohickey)num).getMass() > 0
D.
((Doohickey) glop.get(num)).getMass() > 0
E.
glop.get(glop.getMass(num)) > 0
Questions 17 and 18 refer to
the following method that is intended to remove all duplicates of the first
value in an ArrayList. For example, if
the ArrayList contains 2 3 2 4 4 2 2 2 3, removeDupsOfFirst should return 2 3 4
4 3. The method does not always work as
intended.
public static void removeDupsOfFirst(ArrayList a)
{
int k = 1;
while(k <
a.size())
{
if(((Integer)a.get(k)).compareTo(((Integer)a.get(0)))
== 0)
a.remove(k);
k++;
}
}
17. Which of the following sets of test data
would cause removeDupsOfFirst to fail?
A.
2
1 0
B.
2
2 2
C.
2
3 4 5 6
D.
2
3 4 5 2
E.
2
2 3 2 4 2 5
18. Which of the following best describes how to
correct removeDupsOfFirst so that it always works as intended?
A.
Initialize
a variable to count the number of duplicates to be removed.
B.
Initialize
k to 0.
C.
Change
the while loop to a for loop
D.
Insert
else before k++
E.
Make
the return type ArrayList and return a
19. What is the output from the following code?
int x = 5, y
= 2;
System.out.println(x/y – (double)(x/y));
A.
0
B.
0.5
C.
-0.5
D.
-2.5
E.
None of the above
20. What are the values of u and v after the
following code is executed ?
int u = 3, v
= 5;
u += v;
v += u;
u -= v;
v -= u;
A.
0,
0
B.
3,
5
C.
5,
3
D.
-5,
-3
E.
-5,
18
21. Which of the following statements DOES NOT
display 9.95?
A.
System.out.println(9
+ 0.95);
B.
System.out.println(995/100.0);
C.
System.out.println(9.
+ 95/100);
D.
System.out.println(9
+ 95.0/100);
E.
System.out.println(9
+ “.” + 95);
22. An integer array a has 19 elements. What is the value of the middle element after
the following code is executed?
int i, j, n
= 19;
for(i = 0; i
< n; i++)
a[i] = i
+ 1;
for(i = 0, j
= n-1; i <= j; i++, j--)
a[(i+j)/2]
-= (a[i] + a[j]) / 2;
A.
0
B.
10
C.
-41
D.
-62
E.
-71
23. Consider the following method:
public void
mysteryMix(Integer a, Integer b) {
a = new
Integer(2 * a.intValue());
b = a; }
What is the
output of the following code?
Integer
a = new Integer(1);
Integer
b = new Integer(2);
mysteryMix(a,
a);
mysteryMix(a,
b);
System.out.println(a
+ “ “ + b);
A.
1
1
B.
1
2
C.
2
2
D.
1
4
E.
4
4
24. The Binary Search algorithm normally finds a
value in an array sorted in ascending order.
Suppose that by mistake the algorithm is used on an unsorted array with
the following seven elements:
1
3 2 5 13 8 21
Which of the following target values will NOT be
found?
A.
1
B.
3
C.
5
D.
13
E.
21
25. An array has 4095 = 212 – 1
elements, arranged in ascending order.
Binary Search is used to find the position of a target value. This Binary Search is implemented
iteratively, in such a way that in each iteration the target is compared to one
of the elements of the array. Suppose we
know that the larget is somewhere in the array.
What number of interations guarantees that a target value is found?
A.
10
B.
11
C.
12
D.
2047
E.
4095
(Hint: Come up with smaller examples for which we
easily know the answer!)
PART
2: The fun stuff! Please write all classes using correct java
syntax. NO PSEUDOCODE.
Question
1
Consider the following declarations for maintaining
an inventory list of toys at a toy store.
Information about each toy includes the name, price, appropriate age
range (in years), and appropriate gender (“girl”, “boy”, “either”). The inventory is ordered by age range. For example, a very abbreviated inventory
might be the following:
Name |
Price |
Lower Bound |
Upper Bound |
Gender |
Canopy tricycle |
$29.99 |
3 |
5 |
either |
Beach Ball |
$1.29 |
3 |
80 |
either |
Fashion Doll |
$11.99 |
6 |
14 |
girl |
public class Toy
{
private
String name;
private
double price;
private int
lBound;
private int
UBound;
private
String gender;
public
String getName()
public
double getPrice()
public
String getGender()
// returns
true if a toy is appropriate for age; otherwise false
public
boolean isAgeAppropriate(int age)
{ /* missing
code */ }
// other
methods not shown
}
A.
Write the Toy method isAgeAppropriate that returns true if a toy
is recommended for a child of a particular age, otherwise return false.
//
postcondition: returns true if a toy is appropriate for age
//
postcondition: otherwise returns false
public
boolean isAgeAppropriate(int age)
B.
Suppose a high school service club is looking for a list of toys
that are age and gender appropriate for a group of needy children. The club asks the toy store manager for
suggestions.
public
class ToyInventory
{
private
ArrayList toyList;
// Builds a list
containing each toy in the inventory that is appropriate for anAge and aGender
public
ArrayList toySelection(int anAge, String aGender)
{
/* missing code */ }
//
other data and methods not shown
}
Write the ToyInventory method
toySelection that builds a list containing each toy in its inventory that is
age and gender appropriate for a particular child.
// Builds a list containing
each toy in the inventory that is appropriate for anAge and aGender
public ArrayList
toySelection(int anAge, String aGender)
PART 2 – Question 2
Rearview Motors, Inc.,
manufactures three different models of car (couple, sedan, or wagon). Each car has one of five exterior colors
(black, white, red, blue, or silver) and one of three interior colors (tan,
gray, or burgundy). In addition there is
a list of options that buyers may purchase.
Some of the options are heated seats, surround-sound system, and steel
wheels, but there are many others. Cars
are assembled at various plants throughout the country. Each plant is responsible for keeping track
of the cars it has produced each month.
Executives at corporate headquarters are likely to ask for such
information as the total number of cars produced, a description of the car most
recently produced, and the number of cars with any given feature (e.g., “cars
with steel wheels” or “cars with heated seats.”) The company keeps track of all this via an
AssemblyPlant class, part of which is shown below:
public class AssemblyPlant
{
private String plantName;
private ArrayList carsProduced; //
holds one Car object for each car produced
public int totalCarsProduced() {...}
public String mostRecentCarProduced() {...}
public int carsProducedWith(String feature) {...}
// other methods and/or constructors not shown
}
A.
Write a class definition for the Car class that will keep track of the information and provide the
services for the class, putting only “{...}” in for the bodies of the
constructor(s) and method(s). In writing
this definition you must:
-
Choose
appropriate names for all the identifiers.
-
Provide
(at least) the functionality specified above.
-
Make
data representation decisions consistent with the specfications above.
-
Make
design decisions that are consistent with the principles of object-oriented
design.
Comments are
not required, but may be included to explain your intent.
Do
not write the implementations of the constructors or the methods of the Car
class.
B.
Write the method carsProducedWith from the AssemblyPlant class. The
header is given below.
//
precondition: feature is a valid feature
//
postcondition: returns the number of cars with the specified feature that have
been produced at this plant
public int
carsProducedWith(String feature)
C.
Write the implementation(s) for any methods in the Car class
that were used in your answer to Part B.