You are on page 1of 11

Chapter 5: Enhancing Classes

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)

The result of x.length( ) + y.length( ) is


a) 0
b) 5
c) 6
d) 10
e) a thrown exception
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).
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
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.
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
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.

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
TB 47

TB 48

Lewis/Loftus/Cocking, 2/e: Chapter 5 Test Bank

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)

The statement y.get2( ); will


a) return 5
b) return 6
c) return 3
d) return 0
e) cause a run-time error
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.
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
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.
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.

Lewis/Loftus/Cocking, 2/e: Chapter 5 Test Bank

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)

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
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.
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
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.

TB 50

Lewis/Loftus/Cocking, 2/e: Chapter 5 Test Bank

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).

Lewis/Loftus/Cocking, 2/e: Chapter 5 Test Bank

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)

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
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.
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.
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

TB 52

Lewis/Loftus/Cocking, 2/e: Chapter 5 Test Bank

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)

JOptionPane is a class that provides GUI


a) dialog boxes
b) buttons
c) output fields
d) panels and frames
e) all of the above
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.
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
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.
True/False Questions:

1) Several variables can reference the same object.


Answer: True. Explanation: When variables reference the same object, they are known as aliases. As an example,
consider the following code. In it, x, y and z all reference the same String (they do not just equal the same value, they
are all the same String) and so they are all aliases of each other.
String x = hi;
String y = x;
String z = y;
2) The = = operator performs differently depending on whether the variables being compared are primitives types or
objects.
Answer: True. Explanation: If two objects are being compared using = =, then the comparison returns true if the two
objects are aliases (the same object). But if two primitive data types are being compared, then the comparison returns
true if the two variables store the same value.
3) If first and last are both String variables, then first.equals(last); does the same thing as (first = = last).

Lewis/Loftus/Cocking, 2/e: Chapter 5 Test Bank

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

Lewis/Loftus/Cocking, 2/e: Chapter 5 Test Bank

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.

Lewis/Loftus/Cocking, 2/e: Chapter 5 Test Bank

TB 55

4) Provide a reason why an instance data would be declared static.


Answer: If an instance data is to be shared among all objects of the class, the instance data would be static. As an
example, an instance data that counts the number of times something has happened across all objects of the class would
be made static. If we are writing a chess game and have a ChessPiece class that includes a method called movePiece,
we would want to know how many moves a player has made, but not necessarily how many times a single piece has
been moved. So, all of the ChessPieces share a numberOfTimesMoved instance data that is incremented by any
ChessPiece whenever it is moved.
5) Provide a reason why a method would be declared static.
Answer: A method is declared static if it might be used, not by the current object, but by any objects. That is, the
method does not require access to any single objects instance data. Consider a class called Point that consists of an x
and y coordinate. To determine the distance between two Points, we could make a static computeDistance method. It is
passed two Points as parameters and computes the distance. Another example is the Math class, which has static
methods for various math functions.
6) Assume a class Foo implements Comparable. Without knowing anything else about the Foo class, write an equals
method that returns true if the Foo parameter passed to this Foo is equal to this Foo as determined by using the
implementation of Comparable.
Answer:
public boolean equals(Foo a)
{
if(compareTo(a)) = = 0) return true;
else return false;
}
For questions 7 8, assume that iter is an object of a class that implements Iterator.
7) Write code that outputs all elements of iter, one per line.
Answer:
while (iter.hasNext( ))
{
System.out.println(iter.next());
}
8) Write a method that receives an int parameter and removes the item from iter at that location, where the first item is
numbered location 1. For instance, if the parameter is 3, the 3rd item is removed. If the parameter is out of bounds
(less than 1 or too large for the number of items in iter), then the method should output a message indicating this.
public void removeOne(int x)
{
if (x < 1) System.out.println(x + is too small, cannot remove item);
else
{
int count = 0;
while (count < x && iter.hasNext( ))
{
iter.next( );
count++;
}
if (count == x) iter.remove( );
else System.out.println(x + is too large, cannot remove item);
}
}
For 9 10, 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, the int player will store 0 or 1 depending on whose piece it is.
Assume that the class has methods returnType and returnPlayer which will return the String type and the int player
respectively.

TB 56

Lewis/Loftus/Cocking, 2/e: Chapter 5 Test Bank

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();

Lewis/Loftus/Cocking, 2/e: Chapter 5 Test Bank

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( );
}

You might also like