Which part of the following code will produce a compiler error if we know class cat extends a class called animal and both of the classes have a method called makeNoise and class cat has a method called showFood.
1 animal mydog = new animal();
2 mydog.makeNoise();
3 animal mycat = new cat();
4 mycat.makeNoise();
5 mycat.showFood();
A
line 3, new cat should be changed to new animal.
B
line 3, animal should be changed to cat.
C
line 4, makeNoise has not been recognized by mycat
In a program 5 objects are created initially and inserted into a vector. These objects increase to 64 during the execution of the program. Each time 8 objects is added to the vector except the last time in which 3 objects is added. Which of the following definition results in better performance in terms of execution time and allocated space at the end?
A
Vector<Object> objectVect = new Vector<Object>(5,8);
*B*
Vector<Object> objectVect = new Vector<Object>(8);
C
Vector<Object> objectVect = new Vector<Object>(8,5);
D
Vector<Object> objectVect = new Vector<Object>(5);
Which option is NOT a correct solution to handle an exception if we know that NumberException is a user defined exception?
A
public static int testNumber(int x) throws NumberException{
if (x >= 12)
throw new NumberException("This is my created exception message");
return x;
}
B
public static int testNumber(int x) throws NumberException{
try{
if (x >= 12)
throw new NumberException("This is my created exception message");
}
finally{}
return x;
}
*C*
public static int testNumber(int x) throws NumberException{
try{
if (x >= 12) new NumberException();
}
catch (NumberException e){
e.printStackTrace();
}
finally{}
return x;
}
D
public static int testNumber(int x) {
try{
if (x >= 12) throw new NumberException();
}
catch (NumberException e){
e.printStackTrace();
}
finally{}
return x;
}
Field
Value
ID
627690 [created: 2013-05-28 11:10:12, author: kate (xkate), avg difficulty: 0.0000]
Question
2. Consider the following class definition:
public class SillyTestClass {
public SillyTestClass(int x, int y) {
System.out.println(y);
}
public SillyTestClass(String string1, String string2) {
System.out.println(string2);
}
public static void main (String [ ] args) {
SillyTestClass app = new SillyTestClass(20, “Try this!”);
}
}
Which of the following is the most accurate statement about this code?
A
The class definition won't compile, because it has two constructors.
B
The class definition won't compile, because two constructors have the same number of parameters.
*C*
The class definition won't compile, because the actual and formal parameter types don't match.
D
It will compile, and the output when the main method is executed will be: 20
E
It will compile, and the output when the main method is executed will be: Try this!
Explanation
Answer A is wrong because Java programs can have more than one constructor. Answer B is wrong because a variation between the type of the parameters is also sufficient. Answers D and E are wrong because the program won't compile or execute. Answer C identifies the problem.
627757 [created: 2013-06-07 09:02:27, author: kate (xkate), avg difficulty: 0.0000]
Question
The code fragment given above was intended to read values until a negative value was read and then to print the product of the positive values read. Unfortunately, it does not work.
1. Scanner kbd = new Scanner(System.in);
2. int x, product;
3. product = 0;
4. x = kbd.nextInt();
5. while (x >= 0) {
6. if (x > 0) {
7. product *= x;
8. }
9. x = kbd.nextInt();
10. }
11. System.out.println(product);
Which of the following best describes the error that prevents the code from computing the correct answer?
A
Variable x is not initialized correctly.
*B*
Variable product is not initialized correctly.
C
The loop is executed one too many times.
D
The loop is executed one two few times.
E
None of the above.
Explanation
Because the variable product is initialized to 0 instead of 1, the answer will always be 0.
Using the information in the UML diagram above, suppose some method of Truck has the line super.move(). Which of these is true?
A
The move method defined in Truck is executed when that line is executed.
B
The move method defined in Vehicle is executed when that line is executed.
C
It depends on whether move() is defined in Vehicle’s superclass
*D*
The code will not compile, so I cannot run it.
E
None of the above
Explanation
super.move() refers to the move method defined in Vehicle, and since Vehicle's move method is abstract this will not compile, even if an ancestor of Vehicle defines a move() method that Vehicle would presumably inherit.
Using the information in the UML diagram above, suppose we execute the following Java statements:
Vehicle vehicle = new OilTanker(2500);
vehicle.move();
which definition of move will be executed?
A
The one defined in Truck
B
The one defined in Vehicle
*C*
The one defined in OilTanker
D
The one defined in PeopleHauler
E
The code will not work
Explanation
Since the actual type of vehicle is OilTanker, and since move is an appropriate method for instances of Vehicle, which is vehicle's declared type, the move method invocation will work, and will be the one defined in OilTanker
Field
Value
ID
629601 [created: 2013-06-10 09:07:59, author: kate (xkate), avg difficulty: 0.0000]
Question
Consider the following code:
public int examMethod(int n) {
if (n == 1) return 1;
else if (n > 1) return (n + this.examMethod(n-1));
}
What is the purpose of examMethod?
A
to compute fibonacci(n)
B
to compute factorial(n)
*C*
to compute the sum of the positive integers from 1 to n
D
none of the above
Explanation
The method returns 1 if n is 1, 2+1 if n is 2, 3+2+1 if n is 3, etc. In other words, it computes the sum of the integers from 1 to n (answer C).
629606 [created: 2013-06-10 09:23:34, author: kate (xkate), avg difficulty: 0.0000]
Question
Consider the following method:
public int examMethod(int n) {
if (n == 1) return 1;
else return (n + this.examMethod(n-1));
}
Which of the following inputs will cause a non-terminating recursion?
*A*
0
B
1
C
20
D
30,000
E
None of the above
Explanation
The base case for this recursion is n == 1. If n is 1, the recursion is done. If n is 20, then the value of n will be reduced by 1 with each recursive call (examMethod(19), examMethod(18), etc.), the value of n will finally reach 1, and the recursion will end. Similarly if n is 30,000.
But if n is 0 to begin with, then the next recursive call will be to examMethod(-1), then examMethod(-2), etc. The value of n will never reach the base case, and the method will (in theory) never terminate.
Using the information in the UML diagram above, suppose we execute the following Java statements:
PeopleHauler pM = new Car();
pM.move();
which definition of move will be executed?
*A*
The one defined in Car
B
The one defined in PeopleHauler
C
The one defined in Vehicle
D
The one defined in Truck
E
None of the above
Explanation
The actual type of pM is Car. Since the declared type of pM is PeopleMover, an interface, move is an appropriate method call for pM since it is in the interface. The definition used will be the one in the actual type, Car.
Field
Value
ID
629919 [created: 2013-06-11 04:19:32, author: kate (xkate), avg difficulty: 0.0000]
Question
Consider the following Java interface definition:
public interface Mover { public int getX(); public int getY(); public void setLocation(int x, int y);
}
Which of the following is a correct implementation of the Mover interface?
A
public class CartoonCharacter implements Mover{
private int x, y;
public int getX;
public int getY;
public void setLocation;
}
B
public class CartoonCharacter implements Mover{
private int x, y;
public int getX();
public int getY();
public void setLocation(int x, int y);
}
C
public class CartoonCharacter implements Mover{
private int x, y;
public int getX() {
// code for method body
}
public int getY() {
// code for method body
}
}
*D*
public class CartoonCharacter implements Mover{
private int x, y;
public int getX() {
// code for method body
}
public int getY() {
// code for method body
}
public void setLocation(int x, int y){
// code for method body
}
}
E
public class CartoonCharacter implements Mover{
private int x, y;
public int getX() {
// code for method body
}
public int getY() {
// code for method body
}
public int setLocation(int x, int y){
// code for method body
}
}
Explanation
Choice A is wrong because it doesn't include parameter lists or implementations of any of the methods required by the interface.
Choice B is wrong because it doesn't include implementations of the methods on the list.
Choice C is wrong because it implements some but not all of the interface methods.
Choice E is wrong because the method signatures do not match those in the interface.
Choice D is the correct answer, because it's the only one where the required methods are all implemented, and their signatures match
NOTE: There is no appropriate topic for this question in the list. Suggestion: TopicSimon-interfaces-Java
626600 [created: 2013-06-06 13:39:48, author: kate (xkate), avg difficulty: 0.0000]
Question
1. What is the value of the following Java arithmetic expression?
4 * 3 + 6 / 4
A
4
B
4.5
*C*
13
D
9
E
13.5
Explanation
This question addresses two points: first, operator precedence (multiplication and division are both done before addition) and second, integer division. Answer A is wrong about operator precedence: the answer you get if you apply the operators in order from left to right. Answer B makes the same mistake and is also wrong about integer division. Answer D is the answer you get if you assume that addition has a higher precedence than the other two operations. Answer E gets the operator precedence right, but is wrong about integer division. Answer C is the only one that has both right.
What is the maximum result of computing X % 7, where all we know about X is that it is a positive integer?
A
0
B
1
*C*
6
D
7
E
There is not enough information in the question description to answer.
Explanation
% is the modular division operation, which perform division and returns the remainder. For example, 7 % 7 is 0, since 7 goes into 7 once with a remainder of 0. 8 % 7 is 1, since 7 goes into 8 with a remainder of 1. Similarly, 13 % 7 is 6, while 14 % 7 is again 0, since 7 goes into 14 twice with no remainder. If you mod a positive integer by N, the maximum result is N-1.
if x >= 0:
print (1)
elif x < 20:
print(2)
else:
print(3)
print(4)
For what values of x will 2 be among the values printed?
*A*
x < 0
B
x >= 0
C
x < 20
D
All values of x
E
None of the above
Explanation
Although the condition of the elif is x<20, all values between 0 and 20 are subsumed (i.e. covered by) the first condition, x>=0. So only values of x strictly less than 0 will result in 2 being printed.
After the assignment signal = ’abracadabra’, what is returned by signal[:5]?
A
’abraca’
*B*
’abrac’
C
’c’
D
An error
E
None of the above
Explanation
This is a slice operation. Slices in Python work with both lists and with Strings, and go up to but not including the limit. Since the limit is 5, we get the first 5 characters (indexed 0 through 4). Hence abrac
After the assignment signal = ’abracadabra’, what is returned by signal[-1:]?
*A*
'a'
B
'abracadabra'
C
''
D
an error
E
none of the above
Explanation
Python actually allows negative indexes, which start counting from the back of a list or String. However, the slice operation by default still only uses increasing indexes. So, slicing [-1:] means to slice from the last character through the rest of the String (slice operations that leave out the upper boundary implicitly mean "slice to the end").
This is a lexicographic (i.e. alphabetic) comparison. The first 2 characters of both strings are the same (i.e. 'A '), but for the third character, 'A' comes before 'L' so we return True.
Many English words have separate singular and plural forms, e.g., "dog" and "dogs." We are trying to write a method that properly pluralizes a word (though naively, by only adding an "s" at the end) if the count we have of that word is not 1. If the count is 1, we leave the word as is. Which of the following proposed solutions does not meet this specification?
if x >= 0:
print (1)
elif x < 20:
print(2)
else:
print(3)
print(4)
For what integer values of x will 3 be amont the values printed?
A
x < 0
B
x >= 0
C
x < 20
D
All values of x
*E*
None of the above
Explanation
It's not possible to get 3 to print. This is because all possible values of x are covered by if x>=0 and x<20. This creates a range that includes all possible values of x, since any number is either >=0 or < 20.
Converting a value from one type to another sometimes requires an explicit cast and sometimes does not. Which of the following conversions and lines of reasoning explains how to convert a double d to an int i?
A
i = d. No explicit cast is necessary because if the conversion isn't valid, an exception is thrown.
B
i = (int) d. An explicit cast is needed to round d to the nearest integer.
C
i = d. No explicit cast is necessary because any int can be stored in a double.
*D*
i = (int) d. An explicit cast is needed because information may be lost in the conversion.
E
i = d. No explicit cast is necessary because d isn't changed in the conversion process.
Explanation
Not all doubles can be stored as ints. You must sign off on the potential information loss with an explicit cast.
What are the merits of insertion sort compared to bubble sort and selection sort?
A
It doesn't require as much extra storage.
B
It copies elements only to their final locations.
C
It requires less code.
*D*
It is faster for already sorted data.
E
It can be implement recursively.
Explanation
Neither selection nor bubble sort require extra storage. Selection sort doesn't make unnecessary copies. Bubble sort can be expressed in very little code. Any of them could be expressed recursively. If the array is already sorted, then insertion sort will only make N comparisons and no copies, giving it better performance than the other sorts.
public class Main {
public static void swap(int a, int b) {
int tmp = a;
a = b;
b = tmp;
}
public static void main(String[] args) {
int a = 5, b = 7;
swap(a, b);
System.out.println(a + " " + b);
}
}
A
7 5
*B*
5 7
C
5 5
D
7 7
E
12
Explanation
Main.swap only receives copies of main's a and b. Its assignments do not alter main's variables. Thus, a is still 5 and b is still 7 when the print statement is executed.
You need only examine the supertype of generic parameters on the Rosters class to determine the erasure type. There is no explicit supertype, so the supertype is Object.
in_str = input(’Enter a string: ’)
a = ’’
d = 0
r = 1
for c in ’abcdefghijklmnopqrstuvwxyz’:
if c in in_str:
a = c + a
else:
d = d + 1
r += 2
print(a) # Line 1
print(d) # Line 2
print(r) # Line 3
Given the input ’Frick & Frack’ what output is produced by Line 1?
A
FrickFrack
B
kcarkcir
C
acikr
*D*
rkica
E
none of the above
Explanation
Essentially this is filtering out all the upper case and non-alphabetic characters. The for loop goes through each lower-case letter, and if that letter is in the input string in_str, we concatenate the letter to the variable a.
in_str = input(’Enter a string: ’)
a = ’’
d = 0
r = 1
for c in ’abcdefghijklmnopqrstuvwxyz’:
if c in in_str:
a = c + a
else:
d = d + 1
r += 2
print(a) # Line 1
print(d) # Line 2
print(r) # Line 3
Given the input ’Frick & Frack’ what output is produced by Line 2?
A
5
*B*
21
C
10
D
86
E
none of the above
Explanation
This basically counts the number of lower case letters.
Your data has 4-bit keys. You also have magical, perfect hash function that will prevent any collisions from happening, provided there is room enough for all possible elements in the array. What's the minimum number of elements the array must be able to hold?
A
8
*B*
16
C
32
D
64
E
128
Explanation
4-bit keys uniquely identify 24 = 16 elements. The array must be able to hold these 16 items.
You've got this Word class for a project you are working on:
class Word {
private String letters;
...
public int hashCode() {
return letters.charAt(1);
}
}
For which of the word lists below is this implementation of hashCode a poor choice?
A
we, us, oh, by
B
aa, bb, cc, dd
C
mom, mill, mull, mat
*D*
cat, bad, fall, late
E
dinosaur, paroxysm, levitate, apiary
Explanation
The hashCode examines the second letter of each word to find the location in the hashtable. In list D, all words share the second letter 'a,' resulting in many collisions.
You know exactly how much data you need to store, but there's not much of it. You do not need to be able to search the collection quickly, but insertion should be as fast as possible. What is the simplest data structure that best suits for your needs?
*A*
Unordered array
B
Ordered array
C
Linked list
D
Hashtable
E
Binary search tree
Explanation
If you know the memory needs, you can allocate a large enough array. Inserting elements in the array can be done in constant time, and requires less work than inserting in a linked list.
The number of elements in a hashtable must be prime
A
so that linear probing will terminate
B
so that quadratic probing will terminate
C
to reduce collisions
D
to reduce cluster sizes
*E*
so that probing with a double hash visits all elements
Explanation
Since the double hash produces a fixed step size for probing, it may be the case that the step size is a factor of the table size. In this case, advancing by the fixed step size will land us in a cycling sequence.
You've got a class that holds two ints and that can be compared with other IntPair objects:
class IntPair {
private int a;
private int b;
public IntPair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(IntPair other) {
if (a < other.a) {
return -1;
} else if (a > other.a) {
return 1;
} else {
if (b == other.b) {
return 0;
} else if (b > other.b) {
return -1;
} else {
return 1;
}
}
}
}
Let's denote new IntPair(5, 7) as [5 7]. You've got a list of IntPairs:
[3 7], [4 6], [3 4]
You sort them using IntPair.compareTo. What is their sorted order?
A
[3 4], [3 7], [4 6]
*B*
[3 7], [3 4], [4 6]
C
[4 6], [3 7], [3 4]
D
[4 6], [3 4], [3 7]
Explanation
The compareTo orders first by IntPair.a in ascending order, and in the case of a tie, but IntPair.b in descending order.
int outer=0;
for (int i=0; i<12; i++) {
if (i % 2 == 0) {
outer++;
}
}
System.out.println(outer);
A
12
*B*
6
C
3
D
1
E
0
Explanation
i % 2 == 0 is true only when i is 0. This loop counts the number of even values between 0 and 12, exclusive (because the loop body doesn't execute when i is 12, the loop ends instead). In this case the result is 6 (0, 2, 4, 6, 8, 10).
in_str = input(’Enter a string: ’)
a = ’’
d = 0
r = 1
for c in ’abcdefghijklmnopqrstuvwxyz’:
if c in in_str:
a = c + a
else:
d = d + 1
r += 2
print(a) # Line 1
print(d) # Line 2
print(r) # Line 3
A
2
*B*
3
C
21
D
27
E
53
Explanation
The statement r+=2 is not inside the loop, so we just assign 1 to r, then add 2 to it to get 3.
s = input(’Enter a string: ’)
w = ’’
for c in s:
if c in "0123456789":
#REPLACE
else:
w = w + c
print w
What replacement for the comment #REPLACE will cause the program to print the input string with all of the digits removed? In other words, for the 'aaa3b3c1', we would print 'aaabc'.
A
break
*B*
continue
C
return w
D
any of the above
E
none of the above
Explanation
A is wrong because break will end the loop.
C is wrong because the problem asks us to print, not to return.
The continue statement works because it goes back to the top of the loop.
s = input(’Enter a string: ’)
w = ’’
for c in s:
if c in "0123456789":
#REPLACE
else:
w = w + c
print(w)
What replacement statement for the comment #REPLACE will cause the code to print out all of the characters up to the first digit? In other words, if the input is 'aaa3bb3c1', we should output 'aaa'.
*A*
break
B
continue
C
return w
D
any of the above will work
E
none of the above
Explanation
B is wrong because continue will skip the digits but continue with the rest of the String.
C is wrong because the exercise askes us to PRINT, not return the String.
In a heap, we only know that a node's key is greater than both its chidrens' keys. We may need to search both subheaps for an element. In the worst case, we'll visit every element.
Why can a heap be efficiently implemented using an array instead of a linked structure?
A
Linked implementations consume more space
B
The array never needs to change size
C
The heap condition makes it easier to calculate indices
D
We only traverse the heap in a breadth-first fashion
*E*
It is complete
Explanation
Because the heap is complete, the elements can be stored contiguously and parent and child nodes (which we're guaranteed to have) fall in locations we can compute with simple arithmetic.
class Custom {
private int i;
...
public String toString() {
return "" + i;
}
}
Consider this code, which prints a Custom instance:
Custom a = ...;
System.out.println(a);
What overloaded version of PrintStream.println is called?
A
println(String s)
B
println(Custom c)
C
println(int i)
D
println()
*E*
println(Object o)
Explanation
The version of println that we call must have a type that is a supertype of Custom, leaving only Custom and Object as our two choices. Since PrintStream was written years before our Custom class ever existed, it doesn't know anything about our class. However, it does know about Objects and that all Objects have a toString method.