. Assume MIN_FACES is an int equal to 4.
public Die( ) public Die(int faces)
{ {
numFaces = 6; if(faces < MIN_FACES) numFaces = 6;
faceValue = 1; else numFaces = faces;
} faceValue = 1;
}
20) The instruction Die d = new Die(10, 0); results in
a) The Die d having numFaces = 6 and faceValue = 1
b) The Die d having numFaces = 10 and faceValue = 1
c) The Die d having numFaces = 10 and faceValue = 10
d) The Die d having numFaces = 6 and faceValue = 10
e) A syntax error
. Assume MIN_FACES is an int equal to 4.
public Die( ) public Die(int faces)
{ {
numFaces = 6; if(faces < MIN_FACES) numFaces = 6;
faceValue = 1; else numFaces = faces;
} faceValue = 1;
}
20) The instruction Die d = new Die(10, 0); results in
a) The Die d having numFaces = 6 and faceValue = 1
b) The Die d having numFaces = 10 and faceValue = 1
c) The Die d having numFaces = 10 and faceValue = 10
d) The Die d having numFaces = 6 and faceValue = 10
e) A syntax error
Front
Answer: e. Explanation: The Die class has two constructors, one that receives no parameters and one that receives a
single int parameter. The instruction above calls the Die constructor with 2 int parameters. Since no constructor
matches this number of parameters exists, a syntax error occurs
Back
12) A constructor is a method that gets called automatically whenever an object is created, for example with the new
operator.
Front
Answer: True. The constructor is used to initialize an object and it gets called whenever a new object is created from a
particular class.
Back
12) An example of passing a message to a String where the message has a String parameter occurs in which of the
following messages?
a) length
b) substring
c) equals
d) toUpperCase
e) none of the above, it is not possible to pass a String as a parameter in a message to a String
Front
Answer: c. Explanation: The length and toUpperCase messages do not have parameters and substring has two int
parameters. For equals, a String must be passed as a parameter so that the String receiving the message can be
compared to the String passed as a parameter.
Back
21) If the instruction Swapper s = new Swapper(0, "hello", 0); is executed followed by s.toString( ); what value is
returned from s.toString( )?
a) "hello"
b) "hello00"
c) "00"
d) "0"
e) 0
Front
Answer: c. Explanation: The toString method compares x and z, and if x < y it returns the String y. In this case, x ==
z, so the else clause is executed, and the String of "" + x + z is returned. This is the String "00".
Back
11) A class may contain methods but not variable declarations.
Front
Answer: False. A class may contain both methods and variable declarations.
Back
25) An object may be made up of other objects
Front
Answer: True. An aggregate object is an object that has other objects as instance data.
Back
25) Consider a method defined with the header: public void doublefoo(double x). Which of the following method
calls is legal?
a) doublefoo(0);
b) doublefoo(0.555);
c) doublefoo(0.1 + 0.2);
d) doublefoo(0.1, 0.2);
e) all of the above are legal except for d
Front
Answer: e. Explanation: In the case of a, the value 0 (an int) is widened to a double. In the case of c, the addition is
performed yielding 0.3 and then doublefoo is called. The parameter list in d is illegal since it contains two double
parameters instead of 1.
Back
For questions 13-15, use the following class definition
import java.text.DecimalFormat;
public class Student
{
private String name;
private String major;
private double gpa;
private int hours;
public Student(String newName, String newMajor, double newGPA, int newHours)
{
name = newName;
major = newMajor;
gpa = newGPA;
hours = newHours;
}
public String toString( )
{
DecimalFormat df = new DecimalFormat("xxxx"); // xxxx needs to be replaced
return name + " " + major + " " + df.format(gpa) + " " + hours
}
}
14) Assume that another method has been defined that will compute and return the student's class rank (Freshman,
Sophomore, etc). It is defined as:
public String getClassRank( )
TB 38 Lewis/Loftus/Cocking: Chapter 4 Test Bank
Given that s1 is a student, which of the following would properly be used to get s1's class rank?
a) s1 = getClassRank( );
b) s1.toString( );
c) s1.getHours( );
d) s1.getClassRank( );
e) getClassRank(s1);
Front
Answer: d. Explanation: To call a method of an object requires passing that object a message which is the same as the
method name, as in object.methodname(parameters). In this situation, the object is s1, the method is getClassRank, and
this method expects no parameters. Answers a and e are syntactically illegal while answer b returns information about
the Student but not his/her class rank, and there is no "getHours" method so c is also syntactically illegal
Back
3) All Java classes must contain a main method which is the first method executed when the Java class is called upon.
Front
Answer: False. Explanation: Only the driver program requires a main method. The driver program is the one that is
first executed in any Java program (except for Applets), but it may call upon other classes as needed, and these other
classes do not need main methods
Back
. Assume MIN_FACES is an int equal to 4.
public Die( ) public Die(int faces)
{ {
numFaces = 6; if(faces < MIN_FACES) numFaces = 6;
faceValue = 1; else numFaces = faces;
} faceValue = 1;
}
19) The instruction Die d = new Die(10); results in
a) The Die d having numFaces = 6 and faceValue = 1
b) The Die d having numFaces = 10 and faceValue = 1
c) The Die d having numFaces = 10 and faceValue = 10
d) The Die d having numFaces = 6 and faceValue = 10
e) A syntax error
Front
Answer: b. Explanation: Since an int parameter is passed to the constructor, the second constructor is executed, which
sets numFaces = 10 (since numFaces >= MIN_FACES) and faceValue = 1.
Back
19) The number and types of the actual parameters must match the number and types of the formal parameters
Front
Answer: True. The names of the corresponding actual and formal parameters may be different but the number and
types of the parameters must match.
Back
6) A method defined in a class can access the class' instance data without needing to pass them as parameters or
declare them as local variables.
Front
Answer: True. Explanation: The instance data are globally available to all of the class' methods and therefore the
methods do not need to receive them as parameters or declare them locally. If variables of the same name as instance
data were declared locally inside a method then the instance data would be "hidden" in that method because the
references would be to the local variables.
Back
14) A constructor must always return an int
Front
Answer: False. In fact, a constructor cannot return anything. It has no return value, not even void. When a constructor
is written, no return value should be listed.
Back
7) The interface of a class is based on those data instances and methods that are declared public.
Front
Answer: True. Explanation: The interface is how an outside agent interacts with the object. Interaction is only
available through those items declared to be public in the class' definition.
Back
8) Defining formal parameters requires including each parameters type
Front
Answer: True. Explanation: In order for the compiler to check to see if a method call is correct, the compiler needs to
know the types for the parameters being passed. Therefore, all formal parameters (those defined in the method header)
must include their type. This is one element that makes Java a Strongly Typed language.
Back
2) The relationship between a class and an object is best described as
a) classes are instances of objects
b) objects are instances of classes
c) objects and classes are the same thing
d) classes are programs while objects are variables
e) objects are the instance data of classes
Front
Answer: b. Classes are definitions of program entities that represent classes of things/entities in the world. Class
definitions include instance data and methods. To use a class, it is instantiated. These instances are known as objects.
So, objects are instances of classes. Program code directly interacts with objects, not classes.
Back
16) The methods in a class should always be made public so that those outside the class can use them
Front
Answer: False. Methods that need to be available for use outside a class should be made public, but methods that will
only be used inside the class should be made private.
Back
10) Having multiple class methods of the same name where each method has a different number of or type of
parameters is known as
a) encapsulation
b) information hiding
c) tokenizing
d) importing
e) method overloading
Front
Answer: e. Explanation: When methods share the same name, they are said to be overloaded. The number and type of
parameters passed in the message provides the information by which the proper method is called.
Back
13) A constructor must have the same name as its class.
Front
Answer: True. A constructor is required to have the same name as the class.
Back
23) If we have Swapper r = new Swapper (5, "no", 10); then r.swap( ); returns which of the following?
a) nothing
b) "no"
c) "no510"
d) "510"
e) "15"
Front
Answer: b. Explanation: The swap method swaps the values of x and z (thus x becomes 10 and z becomes 5) and
returns the value of y, which is "no" for r.
Back
10) While multiple objects of the same class can exist, there is only one version of the class
Front
Answer: True. Explanation: A class is an abstraction, that is, it exists as a definition, but not as a physical instance.
Physical instances are created when an object is instantiated using new. Therefore, there can be many objects of type
String, but only one String class.
Back
9) Every class definition must include a constructor.
Front
Answer: False. Explanation: Java allows classes to be defined without constructors, however, there is a default
constructor that is used in such a case.
Back
For questions 13-15, use the following class definition
import java.text.DecimalFormat;
public class Student
{
private String name;
private String major;
private double gpa;
private int hours;
public Student(String newName, String newMajor, double newGPA, int newHours)
{
name = newName;
major = newMajor;
gpa = newGPA;
hours = newHours;
}
public String toString( )
{
DecimalFormat df = new DecimalFormat("xxxx"); // xxxx needs to be replaced
return name + " " + major + " " + df.format(gpa) + " " + hours
}
}
15) Another method that might be desired is one that updates the Student's number of credit hours. This method will
receive a number of credit hours and add these to the Student's current hours. Which of the following methods
would accomplish this?
a) public int updateHours( )
{
return hours;
}
b) public void updateHours( )
{
hours++;
}
c) public updateHours(int moreHours)
{
hours += moreHours;
}
d) public void updateHours(int moreHours)
{
hours += moreHours;
}
e) public int updateHours(int moreHours)
{
return hours + moreHours;
}
Front
Answer: d. Explanation: This method will receive the number of new hours and add this to the current hours. The
method in d is the only one to do this appropriately. Answer c is syntactically invalid since it does not list a return type.
The answer in e returns the new hours, but does not reset hours appropriately.
The Coin class, as defined in Chapter 4, consists of a constructor, and methods flip, isHeads and toString. The method
isHeads returns true if the last flip was a Heads, and false if the last flip was a Tails. The toString method returns a
String equal to "Heads" or "Tails" depending on the result of the last flip. Using this information, answer questions 16
- 17
Back
9) A class' constructor usually defines
a) how an object is initialized
b) how an object is interfaced
c) the number of instance data in the class
d) the number of methods in the class
e) if the instance data are accessible outside of the object directly
Front
Answer: a. Explanation: The constructor should be used to "construct" the object, that is, to set up the initial values of
the instance data. This is not essential, but is typically done. The interface of an object is dictated by the visibility
modifiers used on the instance data and methods.
Back
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
Front
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.
Back
4) Java methods can return more than one item if they are modified with the reserved word continue, as in public
continue int foo( ) { ... }
Front
Answer: False. Explanation: All Java methods return a single item, whether it is a primitive data type an object, or void.
The reserved word continue is used to exit the remainder of a loop and test the condition again.
Back
16) A set of code has already instantiated c to be a Coin and has input a String guess, from the user asking whether the
user guesses that a coin flip will result in "Heads" or "Tails". Which of the following sets of code will perform the
coin flip and see if the user's guess was right or wrong?
a) c.flip( );
if(c.isHeads( ).equals(guess)) System.out.println("User is correct");
b) if(c.flip( ).equals(guess)) System.out.println("User is correct");
c) if(c.isHeads( ).equals(guess)) System.out.println("User is correct");
Lewis/Loftus/Cocking: Chapter 4 Test Bank TB 39
d) c.flip( );
if(c.toString( ).equals(guess)) System.out.println("User is correct");
e) c.flip( ).toString( );
if(c.equals(guess)) System.out.println("User is correct");
Front
Answer: d. Explanation: c.flip( ) must be performed first to get a Coin flip. Next, the user's guess is compared against
the value of the Coin's flip. The Coin c stores the result as an int and the user's guess is a String. Using getFace( )
returns the int value but using the toString method will return the String "Heads" or "Tails". So, the code compares
c.toString( ) with the user's guess using the String method equals.
Back
24) Consider a method defined with the header: public void foo(int a, int b). Which of the following method calls is
legal?
a) foo(0, 0.1);
b) foo(0 / 1, 2 * 3);
c) foo(0);
d) foo( );
e) foo(1 + 2, 3 * 0.1);
Front
Answer: b. Explanation: The only legal method call is one that passes two int parameters. In the case of answer b, 0 /
1 is an int division (equal to 0) and 2 * 3 is an int multiplication. So this is legal. The answers for a and e contain two
parameters, but the second of each is a double. The answers for c and d have the wrong number of parameters.
Back
17) What does the following code compute?
int num = 0;
for(int j = 0; j < 1000; j++)
{
c.flip( );
if(c.isHeads()) num++;
}
double value = (double) num / 1000;
1) the number of Heads flipped out of 1000 flips
2) the number of Heads flipped in a row out of 1000 flips
3) the percentage of heads flipped out of 1000 flips
4) the percentage of times neither Heads nor Tails were flipped out of 1000 flips
5) nothing at all
Front
Answer: c. Explanation: The code iterates 1000 times, flipping the Coin and testing to see if this flip was a 0
("Heads") or 1 ("Tails"). The variable num counts the number of Heads and the variable value is then the percentage of
Heads over 1000
Back
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
Front
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.
Back
1) The behavior of an object is defined by the object's
a) instance data
b) constructor
c) visibility modifiers
d) methods
e) all of the above
Front
Answer: d. Explanation: The methods dictate how the object reacts when it is passed messages. Each message is
implemented as a method, and the method is the code that executes when the message is passed. The constructor is one
of these methods but all of the methods combine dictate the behavior. The visibility modifiers do impact the object's
performance indirectly.
Back
15) A class's instance data are the variables declared in the main method.
Front
Answer: False. A class's instance data are declared in the class but not inside any method. Variables declared in a
method are local to that method and can only be used in that method. Furthermore, every class need not have a
main method.
Back
17) The body of a method may be empty.
Front
Answer: True. The method body may have 0 or more instructions, so it could have 0. An empty method body is simply
{ } with no statements in between.
Back
24) Method decomposition is the process of creating overloaded versions of a method that do the same thing, but
operate on different data types.
Front
Answer: False. Method decomposition is breaking a complicated method into simpler methods to create a more
understandable design
Back
6) If a method does not have a return statement, then
a) it will produce a syntax error when compiled
b) it must be a void method
c) it can not be called from outside the class that defined the method
d) it must be defined to be a public method
e) it must be an int, double, or String method
Front
Answer: b. Explanation: All methods are implied to return something and therefore there must be a return statement.
However, if the programmer wishes to write a method that does not return anything, and therefore does not need a
return statement, then it must be a void method (a method whose header has "void" as its return type).
Back
21) If a method takes a double as a parameter, you could pass it an int as the actual parameter
Front
Answer: True. Since converting from an int to a double is a widening conversion, it is done automatically, so there
would be no error.
Back
23) The println method on System.out is overloaded
Front
Answer: True. The println method includes versions that take a String, int, double, char, and boolean.
Back
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
Front
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.
Back
11) Instance data for a Java class
a) are limited to primitive types (e.g., int, double, char)
b) are limited to Strings
c) are limited to objects(e.g., Strings, classes defined by other programmers)
d) may be primitive types or objects, but objects must be defined to be private
e) may be primitive types or objects
Front
Answer: e. Explanation: The instance data are the entities that make up the class and may be any type available
whether primitive or object, and may be public or private. By using objects as instance data, it permits the class to be
built upon other classes. This relationship where a class has instance data that are other classes is known as a has-a
relationship.
Back
18) The return statement must be followed a single variable that contains the value to be returned.
Front
Answer: False. The return statement may be following by any expression whose type is the same as the declared return
type in the method header. For example, return x*y+6; is a valid return statement. The statement return; is also
valid for a method that does not return anything (void).
Back
18) In the Rational class, defined in chapter 4, the methods reduce and gcd are declared to be private. Why?
a) Because they will never be used
b) Because they will only be called from methods inside of Rational
c) Because they will only be called from the constructor of Rational
d) Because they do not use any of Rational's instance data
e) Because it is a typo and they should be declared as public
Front
Answer: b. Explanation: All items of a class that are declared to be private are only accessible to entities within that
class, whether they are instance data or methods. In this case, since these two methods are only called from other
methods (including the constructor) of Rational, they are declared private to promote information hiding to a greater
degree. Note that answer c is not a correct answer because the reduce method calls the gcd method, so one of the
methods is called from a method other than the constructor.
Back
20) The different versions of an overloaded method are differentiated by their signatures
Front
Answer: True. A method's signature include the number, types, and order of its parameters. With overloaded methods,
the name is the same, but the the methods must differ in their parameters.
Back
2) Formal parameters are those that appear in the method call and actual parameters are those that appear in the
method header
Front
Answer: False. Explanation: The question has the two definitions reversed. Formal parameters are those that appear
in the method header, actual parameters are the parameters in the method call (those being passed to the method).
Back
22) Which of the following criticisms is valid about the Swapper class?
a) The instance data x is visible outside of Swapper
b) The instance data y is visible outside of Swapper
c) The instance data z is visible outside of Swapper
d) All 3 instance data are visible outside of Swapper
e) None of the methods are visible outside of Swapper
Front
Answer: c. Explanation: We would expect none of the instance data to be visible outside of the class, so they should
all be declared as "private" whereas we would expect the methods that make up the interface to be visible outside of the
class, so they should all be declared as "public". We see that z is declared "public" instead of "private".
Back
22) A method defined without a return statement will cause a compile error.
Front
Answer: False. If a method is declared to return void then it doesn't need a return statement. However, if a method is
declared to return a type other than void, then it must have a return statement.
Back
1) Java methods can return only primitive types (int, double, boolean, etc).
Front
Answer: False. Explanation: Java methods can also return objects, such as a String.
Back
5) The following method header definition will result in a syntax error: public void aMethod( );
Front
Answer: True. Explanation: The reason for the syntax error is because it ends with a ";" symbol. It instead needs to be
followed by { } with 0 or more instructions inside of the brackets. An abstract method will end with a ";" but this
header does not define an abstract method.
Back
For questions 13-15, use the following class definition
import java.text.DecimalFormat;
public class Student
{
private String name;
private String major;
private double gpa;
private int hours;
public Student(String newName, String newMajor, double newGPA, int newHours)
{
name = newName;
major = newMajor;
gpa = newGPA;
hours = newHours;
}
public String toString( )
{
DecimalFormat df = new DecimalFormat("xxxx"); // xxxx needs to be replaced
return name + " " + major + " " + df.format(gpa) + " " + hours
}
}
13) Which of the following could be used to instantiate a new Student s1?
a) Student s1 = new Student( );
b) s1 = new Student( );
c) Student s1 = new Student("Jane Doe", "Computer Science", 3.333, 33);
d) new Student s1 = ("Jane Doe", "Computer Science", 3.333, 33);
e) new Student(s1);
Front
Answer: c. Explanation: To instantiate a class, the object is assigned the value returned by calling the constructor
preceded by the reserved word new, as in new Student( ). The constructor might require parameters, and for Student,
the parameters must be are two String values, a double, followed by an int.
Back
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
Front
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.
Back
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
Front
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.
Back
Section 2
(50 cards)
2) The result of x.length( ) + y.length( ) is
a) 0
b) 5
c) 6
d) 10
e) a thrown exception
Front
Answer: e. Explanation: The statement y.length( ) results in a thrown NullPointException because it is not possible to
pass a message to an object that is not currently instantiated (equal to null).
Back
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
Front
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");
Back
4) If the operation y = x; is performed, then the result of (x = = y) is
a) true
b) false
c) x being set to the value null while y retains the value "Hello"
d) y being set to the value null while x retains the value "Hello"
e) x being set to y, which it is already since y = x; was already performed
Front
Answer: a. Explanation: When y = x; was performed, the two variables are now aliases, that is, they reference the
same thing in memory. So, (x = = y) is now true.
Back
22) An exception can produce a "call stack trace" which lists
a) the active methods in the order that they were invoked
b) the active methods in the opposite order that they were invoked
c) the values of all instance data of the object where the exception was raised
d) the values of all instance data of the object where the exception was raised and all local variables and
parameters of the method where the exception was raised
e) the name of the exception thrown
Front
Answer: b. Explanation: The call stack trace provides the names of the methods as stored on the run-time stack. The
method names are removed from the stack in the opposite order that they were placed, that is, the earliest method was
placed there first, the next method second, and so forth so that the most recently invoked method is the last item on the
stack, so it is the first one removed. The stack trace then displays all active methods in the opposite order that they were
called (most recent first).
Back
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
Front
Answer: c. Explanation: Java array indices start at 0, so values[3] is really the fourth array element, which is 2.
Back
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."
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;
Front
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 parameter's 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.
Back
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.
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;
Front
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.
Back
19) If s is a String, and s = "no"; is performed, then s
a) stores the String "no"
b) references the memory location where "no" is stored
c) stores the characters 'n', 'o'
d) stores an int value that represents the two characters
e) stores the character 'n' and a reference to the memory location where the next character, 'o' is stored
Front
Answer: b. Explanation: Strings are objects and all objects in Java are referenced by the variable declared to be an
object. That is, the variable represents the memory location where the object is stored. So, s does not directly store
"no" or 'n', 'o', but instead stores a memory location where "no" is stored.
Back
For questions 1-4, assume x and y are String variables with x = "Hello" and y = null.
1) The result of (x = = y) is
a) true
b) false
c) a syntax error
d) a run-time error
e) x being set to the value null
Front
Answer: b. Explanation: x is a String instantiated to the value "Hello" and y is a String that has not yet been
instantiated, so they are not the same String. (x = = y) is a condition, testing to see if x and y are the same String (that
is, x and y reference the same item in memory), which they don't, so the result is false.
Back
25) A listener is an object that
a) implements any type of interface
b) is used to accept any form of input
c) is an inner class to a class that has abstract methods
d) waits for some action from the user
e) uses the InputStreamReader class
Front
Answer: d. Explanation: The listener "listens" for a user action such as a mouse motion, a key entry or an activation of
a GUI object (like a button) and then responds appropriately. Listeners allow us to write programs that interact with the
user whenever the user performs an operation as opposed to merely seeking input from the user at pre-specified times.
Back
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
Front
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];
Back
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
Front
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.
Back
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
Front
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 object's 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.
Back
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;
7) If the instruction z.set2(y.get1( )); is executed, 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) the statement causes a run-time error
Front
Answer: a. Explanation: Since y=z; was performed previously, y and z are aliases, so that a change to one results in a
change to the other. The statement z.set2(y.get1( )); is essentially the same as z.set2(z.get1( )); or y.set2(y.get1( )); and
in any case, it sets the second value to equal the first for the object which is referenced by both y and z.
Back
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
Front
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.
Back
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
Front
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);.
Back
24) JOptionPane is a class that provides GUI
a) dialog boxes
b) buttons
c) output fields
d) panels and frames
e) all of the above
Front
Answer: a. Explanation: the JOptionPane class contains three formats of dialog boxes, an input dialog box that
prompts the user and inputs String text, a message dialog box that outputs a message, and a confirm box that prompts
the user and accepts a Yes or No answer.
Back
11) Static methods cannot
a) reference instance data
b) reference non-static instance data
c) reference other objects
d) invoke other static methods
e) invoke non-static methods
Front
Answer: b. Explanation: A static method is a method that is part of the class itself, not an instantiated object, and
therefore the static method is shared among all instantiated objects of the class. Since the static method is shared, it
cannot access non-static instance data because all non-static instance data are specific to instantiated objects. A static
method can access static instance data because, like the method, the instance data is shared among all objects of the
class. A static method can also access parameters passed to it.
Back
For questions 1-4, assume values is an int array that is currently filled to capacity, with the following values:
2) What is the value of values.length?
a) 0
b) 5
c) 6
d) 7
e) 18
Front
Answer: d. Explanation: The length operator for an array returns the size of the array. The above picture shows that
that values stores 7 elements and since it is full, the size of values is 7.
Back
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.
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
Front
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 child's index who sold the most in value2.
Since value2 is returned, the code returns the index of the child who sold the most.
Back
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
Front
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
Back
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
Front
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.
Back
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
Front
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.
Back
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
Front
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.
Back
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
Front
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.
Back
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;
6) The statement y.get2( ); will
a) return 5
b) return 6
c) return 3
d) return 0
e) cause a run-time error
Front
Answer: a. Explanation: The statement y = z; causes y and z to be aliases where y.get2( ); returns the same value as
z.get2( );. Since z.set2(y.get1( )); was performed previously, z and y's second value is 5.
Back
For questions 1-4, assume values is an int array that is currently filled to capacity, with the following values:
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.length-1;j++) values[j]++;
e) for(j=1;j<values.length-1;j++) values[j]++;
Front
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.length-1, 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 <=.
Back
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
Front
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.
Back
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
Front
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!)
Back
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)
Front
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
Back
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[ ])
Front
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.
Back
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
Front
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.
Back
16) We compare sorting algorithms by examining
a) the number of instructions executed by the sorting algorithm
b) the number of instructions in the algorithm itself (its length)
c) the types of loops used in the sorting algorithm
d) the amount of memory space required by the algorithm
e) whether the resulting array is completely sorted or only partially sorted
Front
Answer: a. Explanation: Different sorting algorithms require a different number of instructions when executing. The
Selection Sort for instance usually requires more instructions than the Insertion Sort. So, we compare sorting
algorithms by the number of instructions that each takes to execute to sort the array. We might count the maximum
number of instructions that a sorting algorithm will execute in the worst case, or the minimum number in the best case,
or count on average the number of instructions executed. If two sorting algorithms require roughly the same number of
instructions to sort an array, then we might also examine the amount of memory space required.
Back
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
Front
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.
Back
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
Front
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.
Back
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
Front
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.
Back
3) If the operation y = "Hello"; is performed, then the result of (x = = y) is
a) true
b) false
c) x and y becoming aliases
d) x being set to the value null
e) a run-time error
Front
Answer: b. Explanation: While x and y now store the same value, they are not the same String, that is, x and y
reference different objects in memory, so the result of the condition (x = = y) is false.
Back
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)
Front
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).
Back
6) In Java, arrays are
a) primitive data types
b) objects
c) interfaces
d) primitive data types if the type stored in the array is a primitive data type and objects if the type stored
in the array is an object
e) Strings
Front
Answer: b. Explanation: In Java, arrays are implemented as objects. The variable is a reference variable to the block
of memory that stores the entire array. However, arrays are accessed using the notation name[index] rather than by
message passing.
Back
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";
Front
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.
Back
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
Front
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.
Back
For questions 12 - 13, use the following class definition:
public class StaticExample
{
private static int x;
public StaticExample (int y)
{
x = y;
}
public int incr( )
{
x++;
return x;
}
}
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
Front
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.
Back
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
Front
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.
Back
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;
5) The statement z.get2( ); will
a) return 5
b) return 6
c) return 3
d) return 0
e) cause a run-time error
Front
Answer: a. Explanation: The statement y.get1( ) returns the value 5, and therefore the statement z.set2(y.get1( )) sets
the second value of z to be 5, so that z.get2( ) returns 5.
Back
For questions 1-4, assume values is an int array that is currently filled to capacity, with the following values:
4) The statement System.out.println(values[7]); will
a) output 7
b) output 18
c) output nothing
d) cause an ArrayOutOfBoundsException to be thrown
e) cause a syntax error
Front
Answer: d. Explanation: The array has 7 values, but these are indexed values[0] to values[6]. Since values[7] is
beyond the bounds of the array, values[7] causes an ArrayOutOfBoundsException to be thrown.
Back
7) The "off-by-one" error associated with arrays arises because
a) the first array index is 0 and programmers may start at index 1, or may use a loop that goes one index
too far
b) the last array index is at length + 1 and loops may only iterate to length, missing one
c) the last array element ends at length - 1 and loops may go one too far
d) programmers write a loop that goes from 0 to length - 1 whereas the array actually goes from 1 to
length
e) none of the above, the "off-by-one" error has nothing to do with arrays
Front
Answer: a. Explanation: The array is initialized as = new type[x] where x is the size of the array. However, the array
has legal indices of 0 to x - 1 and so, programmers are often off-by-one because programmers will write code to try to
access indices 1 to x.
Back
23) If x is a char, and values is an int array, then values[x]
a) causes a syntax error
b) causes an Exception to be thrown
c) casts x as an int based on x's position in the alphabet (for instance, if x is 'a' then it uses 0 and if x is
'z' then it uses 25)
d) casts x as an int based on x's Unicode value (for instance, if x is 'a' then it uses 97 and if x is 'z' then
it uses 122)
e) casts x as an int based on the digit that is stored in x (for instance, if x is '3' it uses 3) but throws an
exception if x does not store a digit
Front
Answer: d. Explanation: An array index must be an int value, so normally values[x] would cause a syntax error if x
were not an int, but the Java compiler will automatically cast x to be an int if it can be cast. Characters are cast as ints
by converting the char value to its equivalent Unicode value. So, if x is 'a', it is cast as the int 97 instead and so
values[x] accesses values[97].
Back
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
Front
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.
Back
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];
Front
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.
Back
For questions 12 - 13, use the following class definition:
public class StaticExample
{
private static int x;
public StaticExample (int y)
{
x = y;
}
public int incr( )
{
x++;
return x;
}
}
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
Front
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.