Professional Documents
Culture Documents
Test Bank
Multiple Choice:
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
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.
2)
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)
TB 48
b) return 6
c) return 3
d) return 0
e) cause a run-time error
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.
6)
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.
TB 49
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.
11)
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.
TB 50
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).
TB 51
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.
19)
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.
22)
TB 52
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
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).
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);
24)
TB 53
Answer: False. Explanation: The statement first.equals(last); compares the two Strings referenced by first and last to
see if the Strings store the same character, while (first = = last) determines if first and last reference the same String, that
is, are aliases.
4) If String x = null; then x.length( ); returns the int 0.
Answer: False: Explanation: Since x is null, the instruction x.length( ); tries to pass the length( ) message to no object.
This cannot occur and so a NullPointerException is thrown.
5) Assume that the class Bird has a static method fly( ). If b is a Bird, then to invoke fly, you could do Bird.fly( );.
Answer: True. Explanation: Static methods are invoked through the class and not an object of the class. This is
because the static method is shared among all instances. So, Bird.fly( ); will invoke fly. It should be noted that fly can
also be invoked through b, so b.fly( ); will also work.
6) If an exception is thrown and is not caught anywhere in the program, then the program terminates.
Answer: True. Explanation: Exceptions are events of interest or are run-time situations that cannot be handled
normally without an exception handler. An exception is caught by an associated exception handler. If the exception is
thrown but not handled, then the program must terminate.
7) To implement the ActionListener interface, you must implement the method actionPerformed.
Answer: True. Explanation: All interfaces contain abstract methods that must be implemented by the programmer who
wishes to implement that interface. The abstract method of ActionListener is actionPerformed.
8) Any class can implement an interface, but no classes can implement more than a single interface.
Answer: False. Explanation: Classes can implement any number of interfaces, 0, 1, or more.
9) All objects implement Comparable.
Answer: False. Explanation: Comparable is an interface, and the class must define the compareTo method and
explicitly state that it implements Comparable to be considered an implementation of Comparable. Most classes do not
implement Comparable.
10) An object uses the this reserved word to refer to itself.
Answer: True. Explanation: The this reserved word refers to the currently executing object.
11) The add method is used to add components to a JPanel.
Answer: True. Explanation: Any GUI component can be added to a JPanel by using the add method, for example:
myPanel.add(myLabel).
12) Any variable can take on the value null to indicate that it has no value.
Answer: False. Explanation: Only variable that are object references can be null, which indicate that they do not refer
to any object. Variables of primitive types such as int and double cannot be assigned null.
13) Assuming name is a String variable, the test if (name != null && name.length() < 10) will cause a
NullPointerException if name is null.
Answer: False. Explanation: If name is null, the && will short-circuit and name.length() will not be evaluated.
(Otherwise, name.length() would cause an exception if name was null.)
14) The statements String a = hi; String b = a + ; cause a and b to be alises of each other.
Answer: False. Explanation: The string concatenation operator (+) creates a new String and assigns it to b, so a and b
are not aliases, they simply contain the same characters. (a + is adding the empty string to a, so b gets assigned hi.)
15) When an object is passed as a parameter, the formal and actual parameters become aliases of each other.
Answer: True. Explanation: Since a variable that is an object stores a reference to the object, the actual and formal
parameters refer to the same object and thus are aliases.
16) When an int is passed as a parameter, the formal and actual parameters become alises of each other.
TB 54
Answer: False. Explanation: That only happens with objects. When an int is passed, the value of the actual parameter
is copied into the formal parameter, and any changes made to the formal parameter do not affect the actual parameter.
17) Variables should never be static.
Answer: False. Explanation: Constants (final variables) are good candidates for static variables. Since their value
cannot change, there is no need to have a separate copy for each object.
18) If the Bar class has a static method named foo which takes no parameters, then it may be called with the statement.
Bar.foo();
Answer: True. Explanation: Static methods are called using the class name; no object need be created.
19) When a program attempts to divide by 0, a NullPointerException occurs.
Answer: False. Explanation: An ArithmeticException occurs.
20) Exceptions may only be thrown by the Java runtime system.
Answer: False. Explanation: The programmer may throw exceptions using a throw statement.
21) To throw a NullPointerException the programmer could use the following statement: throw NullPointerException;
Answer: False. Explanation: NullPointerException is a class and an object must be created and thrown. The following
statement could be used: throw new NullPointerException();
22) In an interface, the programmer has the choice of providing a method body or not.
Answer: False. Explanation: All the methods in an interface are abstract, so none of them may have method bodies.
23) A class that implements an interface must implement every method in the interface.
Answer: True. Explanation: If not, a syntax error will occur.
24) A class representing a car might implement the List interface.
Answer: False. Explanation: The List interface is implemented by classes that represent an ordered collection of
elements.
25) When designing a class to represent an object, you need to think about the objects state and behavior.
Answer: True. Explanation: Both state (represented by instance variables) and behavior (represented by methods)
should be considered when designing a class.
Free-form Questions:
1) Explain why aliases can cause trouble for programmers who are not aware of them.
Answer: Aliases arise in Java when variables refer to the same object. If one of those variables is used to pass a
message to the object in such a way that the object is changed, then the other variables now refer to a changed object.
Unless the programmer is careful, he/she may not realize that a change has been made to the object. Consider a class
Foo that has an instance data x and a method incr that adds one to x. Assume a and b are both of type Foo, where as x
is 10. Consider the following two instructions: b = a; b.incr( ); The result is that a/bs value x is now 11, but if the
programmer is not aware of the aliasing, then he/she might expect as x to still be 10.
2) Explain what a NullPointerException is and how it can arise.
Answer: A NullPointerException is an exception that indicates that an operation was attempted on some object that is
equal to null. For instance, ChessPiece c; declares c to refer to a ChessPiece, but c has not yet been instantiated, so any
message passed to c at this point will cause a NullPointerException.
3) Consider the condition (x = = y). How is this handled if x and y are primitive types? How is this handled if x and y
are objects?
Answer: If x and y are primitive types, then the values stored in x and y are compared and true is returned if the two
values are equal. If x and y are objects, then the object that x and y reference are compared. If they are the same object,
it returns true, otherwise it returns false.
TB 55
TB 56
9) To implement Comparable for the ChessPiece class, the current ChessPieces type is compared to a ChessPiece
passed as a parameter. The method should return 0 if the types are equal, -1 if this pieces type is a lesser piece
than the parameters type, and 1 if this pieces type is a greater piece than the parameters type. 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.
Write the proper method to implement Comparable for this class.
Answer:
public int compareTo(ChessPiece a)
{
if(this.type.equals(a.getType( )) | |
(this.type.equals(Knight) && a.getType( ).equals(Bishop)) | |
(this.type.equals(Bishop) && a.getType( ).equals(Knight))) return 0;
else if (this.type.equals(King)) return 1;
else if (a.getType( ).equals(King)) return 1;
else if (this.type.equals(Queen)) return 1;
else if (a.getType( ).equals(Queen)) return 1;
else if (this.type.equals(Rook)) return 1;
else if (a.getType( ).equals(Rook)) return 1;
else if (this.type.equals(Knight) | | (this.type.equals(Bishop)) return 1;
else if (a.getType( ).equals(Knight) | | (a.getType( ).equals(Bishop)) return 1;
}
10) Write a static method that is passed two ChessPieces and determines if the two pieces are owned by the same
player. It should return true or false.
Answer:
public static boolean samePlayer(ChessPiece p1, ChessPiece p2)
{
return (p1.getPlayer( ) = = p2.getPlayer( ));
}
For questions 11-12, consider a class that creates a JFrame which will input from the user their age and output a
message about their age. The JFrame has the following GUI components:
JFrame frame;
JPanel panel;
JLabel inputLabel, outputLabel, messageLabel;
JTextField ageField;
11) Write the code to define the JFrame which will have the components placed into the JPanel first where the JPanel
will have the inputLabel and ageField side by side and the outputLabel and messageLabel beneath them. Do not
worry about making the JFrame do anything (i.e. dont implement an ActionListener).
Answer:
frame = new JFrame ("Age GUI");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
inputLabel = new JLabel ("Enter your age:");
outputLabel = new JLabel ("Here is a message about your age");
messageLabel = new JLabel ("");
ageField = new JTextField (3);
panel = new JPanel();
panel.setPreferredSize (new Dimension(2, 2));
panel.setBackground (Color.white);
panel.add (inputLabel);
panel.add (ageField);
panel.add (outputLabel);
panel.add (messageLabel);
frame.getContentPane().add (panel);
frame.pack();
TB 57
frame.show();
12) Write an actionPerformed method that will take the age from the ageField and place one of the following Strings in
the outputLabel JLabel appropriately:
If age is between 0 and 17, output child, do not work
If between 18 and 60, output adult, get a job
and if above 60, output adult, time to retire
Answer:
public void actionPerformed(ActionEvent ae)
{
int age = Integer.parseInt(ageField.getText( ));
if(age >= 0 && age <= 17) outputLabel = new JLabel(child, do not work);
else if (age > 17 && age <= 60) outputLabel = new JLabel(adult, get a job);
else if (age > 60) outputLabel = new JLabel(adult, time to retire);
}
13) Identify the possible classes in the following partial program description:
The program will be used at a vehicle inspection station. Each vehicle that enters the station will have an inspector
assigned to it. The vehicle must pass a series of tests. A record of each customer, their vehicle, and the test results
should be kept.
Answer:
(vehicle inspection) station
vehicle
inspector
customer
test
14) Explain or provide an example showing how each of the following Exceptions could arise.
a) ArithmeticException
b) NullPointerException
c) IndexOutOfBoundsException
Answer:
a) An arithmetic operation could not take place because of an illegal action such as division by zero or square root
of a negative number
b) An object was not instantiated (it had the value null) before a message was passed to it
c) A numeric parameter used as an index into an object such a String (or an array) was out of range, such as
charAt(-1)
15) Define an interface class that contains two int constants, X = 5 and Y = 10 and one int method called doSomething
which receives no parameters. Call your interface class XYClass
Answer:
public interface XYClass
{
public static final int X = 5;
public static final int Y = 10;
public int doSomething( );
}