Professional Documents
Culture Documents
Mid-Term Study Guide: Multiple Choice Questions
Mid-Term Study Guide: Multiple Choice Questions
Chapter 1
Multiple Choice Questions:
1) A Java program is best classified as
a) hardware
b) software
c) storage
d) processor
e) input
Answer: b. Explanation: Programs are classified as software to differentiate them from the mechanisms of
the computer (hardware). Storage and the processor are two forms of hardware while input is the information that the program
processes.
3) When executing a program, the processor reads each program instruction from
a) secondary memory (storage)
b) the Internet
c) registers stored in the processor
d) main memory
e) could be any of these
Answer: d. Explanation: The program is first loaded from secondary memory into main memory before it is executed so that the
processor is not slowed down when reading each instruction. This idea of executing programs stored in memory is called the Stored
Program Computer and was pioneered by Von Neumann in the 1940s.
5) Volatility is a property of
a) RAM
b) ROM
c) disk
d) software
e) computer networks
Answer: a. Explanation: Volatility means that the contents of memory are lost if the electrical power isshut
off. This is true of RAM, but not ROM or disk. Software and computer networks are not forms of memory.
6) The ability to directly obtain a stored item by referencing its address is known as
a) random access
b) sequential access
c) read-only access
d) fetch access
e) volatility
Answer: a. Random access is meant to convey that accessing any item is equally easy, and that any item is
retrievable based solely on its address. Random access is the form of access used by both RAM and ROM
memory. Disk access, called direct access, is a similar idea and direct and random access are sometimes
referred to synonymously. Sequential access is used by tape.
7) In order for a computer to be accessible over a computer network, the computer needs its own
a) MODEM
b) Communication line
c) Network address
d) Packet
e) Router
Answer: c. Explanation: In order to differentiate between the computers on a network, each is given its own,
unique, network address. In this way, a message intended for one computer can be recognized by that
computer through the messages destination address. A MODEM is a device that is used to allow a computer
to communicate to another computer over the telephone line. The communication line is the network media
itself. A packet is a piece of information being sent from over a network. A router is a hardware device used
to take a message from one network and move it to another based on the messages destination address.
9) It is important to dissect a problem into manageable pieces before trying to solve the problem because
a) most problems are too complex to be solved as a single, large activity
b) most problems are solved by multiple people and it is easy to assign each piece to a separate person
c) it is easier to integrate small pieces of a program into one program than it is to integrate one big chunk
of code into one program
d) our first solution may not solve the problem correctly
e) all of the above
Answer: a. Any interesting problem will be too complex to solve easily as a single activity. By decomposing
the problem, we can build small solutions to each piece and then integrate the pieces. Answer d is true, but is
not the reason why we will break a problem down into pieces.
10) Once we have implemented the solution, we are not done with the problem because
a) the solution may not be the best (most efficient)
b) the solution may have errors and need testing and fixing before we are done
c) the solution may, at a later date, need revising to handle new specifications
d) the solution may, at a later date, need revising because of new programming language features
e) all of the above
Answer: e. Explanation: A program should not be considered as a finished product until we are reasonably
assured that it is efficient and error-free. Further, it is common that programs require modification in the future
because of a change to specifications or a change to the language or computer running the program.
11) Of the following list, which one is not true regarding Java as a programming language?
Lewis/Loftus/Cocking: Chapter 1 Test Bank TB 3
a) It is a relatively recent language, having been introduced in 1995
b) It is a language whose programs do not require translating into machine language before they are
executed
c) It is an object-oriented programming language
d) It is a language that embraces the idea of writing programs to be executed using the World Wide Web
e) All of the above are true
Answer: b. Explanation: All languages require translation into machine language. The other statements are
all true about Java.
19) An error in a program that results in the program outputting $100 instead of the correct answer, $250 is
a) a programmer error
b) a syntax error
c) a run-time error
d) a logical error
e) a snafu
Answer: d. Explanation: While this is an error (answer a), programmers classify the type of error in order to
more easily solve the problem. Syntax errors are caught by the compiler and the program cannot run without
fixing all syntax errors. Run-time errors arise during program execution and cause the program to stop running
abnormally. Logical errors are errors whereby the program can run to completion, but gives the wrong answer.
If the result should have been $250, then the logic of the program is wrong since it output $100. A snafu is a
term expressing a messed up situation in combat and should not be used by respectable programmers!
20) Following Java naming convention, which of the following would be the best name for a class about store
customers?
a) StoreCustomer
b) Store Customer
c) storeCustomer
d) STORE_CUSTOMER
e) Store-Customer
Answer: a. Explanation: The Java naming convention states that classes should all start with an upper case
letter and that multiple-word names should start each new name with an upper case letter while the remaining
characters are lower case. Words should either be connected together without spaces, or connected with the
_ character. Answers b and e are not legal names, and using Java naming convention, c would qualify as a
variable name and d would qualify as a constant.
21) Which of the following would be a good variable name for the current value of a stock?
a) curstoval
b) theCurrentValueOfThisStockIs
Lewis/Loftus/Cocking: Chapter 1 Test Bank TB 5
c) currentStockVal
d) csv
e) current
Answer: c. Explanation: Java allows long variable names but the programmer must find a good compromise
between an excessive long name (as with b) and names too short to understand their use (a and d). The name
current might be reasonable if there are no other current values being referenced in the program.
23) A color image is broken down into individual pixels (points), each of which is represented by
a) a 1 for white and a 0 for black
b) 3 values denoting the shade of red, green and blue in the image
c) a single number indicating the intensity of color between white and black
d) two numbers, a value that denotes where between white and black the color is, and a brightness
e) none of the above, it is not possible to represent a color image.
Answer: b. Explanation: Black and white images are stored using 0s and 1s while color images are stored
using three values, one each for the degree of red, the degree of blue, and the degree of green.
24) Which of the following characters does not need to have an associated closing character in a Java program?
a) {
b) (
c) [
d) <
e) all of these require closing characters
Answer: d. Explanation: { is used to open a block, and so } is needed to close the block. ( is used to open an
expression and so ) is needed to close an expression. [ is used to start an array index so ] is needed to close the
array index. < is less than and > is greater than and these are not needed together, so < requires no closing
character.
6) If you want to output the text "hi there", including the quote marks, which of the following could do that?
a) System.out.println("hi there");
b) System.out.println(""hi there"");
c) System.out.println("\"hi there");
d) System.out.println("\"hi there\"");
e) none, it is not possible to output a quote mark because it is used to mark the beginning and ending of
the String to be output.
Answer: d. Explanation: \" is an escape sequence used to place a quote mark in a String, so it is used here to
output the quote marks with the rest of the String.
11) If x is an int and y is a double, all of the following are legal except which assignment statement?
1) y = x;
2) x = y;
3) y = (double) x;
4) x = (int) y;
5) all of the above are legal
Answer: b. Explanation: Since x is an int, it cannot accept a double unless the double is cast as an int. There is no
explicit cast in the assignment statement in b. In a, a cast is not necessary because a double (y) can accept an int
value (x), and in c and d, explicit casts are present making them legal.
12) Given the following assignment statement, which of the following answers is true regarding the order that the
operators will be applied based on operator precedence?
a = (b + c) * d / e f;
a) *, /, +, -
b) *, +, /, -
c) +, *, /, -
d) +, /, *, -
e) +, -, *, /
Answer: c. Explanation: Order of precedence is any operator in ( ) first, followed by * and / in a left-to-right
manner, followed by + and in a left-to-right manner. So, + is first since it is in ( ), followed by * followed by /
since * is to the left of /, followed finally by -.
13) What will be the result of the following assignment statement? Assume b = 5 and c = 10.
int a = b * (-c + 2) / 2;
a) 30
b) 30
c) 20
d) 20
e) 6
Answer: d. Explanation: The unary minus is applied first giving c + 2 = -8. Next, the * is performed giving 5 * -
8 = -40, and finally the / is performed giving 40 / 2 = -20.
14) Assume that x, y and z are all ints equal to 50, 20 and 6 respectively. What is the result of x / y / z?
a) 0
b) 12
c) 16
d) A syntax error as this is syntactically invalid
e) A run-time error because this is a division by 0
Answer: a. Explanation: This division is performed left to right, so first 50 / 20 is performed. Since 50 and 20 are
ints, this results in 2. Next, 2 / 6 is performed which is 0. Notice that if the division were performed right to left,
the evaluation would instead be 50 / (20 / 6) = 50 / 3 = 16.
15) What is output with the statement System.out.println(x+y); if x and y are int values where x=10 and y=5?
a) 15
b) 105
c) 10 5
d) x+y
e) An error since neither x nor y is a String
Answer: a. Explanation: Java first computes x+y and then casts it as a String to be output. x + y = 10 + 5 = 15,
so the statement outputs 15.
16) What is output with the statement System.out.println(""+x+y); if x and y are int values where x=10 and y=5?
a) 15
b) 105
c) 10 5
d) x+y
e) An error since neither x nor y is a String
Answer: b. Explanation: The "" casts the rest of the expression as a String, and so the two + signs are used as
String concatenation, and so x + y becomes x concatenated with y, or 105.
17) If you want to store into the String name the value "George Bush", you would do which statement?
a) String name = "George Bush";
b) String name = new String("George Bush");
c) String name = "George" + " " + "Bush";
d) String name = new String("George" + " " + "Bush");
e) Any of the above would work
Answer: e. Explanation: There are two ways to store a character string into a String variable, by constructing a
new String using "new String(string value); " or by using an assignment statement, so either a or b will work. In c
and d, we have variations where the String concatenation operator + is used. So all four approaches will work.
18) Consider having three String variables a, b and c. The statement c = a + b; can also be achieved by doing
a) c = a.length( ) + b.length( );
b) c = (int) a + (int) b;
c) c = a.concat(b);
d) c = b.concat(a);
e) c = a.plus(b);
Answer: c. The statement c = a + b uses the concatenation operator + (not to be confused with numeric addition).
The same result can be achieved by passing a the concat message with b as the parameter. Answer d will set c to be
b + a rather than a + b.
20) Which of the following would return the last character of the String x?
a) x.charAt(0);
b) x.charAt(last);
c) x.charAt(length(x));
d) x.charAt(x.length( )-1);
e) x.charAt(x.length( ));
Answer: d. Explanation: Since last is not defined, b is syntactically invalid. The 0th character is the first in the
String, so a is true only if the String has a single character. The answer in c is syntactically invalid as length can
only be called by passing the message to x. Finally, d and e are syntactically valid, but since length returns the size
of the String, and since the first character starts at the 0th position, the last character is at x.length()-1, so e would
result in a run-time error.
21) Which library package would you import to use the class Random?
a) java.beans
b) java.io
c) java.lang
d) java.text
e) java.util
Answer: e. Explanation: This is a java utility, and so is found in the java.util package.
22) Since you cannot take the square root of a negative number, you might use which of the following instructions
to find the square root of the variable x?
a) Math.sqrt(x*x);
b) Math.sqrt((int) x);
c) Math.sqrt(Math.abs(x));
d) Math.abs(Math.sqrt(x));
e) Math.sqrt(-x);
Answer: c. Explanation: Math.abs returns the absolute value of x. If x is negative, Math.sqrt(x) causes a run-time
error, but Math.sqrt(Math.abs(x)) does not since x is first converted to its positive equivalent before the square root
is performed. Answer a returns x (square root of x2 is x). In answer b, casting x to an int will not resolve the
problem if x is negative. In answer d, the two Math functions are performed in opposite order and so if x is
negative, it still generates a run-time error. Answer e will only work if x is not positive and so if x is positive, it
now generates a run-time error.
23) Assume that x is a double that stores 0.362491. To output this value as 36%, you could use the NumberFormat
class with NumberFormat nf = NumberFormat.getPercentInstance( ); Which of the following statements then
would output x as 36%?
a) System.out.println(x);
b) System.out.println(nf);
c) System.out.println(nf.x);
d) System.out.println(nf.format(x));
e) System.out.println(format(x));
Answer: d. Explanation: nf is an object and so must be passed a message to use it. The method to format a double
is called format and the value to be formatted is the parameter passed to format. Therefore, the proper way to do
this is nf.format(x). The answer in a will merely output 0.362491 while the answers to b, c and e are syntactically
invalid.
2) In which phase of program development would you expect the programmer(s) to determine the classes and
objects needed?
a) Software requirements
b) Software design
c) Software implementation
d) Software testing
e) Could occur in any of the above
Answer: b. Explanation: Determining which classes and objects to use or create is part of the design.
4) If a programmer follows the four phases of program development as intended, which of the four phases should
require the least amount of creativity?
a) Software requirements
b) Software design
c) Software implementation
d) Software testing
e) None of the above, all four levels would require equal creativity
Answer: c. Explanation: Once the implementation phase has been reached, the algorithm should have already
been specified, so the only effort involved in the implementation phase is of translating from the design (which is
probably in an English-like pseudocode) to the programming language, and entering the code through an editor.
The requirements and design phases require understanding the problem and coming up with a solution respectively,
requiring creativity, and the testing phase will require diagnostic abilities usually forcing the programmer(s) to be
creative in how the errors are found and fixed.
5) The idea that program instructions execute in order (linearly) unless otherwise specified through a conditional
statement is known as
a) boolean execution
b) conditional statements
c) try and catch
d) sequentiality
e) flow of control
Answer: e. Explanation: The flow of control describes the order of execution of instructions. It defaults to
being linear (or sequential) but is altered by using control statements like conditionals and loops.
6) Of the following if statements, which one correctly executes three instructions if the condition is true?
a) if (x < 0)
a = b * 2;
y = x;
z = a y;
b) {
if (x < 0)
a = b * 2;
y = x;
z = a y;
}
c) if { (x < 0)
a = b * 2;
y = x;
z=ay;
}
d) if (x < 0)
{
a = b * 2;
y = x;
z = a y;
}
e) b, c and d are all correct, but not a
Answer: d. Explanation: In order to have three instructions execute in the if clause when the condition is true, the
three statements must be placed in a block following the condition. This is the syntax used in d. In a, there is no
block. In b, the block is placed around the entire if statement such that the if clause is only a = b * 2; and the other
two statements are not part of the if statement, but follow it. The syntax in c is illegal resulting in a syntax error.
Dont forget that the structure of your code (how it lines up) is immaterial to the compiler.
7) Which of the sets of statements below will add 1 to x if x is positive and subtract 1 from x if x is negative but
leave x alone if x is 0?
a) if (x > 0) x++;
else x--;
b) if (x > 0) x++;
else if (x < 0) x--;
c) if (x > 0) x++;
if (x < 0) x--;
else x = 0;
d) if (x == 0) x = 0;
else x++;
x--;
e) x++;
x--;
Answer: b. Explanation: if x is positive, x++ is performed else if x is negative x-- is performed and otherwise,
nothing happens, or x is unaffected. In a, c, d and e, the logic is incorrect. In a, x-- is done if x is not positive, thus
if x is 0, x becomes 1 which is the wrong answer. In c, if x is positive, then x++ is performed. In either case, the
next statement is executed and if x is not negative, the else clause is performed setting x to 0. So if x is positive, it
becomes 0 after this set of code. In d, x++ and x-- are both performed if x is not 0. And in e, this code does not
attempt to determine if x is positive or negative, it just adds one and then subtracts 1 from x leaving x the same.
9) If x is currently 0, a = 0 and b = -5, what will x become after the above statement is executed?
a) 0
b) 2
c) 3
d) 4
e) 5
Answer: b. Explanation: Since (a > 0) is not true, the else clause for this condition is executed, which is x = x +
2, so x is now 2.
10) If x is currently 0, a = 1 and b = -1, what will x become after the above statement is executed?
a) 0
b) 2
c) 3
d) 4
e) 5
Answer: e. Explanation: Since (a > 0) is true, the if clause is executed, which is another if statement. Its condition
(b < 0) is true, so its if clause is executed, which is x = x + 5, so x is now 5.
11) Consider the following code that will assign a letter grade of A, B, C, D, or F depending on a students
test score.
if(score >= 90) grade = 'A';
if(score >= 80) grade = 'B';
if(score >= 70) grade = 'C';
if(score >= 60) grade = 'D';
else grade = F;
a) This code will work correctly in all cases
b) This code will work correctly only if grade >= 60
Lewis/Loftus/Cocking: Chapter 3 Test Bank TB 25
c) This code will work correctly only if grade < 60
d) This code will work correctly only if grade < 70
e) This code will not work correctly under any circumstances
Answer: d. Explanation: The problem with this code is that it consists of three if statements followed by one ifelse
statement, rather than a nested if-else statement. So the logic is improper. If the students grade falls into the
A category, then all 4 conditions are true and the student winds up with a D. If the students grade falls into the
B category, then the first condition is false, but the next three are true and the student winds up with a D. If the
students grade falls into the D category, then the only condition that is true is the one that tests for D and so the
grade is assigned correctly. If the students grade falls into the F category, then none of the conditions are true
and an F is assigned correctly. So, only if the grade < 70 does the code work correctly.
12) Assume that count is 0, total is 20 and max is 1. The following statement will do which of the following? if
(count != 0 && total / count > max) max = total / count;
a) The condition short circuits and the assignment statement is not executed
b) The condition short circuits and the assignment statement is executed without problem
c) The condition does not short circuit causing a division by zero error
d) The condition short circuits so that there is no division by zero error when evaluating the condition,
but the assignment statement causes a division by zero error
e) The condition will not compile because it uses improper syntax
Answer: a. Explanation: Since count is 0, (count != 0) is false. Because the left-hand side of an && condition is
false, the condition is short circuited, and so the right-hand side is not evaluated. Thus, a potential division by zero
error is avoided. Because the condition is false, the statement max = total / count is not executed, again avoiding a
potential division by zero error.
13) What is wrong, logically, with the following code?
if (x > 10) System.out.println("Large");
else if (x > 6 && x <= 10) System.out.println("Medium");
else if (x > 3 && x <= 6) System.out.println("Small");
else System.out.println("Very small");
a) There is no logical error, but there is no need to have (x <= 10) in the second conditional or (x <= 6)
in the third conditional
b) There is no logical error, but there is no need to have (x > 6) in the second conditional or (x > 3) in the
third conditional
c) The logical error is that no matter what value x is, Very small is always printed out
d) The logical error is that no matter what value x is, Large is always printed out
e) There is nothing wrong with the logic at all
Answer: a. Explanation: Because this is a nested if-else statement, if (x > 10) is true, then the first println
statement is executed and the rest of the statement is skipped. If (x > 10) is not true, then the first else clause is
executed and the next if condition is tested. At this point, (x > 10) is known to be false and therefore (x <= 10)
must be true, so there is no need to check this inequality. Similarly, if (x > 6) is false, then the second else clause is
executed and the third if condition is tested. However, (x <= 6) must be true, so there is no need to check this
inequality.
14) Consider the following outline of a nested if-else structure which has more if clauses than else clauses. Which
of the statements below is true regarding this structure?
if (condition1)
if (condition2)
statement1;
else statement2;
a) syntactically it is invalid to have more if clauses than else clauses
b) statement2 will only execute if condition1 is false and condition2 is false
c) statement2 will only execute if condition1 is true and condition2 is false
d) statement2 will only execute if condition1 is false, it does not matter what condition2 is
e) statement2 will never execute
Answer: b. Explanation: The else clause must be matched to the most recent if statement. Therefore, the else
goes with the if statement that tests condition2, not the if statement that tests condition1. So, if condition1 is true
and condition2 is false, then statement2 will execute.
TB 26 Lewis/Loftus/Cocking: Chapter 3 Test Bank
15) Assume that x and y are int variables with x = 5, y = 3, and a and d are char variables with a = 'a' and d = 'A',
and examine the following conditions:
Condition 1: (x < y && x > 0)
Condition 2: (a != d || x != 5)
Condition 3: !(true && false)
Condition 4: (x > y || a == 'A' || d != 'A')
a) All 4 Conditions are true
b) Only Condition 2 is true
c) Condition 2 and Condition 4 are true only
d) Conditions 2, 3 and 4 are all true, Condition 1 is not
e) All 4 Conditions are false
Answer: d. Explanation: Condition 1 is not true because (x < y) is false, making the entire condition false. Since
(c != d) is true, Condition 2 is true even though (x != 5) is false. Condition 3 is true because (true && false) is
false, but !false is true. Condition 4 is true because (x > y) is true, making the entire Condition true. Therefore,
Conditions 2, 3 and 4 are true while Condition 1 is false.
16) If x is an int where x = 1, what will x be after the following loop terminates?
while (x < 100)
x *= 2;
a) 2
b) 64
c) 100
d) 128
e) None of the above, this is an infinite loop
Answer: d. Explanation: With x = 1, the loop condition is true and the statement executes, doubling x, which is
now 2. Since the loop condition is still true, the statement executes again, doubling x to 4. The condition remains
true for the next 4 iterations, where x becomes 8, 16, 32 and 64. Since (x < 100) is still true when x = 64, the loop
iterates again and x becomes 2 * 64 = 128. Now, (x < 100) is no longer true and the loop terminates with x = 128.
17) If x is an int where x = 0, what will x be after the following loop terminates?
while (x < 100)
x *= 2;
a) 2
a) 64
b) 100
c) 128
d) None of the above, this is an infinite loop
Answer: e. Explanation: Since x starts at 0, x *= 2; results in 0 * 2, or x = 0. Since x remains 0, (x < 100) remains
true, and the loop repeats. x continues to be 0 and so the condition never changes to false, and thus the loop never
terminates.
18) Given the following code, where x = 0, what is the resulting value of x after the for-loop terminates?
for(int i=0;i<5;i++)
x += i;
a) 0
b) 4
c) 5
d) 10
e) 15
Answer: d. Explanation: Each pass through the for-loop results with the current value of the loop index, i, being
added to x. The first time through the loop, i = 0 so x = x + 0 = 0. The second time through the loop i = 1 so x = x
+ 1 = 1. The third time through the loop i = 2 so x = x + 2 = 3. The fourth time through the loop i = 3 so x = x + 3
= 6. The fifth and final time through the loop i = 4 so x = x + 4 = 10.
20) Given two String variables, s1 and s2, to determine if they are the same length, which of the following
conditions would you use?
a) (s1.equals(s2))
b) (s1.length( ).equals(s2))
c) (s1.length( ).equals(s2.length( ))
d) (s1.length( ) == s2.length( ))
e) length(s1) == length(s2)
Answer: d. Explanation: Since s1 and s2 are Strings, we can only obtain their length by passing the length( )
message to each one. The length( ) method returns an int that we can directly compare against another int using ==,
as done in d. The answers for b and c are syntactically invalid since s1.length( ) returns an int, and so cannot be
passed the message .equals( ). The answer in e is also syntactically invalid. Finally, the answer in a determines if
the two Strings are the exact same. While their lengths will be equal if this is true, two Strings may have equal
length but not be equal, so this is logically incorrect.
21) Given a String, s, which is assumed to have at least one character in it, which of the following conditions
would determine if the first character of the String is the same as the last character?
f) (s.charAt(0) == s.charAt(s.length( )))
g) (s.charAt(1) == s.charAt(s.length( )))
h) (s.charAt(0) == s.charAt(s.length( ) - 1))
i) (s.charAt(0) == s.charAt(s.length( ) + 1))
j) (s.charAt(0) == s.charAt(last))
Answer: c. Explanation: The first character of a String starts at position 0. So, if a Strings length is 5, then its
last character is at position 4. Therefore, the last character is at position s.length( ) 1. The answer in e could be
correct, but only if last had been previously set equal to s.length( ) 1.
22) Given that s is a String, what does the following loop do?
for(int j = s.length( ); j > 0; j--)
System.out.print(s.charAt(j-1));
a) it prints s out backwards
b) it prints s out forwards
c) it prints s out backwards after skipping the last character
d) it prints s out backwards but does not print the 0th character
e) it yields a run-time error because there is no character at s.charAt(j-1) for j = 0
Answer: a. Explanation: The variable j counts down from the length of the String to 1, each time printing out the
character at position j-1. The character at length 1 is the first character printed and this is the last character of the
String. It continues until it reaches j = 1, and prints out the character at position j 1, or the 0 th character, so it
prints the entire String backwards.
23) The following nested loop structure will execute the inner most statement (x++) how many times?
for(int j = 0; j < 100; j++)
for(int k = 100; k > 0; k--)
x++;
a) 100
b) 200
c) 10,000
d) 20,000
e) 1,000,000
Answer: c. The outer loop iterates 100 times. Each time it iterates, the inner loop, and the x++ statement, execute
100 times. Therefore, the statement x++ executes 100*100 = 10,000 times.
24) This paint method will draw several bars (sort of like a bar graph). How many bars will be displayed?
a) 4
b) 5
c) 6
d) 10
e) 20
Answer: b. Explanation: Since x iterates from 100 up to 200 in units of 20, it iterates 5 times (x = 100, x = 120, x
= 140, x = 160, x = 180).
3) To define a class that will represent a car, which of the following definitions is most appropriate?
a) private class car
b) public class car
c) public class Car
d) public class CAR
e) private class Car
Answer: c. Explanation: Classes should be defined to be public so that they can be accessed by other classes. And
following Java naming convention, class names should start with a capital letter and be lower case except for the
beginning of each new word, so Car is more appropriate than car or CAR.
4) Which of the following reserved words in Java is used to create an instance of a class?
a) class
b) public
c) public or private, either could be used
d) import
e) new
Answer: e. Explanation: The reserved word new is used to instantiate an object, that is, to create an instance of a
class. The statement new is followed by the name of the class. This calls the class constructor. Example: Car x = new
Car( ); will create a new instance of a Car and set the variable x to it.
5) In order to preserve encapsulation of an object, we would do all of the following except for which one?
a) Make the instance data private
b) Define the methods in the class to access and manipulate the instance data
c) Make the methods of the class public
d) Make the class final
e) All of the above preserve encapsulation
Answer: d. Explanation: Encapsulation means that the class contains both the data and the methods needed to
manipulate the data. In order to preserve encapsulation properly, the instance data should not be directly accessible
from outside of the classes, so the instance data are made private and methods are defined to access and manipulate the
instance data. Further, the methods to access and manipulate the instance data are made public so that other classes can use the object.
The reserved word final is usedto control inheritance and has nothing to do with encapsulation.
7) Consider a sequence of method invocations as follows: main calls m1, m1 calls m2, m2 calls m3 and then m2 calls
m4, m3 calls m5. If m4 has just terminated, what method will resume execution?
a) m1
b) m2
c) m3
d) m5
e) main
Answer: b. Explanation: Once a method terminates, control resumes with the method that called that method. In this
case, m2 calls m4, so that when m4 terminates, m2 is resumed.
8) A variable whose scope is restricted to the method where it was declared is known as a(n)
a) parameter
b) global variable
c) local variable
d) public instance data
e) private instance data
Answer: c. Explanation: Local variables are those that are local to the method in which they have been declared,
that is, they are accessible only inside that method. Global variables are those that are accessible from anywhere, while
parameters are the variables passed into a method. Instance data can be thought of as global variables for an entire
object.
For questions 5-8, consider a class that stores 2 int values. These values can be assigned int values with the messages
set1(x) and set2(x) where x is an int, and these values can be accessed through get1( ) and get2( ). Assume that y and z
are two objects of this class. The following instructions are executed:
y.set1(5);
y.set2(6);
z.set1(3);
z.set2(y.get1( ));
y = z;
8) If the instructions z.set2(5); and y.set1(10); are performed, which of the following is true?
a) (y = = z) is still true
b) (y.get1( ) = = z.get1( )) but (y.get2( ) != z.get2( ))
c) (y.get1( ) = = z.get1( )) and (y.get2( ) = = z.get2( )) but (y != z)
d) (y.get1( ) = = z.get2( )) and (y.get2( ) = = z.get1( )) but (y != z)
e) this statement causes a run-time error
Answer: a. Explanation: Since y=z; was peformed previously, y and z are aliases meaning that they refer to the same
object. The statement z.set2(5); causes a change to the object's second value while y.set1(10); causes a change to the
object's first value but neither change the fact that y and z are aliases.
9) Consider the following swap method. If String x = "Hello" and String y = "Goodbye", then swap(x, y); results
in which of the following?
public void swap(String a, String b)
{
String temp;
temp = a;
a = b;
b = temp;
}
a) x is now "Goodbye" and y is now "Hello"
b) x is now "Goodbye" and y is still "Goodbye", but (x != y)
c) x is still "Hello" and y is now "Hello", but (x != y)
d) x and y are now aliases
e) x and y remain unchanged
Answer: e. Explanation: When x and y are passed to swap, a and x become aliases and b and y become aliases. The
statement temp = a sets temp to be an alias of a and x. The statement a = b sets a to be an alias of b and y, but does not
alter x or temp. Finally, b = temp sets b to be an alias of temp and y, but does not alter y. Therefore, x and y remain the
same.
10) Which of the following methods is a static method? The class in which the method is defined is given in
parentheses following the method name.
a) equals (String)
b) toUpperCase (String)
c) sqrt (Math)
d) format (DecimalFormat)
e) paint (Applet)
Answer: c. Explanation: The Math class defines all of its methods to be static. Invoking Math methods is done by
using Math rather than a variable of type Math. The other methods above are not static.
12) What is the value of z after the third statement executes below?
StaticExample a = new StaticExample(5);
StaticExample b = new StaticExample(12);
int z = a.incr( );
a) 5
b) 6
c) 12
d) 13
e) none, the code is syntactically invalid because a and b are attempting to share an instance data
Answer: d. Explanation: Since instance data x is shared between a and b, it is first initialized to 5, it is then changed to
12 when b is instantiated, and then it is incremented to 13 when a.incr( ) is performed. So, incr returns the value 13.
13) If there are 4 objects of type StaticExample, how many different instances of x are there?
a) 0
b) 1
c) 3
d) 4
e) There is no way to know since any of the objects might share x, but they do not necessarily share x
Answer: b. Explanation: Because x is a static instance data, it is shared among all objects of the StaticExample class,
and therefore, since at least one object exists, there is exactly one instance of x.
14) An object that refers to part of itself within its own methods can use which of the following reserved words to
denote this relationship?
a) inner
b) i
c) private
d) this
e) static
Answer: d. Explanation: The reserved word this is used so that an object can refer to itself. For instance, if an object
has an instance data x, then this.x refers to the objects value x. While this is not necessary, it can be useful if a local
variable or parameter is named the same as an instance data. The reserved word this is also used to refer to the class as
a whole, for instance, if the class is going to implement an interface class rather than import an implementation of an
interface class.
15) Which of the following interfaces would be used to implement a class that represents a group (or collection) of
objects?
a) Iterator
b) Speaker
c) Comparable
d) MouseListener
e) KeyListener
Answer: a. Explanation: Iterator is an abstract class allowing the user to extend a given class that implements Iterator
by using the features defined there. These features include being able to store a group of objects and iterate (step)
through them.
16) In order to implement Comparable in a class, what method(s) must be defined in that class?
a) equals
b) compares
c) both lessThan and greaterThan
d) compareTo
e) both compares and equals
Answer: d. Explanation: The Comparable class requires the definition of a compareTo method that will compare two
objects and determine if one is equal to the other, or if one is less than or greater than the other and respond with a
negative int, 0 or a positive int. Since compareTo responds with 0 if the two objects are equal, there is no need to also
define an equals method.
For questions 17-18, consider a class called ChessPiece. This class has two instance data, String type and int player.
The variable type will store King, Queen, Bishop, etc and the int player will store 0 or 1 depending on whose
piece it is. We wish to implement Comparable for the ChessPiece class. Assume that, the current ChessPiece is
compared to a ChessPiece passed as a parameter. Pieces are ordered as follows: Pawn is a lesser piece to a Knight
and a Bishop, Knight and Bishop are equivalent for this example, both are lesser pieces to a Rook which is a
lesser piece to a Queen which is a lesser piece to a King.
17) Which of the following method headers would properly define the method needed to make this class
Comparable?
a) public boolean comparable(Object cp)
b) public int comparable(Object cp)
c) public int compareTo(Object cp)
d) public int compareTo( )
e) public boolean compareTo(Object cp)
Answer: c. Explanation: To implement Comparable, you must implement a method called compareTo which returns
an int. Further, since this class will compare this ChessPiece to another, we would except the other ChessPiece to be
passed in as a parameter (although compareTo is defined to accept an Object, not a ChessPiece).
18) Which of the following pieces of logic could be used in the method that implements Comparable? Assume
that the method is passed Object a, which is really a ChessPiece. Also assume that ChessPiece has a method called
returnType which returns the type of the given piece. Only one of these answers has correct logic.
a) if (this.type < a.returnType( )) return 1;
b) if (this.type = = a.returnType( )) return 0;
c) if (this.type.equals(a.returnType( )) return 0;
d) if (a.returnType( ).equals(King)) return -1;
e) if (a.returnType( ).equals(Pawn)) return 1;
Answer: c. Explanation: If the type of this piece and of a are the same type, then they are considered equal and the
method should return 0 to indicate this. Note that this does not cover the case where this piece is a Knight and a is a
Bishop, so additional code would be required for the equal to case. The answer in b is not correct because it
compares two Strings to see if they are the same String, not the same value. The logic in d and e are incorrect because
neither of these takes into account what the current piece is, only what the parameters type is. In d, if a is a King, it
will be greater than this piece if this piece is not a King, but will be equal if this piece is a King and similarly in e, it
does not consider if this piece is a Pawn or not. Finally, a would give a syntax error because two Strings cannot be
compared using the < operator.
20) Assume that you are defining a class and you want to implement an ActionListener. You state
addActionListener(this); in your class constructor. What does this mean?
a) The class must import another class which implements ActionListener
b) The class must define the method actionPerformed
c) The class must define the method ActionListener
d) The class must define an inner class called ActionListener
e) The class must define the method actionPerformed in an inner class named ActionListener
Answer: b. Explanation: Since the ActionListener being implemented is being added in this class (that is what the
this refers to in addActionListener), then this class must define the abstract methods of the ActionListener class.
There is only one abstract method, actionPerformed. The answer in a is not true, if the class that implements
ActionListener were being imported (assume that the variable al is an instance of this imported class), then the proper
statement would be addActionListener(al);.
21) A Java program can handle an exception in several different ways. Which of the following is not a way that a
Java program could handle an exception?
a) ignore the exception
b) handle the exception where it arose using try and catch statements
c) propagate the exception to another method where it can be handled
d) throw the exception to a pre-defined Exception class to be handled
e) all of the above are ways that a Java program could handle an exception
Answer: d. Explanation: A thrown exception is either caught by the current code if the code is contained inside a try
statement and the appropriate catch statement is implemented, or else it is propagated to the method that invoked the
method that caused the exception and caught there in an appropriate catch statement, or else it continues to be
propagated through the methods in the opposite order that those methods were invoked. This process stops however
once the main method is reached. If not caught there, the exception causes termination of the program (this would be
answer a, the exception was ignored). However, an exception is not thrown to an Exception class.
23) In order to have some code throw an exception, you would use which of the following reserved words?
a) throw
b) throws
c) try
d) Throwable
e) goto
Answer: a. Explanation: The reserved word throw is used to throw an exception when the exception is detected, as in:
if (score < 0) throw new IllegalTestScoreException(Input score + score + is negative);
Chapter 6: Arrays
Multiple Choice Questions:
For questions 1-4, assume values is an int array that is currently filled to capacity, with the following values:
1) What is returned by values[3]?
a) 9
b) 12
c) 2
d) 6
e) 3
Answer: c. Explanation: Java array indices start at 0, so values[3] is really the fourth array element, which is 2.
3) Which of the following loops would adequately add 1 to each element stored in values?
a) for(j=1;j<values.length;j++) values[j]++;
b) for(j=0;j<values.length;j++) values[j]++;
c) for(j=0;j<=values.length;j++) values[j]++;
d) for(j=0;j<values.length1;j++) values[j]++;
e) for(j=1;j<values.length1;j++) values[j]++;
Answer: b. Explanation: The first array element is values[0], so the for-loop must start at 0, not 1. There are
values.length elements in the array where the last element is at values.length1, so the for loop must stop before
reaching values.length. This is the case in b. In d, the for loop stops 1 before values.length since < is being used to
test the condition instead of <=.
5) Which of the following is a legal way to declare and instantiate an array of 10 Strings?
a) String s = new String(10);
b) String[10] s = new String;
c) String[ ] s = new String[10];
d) String s = new String[10];
e) String[ ] s = new String;
9 4 12 2 6 8 18
Answer: c. Explanation: Declaring an array is done by type[ ] variable. Instantiating the array is done by variable =
new type[dimension] where dimension is the size of the array.
8) What does the following code do? Assume list is an array of int values, temp is some previously initialized int
value, and c is an int initialized to 0.
for(j=0;j<list.length.j++)
if(list[j] < temp) c++;
a) It finds the smallest value and stores it in temp
b) It finds the largest value and stores it in temp
c) It counts the number of elements equal to the smallest value in list
d) It counts the number of elements in list that are less than temp
e) It sorts the values in list to be in ascending order
Answer: d. Explanation: The statement if(list[j]<temp) c++; compares each element in list to temp and adds one to c
only if the element is less than temp, so it counts the number of elements in list less than temp, storing this result in c.
An int array stores the following values. Use the array to answer questions 9 12.
9) Which of the following lists of numbers would accurately show the array after the first pass through the Selection
Sort algorithm?
a) 9, 4, 12, 2, 6, 8, 18
b) 4, 9, 12, 2, 6, 8, 18
c) 2, 4, 12, 9, 6, 8, 18
d) 2, 4, 6, 8, 9, 12, 18
e) 2, 4, 9, 12, 6, 8, 18
Answer: c. Explanation: On each successive pass of Selection Sort, the smallest of the unsorted values is found and
swapped with the current array index (where the current index starts at 0 and goes until the second to last position in the
array). On the first pass, the smallest element, 2, is swapped with index 0, so 2 and 9 swap places.
9 4 12 2 6 8 18
10) Which of the following lists of numbers would accurately show the array after the second pass of the Selection Sort
algorithm?
a) 9, 4, 12, 2, 6, 8, 18
b) 2, 4, 9, 6, 12, 8, 18
c) 2, 4, 12, 9, 6, 8, 18
d) 2, 4, 6, 8, 9, 12, 18
e) 2, 4, 12, 6, 8, 9, 18
Answer: c. Explanation: After one pass, the array would be 2, 4, 12, 9, 6, 8, 18. The second pass would look to swap
the item in array index 1 (4) with the smallest value after 2 (4). So, 4 would swap with 4 and the array would stay the
same as it was after the first pass.
11) Which of the following lists of numbers would accurately show the array after the fourth pass of the Selection Sort
algorithm?
a) 9, 4, 12, 2, 6, 8, 18
b) 2, 4, 6, 9, 12, 8, 18
c) 2, 4, 6, 8, 9, 12, 18
d) 2, 4, 6, 9, 8, 12, 18
e) 2, 4, 6, 8, 12, 9, 18
Answer: e. Explanation: The array would be sorted as follows: First pass: 2, 4, 12, 9, 6, 8, 18. Second pass: 2, 4, 12,
9, 6, 8, 18. Third pass: 2, 4, 6, 9, 12, 8, 18. Fourth pass: 2, 4, 6, 8, 12, 9, 18.
12) How many passes will it take in all for Selection Sort to sort this array?
a) 2
b) 4
c) 5
d) 6
e) 7
Answer: d. Explanation: The Selection Sort uses two for-loops where the outer loop iterates through each array index
except for the last one. So it makes a total of n 1 passes where n is the number of items in the array. Since this array
has 7 elements, the outer loop iterates 6 times, or requires 6 passes. You might notice that in fact this array is sorted
after only 5 passes, but the Selection Sort algorithm will still make 6 passes (even if the array had been sorted after only
1 pass, it would still make 6 passes!)
For questions 13 15, assume an int array, candy, stores the number of candy bars sold by a group of children where
candy[j] is the number of candy bars sold by child j. Assume there are 12 children in all.
13) What does the following code do?
int value1 = Keyboard.readInt( );
int value2 = Keyboard.readInt( );
bars[value1] += value2;
a) adds 1 to the number of bars sold by child value1 and child value2
b) adds 1 to the number of bars sold by child value1
c) adds value1 to the number of bars sold by child value2
d) adds value2 to the number of bars sold by child value1
e) inputs a new value for the number of bars sold by both child value1 and child value2
Answer: d. Explanation: bars[value1] is the number of bars sold by child value1, and += value2 adds to this value the
amount input for value2.
14) Which of the following code could be used to compute the total number of bars sold by the children?
a) for(int j=0; j<12; j++) sum+= candy[j];
b) for(int j=0; j<12; j++) candy[j] = sum;
c) for(int j=0; j<12; j++) sum = candy[j];
d) for(int j=0; j<12; j++) sum += [j];
e) for(int j=0; j<12; j++) [j] += sum;
Answer: a. Explanation: The code in a iterates through all 12 elements of candy, adding each value to sum. The
answer in b sets all 12 elements of candy equal to sum, the answer in c sets sum to be each element of candy, resulting
in sum = candy[11] and d and e have syntactically invalid code.
TB 62 Lewis/Loftus/Cocking: Chapter 6 Test Bank
15) What does the following method do?
public int question15( )
{
int value1 = 0;
int value2 = 0;
for(int j=0; j<12; j++)
if(candy[j] > value1)
{
value1 = candy[j];
value2 = j;
}
return value2;
}
a) It returns the total number of candy bars sold
b) It returns the total number of children who sold 0 candy bars
c) It returns the total number of children who sold more than 0 candy bars
d) It returns the number of candy bars sold by the child who sold the most candy bars
e) It returns the index of the child who sold the most candy bars
Answer: e. Explanation: The loop iterates through all 12 array elements. If a particular value of candy is found to be
larger than value1, then this new value is remembered in value1 along with the index of where it was found in value2.
As the loop continues, if a new candy value is found to be greater than the current value1, then it is remembered instead,
so the loop finds the maximum number of candy bars sold in value1 and the childs index who sold the most in value2.
Since value2 is returned, the code returns the index of the child who sold the most.
17) Both the Insertion Sort and the Selection Sort algorithms have efficiencies on the order of ____ where n is the
number of values in the array being sorted.
a) n
b) n * log n
c) n2
d) n3
e) Insertion sort has an efficiency of n and Selection Sort has an efficiency of n2
Answer: c. Explanation: Both sorting algorithms use two nested loops which both execute approximately n times
apiece, giving a complexity of n * n or n2 for both.
18) Consider the array declaration and instantiation: int[ ] arr = new int[5]; Which of the following is true about arr?
a) It stores 5 elements with legal indices between 1 and 5
b) It stores 5 elements with legal indices between 0 and 4
c) It stores 4 elements with legal indices between 1 and 4
d) It stores 6 elements with legal indices between 0 and 5
e) It stores 5 elements with legal indices between 0 and 5
Answer: b. Explanation: Arrays are instantiated with an int value representing their size, or the number of elements
that they can store. So, arr can store 5 elements. Further, all arrays start at index 0 and go to index size 1, so arr has
legal indices of 0 through 4.
19) If an int array is passed as a parameter to a method, which of the following would adequately define the parameter
list for the method header?
a) (int[ ])
b) (int a[ ])
c) (int[ ] a)
d) (int a)
e) (a[ ])
Answer: c. Explanation: The parameter is defined much as the variable is originally declared, as type parameter name.
Here, the type is int[ ] and the parameter is a.
20) If int[ ] x = new int[15]; and the statement x[-1] = 0; is executed, then which of the following Exceptions is thrown?
a) IndexOutOfBoundsException
b) ArrayIndexOutOfBoundsException
c) NegativeArraySizeException
d) NullPointException
e) ArithmeticException
Answer: b. Explanation: The array index is out of bounds as the array index can only be between 0 and 14. 1 is an
illegal index because it is out of bounds. One might expect the answer to be c, but the NegativeArraySizeException is
thrown if an array is being declared with a negative number of elements as in int[ ] x = new int[-5];
21) Assume that BankAccount is a predefined class and that the declaration BankAccount[ ] firstEmpireBank; has
already been performed. Then the following instruction reserves memory space for
firstEmpireBank = new BankAccount[1000];
a) a reference variable to the memory that stores all 1000 BankAccount entries
b) 1000 reference variables, each of which point to a single BankAccount entry
c) a single BankAccount entry
d) 1000 BankAccount entries
e) 1000 reference variables and 1000 BankAccount entries
Answer: b. Explanation: The declaration BankAccount[ ] firstEmpireBank; reserves memory space for
firstEmpireBank, which itself is a reference variable that points to the BankAccount[ ] object. The statement
firstEmpireBank = new BankAccount[1000]; instantiates the BankAccount[ ] object to be 1000 BankAccount objects.
This means that firstEmpireBank[0] and firstEmpireBank[1] and firstEmpireBank[999] are all now legal references,
each of which is a reference variable since each references a BankAccount object. So, the statement reserves memory
space for 1000 reference variables. Note that none of the 1000 BankAccount objects are yet instantiated, so no memory
has been set aside yet for any of the actual BankAccount objects.
22) The following code accomplishes which of the tasks written below? Assume list is an int array that stores positive
int values only.
foo = 0;
for(j=0; j<list.length; j++)
if (list[j] > foo) foo = list[j];
a) it stores the smallest value in list (the minimum) in foo
b) it stores the largest value in list (the maximum) in foo
c) it stores every value in list, one at a time, in foo, until the loop terminates
d) it counts the number of elements in list that are greater than foo
e) it counts the number of elements in list that are less than foo
Answer: b. Explanation: The condition in the if statement tests to see if the current element of list is greater than foo.
If so, it replaces foo. The end result is that every element in list is tested and foo stores the largest element up to that
point, so eventually, foo will be the largest value in the array list.
24) To initialize a String array names to store the three Strings Huey, Duey and Louie, you would do
a) String names = {Huey, Duey, Louie};
b) String[ ] names = {Huey, Duey, Louie};
c) String[ ] names = new String{Huey, Duey, Louie};
d) String names[3] = {Huey, Duey, Louie};
e) String names; names[0] = Huey; names[1] = Duey; names[2] = Louie;
Answer: b. Explanation: An array does not have to be instantiated with the reserved word new if it is instantiated with
the list of values it is to store. So, names = {Huey, Duey, Louie}; will create a String array of 3 elements with
the three values already initialized. Of the other answers, a does not specify that names is a String array, c should not
have the reserved word new, d should not have [3] after names and omits [ ] after String, and e does not instantiate the
array as String[3], and thus , all four of these other answers are syntactically invalid.
25) To declare a two-dimensional int array called threeD, which of the following would you use?
a) int[2] twoD;
b) int[ , ] twoD;
c) int[ ][ ] twoD;
d) int [ [ ] ] twoD;
e) int[ ] twoD[2];
Answer: c. Explanation: In Java, you can only declare one-dimensional arrays. To create a two-dimensional array,
you must declare it as an array of arrays. The proper notation is to declare the type of array using multiple [ ] marks in
succession, as in int[ ][ ] for a two-dimensional array.