Object Oriented Software Development

130 views 8:05 am 0 Comments June 3, 2023

Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
Student ID:
Full name:
MITS4002 – Object Oriented SoftwareWritten assignment
Development
Actvity 11 Exceptons
11.1 Multple-Choice Questons
1) A Java program can handle an excepton in several different ways. Which of the following is not a way that a Java
program could handle an excepton?
A) ignore the excepton
B) handle the excepton where it arose using try and catch statements
C) propagate the excepton to another method where it can be handled
D) throw the excepton to a pre-defned Excepton class to be handled
E) all of the above are ways that a Java program could handle an excepton
ANSWER: D
Explanaton: D) A thrown excepton 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 excepton and caught there in an appropriate catch statement, or else it
contnues 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 excepton causes terminaton of
the program (this would be answer a, the excepton was ignored). However, an excepton is not thrown to an
Excepton class.
2) An excepton can produce a “call stack trace” which lists
A) the actve methods in the order that they were invoked
B) the actve methods in the opposite order that they were invoked
C) the values of all instance data of the object where the excepton was raised
D) the values of all instance data of the object where the excepton was raised and all local variables and
parameters of the method where the excepton was raised
E) the name of the excepton thrown
ANSWER: B
Explanaton: B) The call stack trace provides the names of the methods as stored on the run-tme stack. The
method names are removed from the stack in the opposite order that they were placed, that is, the earliest
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
method was placed there frst, 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 frst one removed. The stack trace then displays all actve methods in the
opposite order that they were called (most recent frst).
Use the code below to answer the following questons. Note that the catch statements in the code are not
implemented, but you will not need those details. Assume flename is a String, x is an int, a is a double array and i
is an int. Use the comments i1, i2, i3, e1, e2, e3, e4, e5 to answer the questons (i for instructon, e for excepton
handler).
try
{

BufferedReader infle = new BufferedReader(new FileReader(flename)); // i1
int x = Integer.parseInt(infle.readLine( ));
a[++i] = (double) (1 / x);
// i2
// i3
}
catch (FileNotFoundExcepton ex) {…}
catch (NumberFormatExcepton ex) {…}
catch (ArithmetcExcepton ex) {…}
catch (ArrayIndexOutOfBounds ex) {…}
catch (IOExcepton ex) {…}
// e1
// e2
// e3
// e4
// e5

3) An excepton raised by the instructon in i1 would be caught by the catch statement labeled
A) e1
B) e2
C) e5
D) either e1 or e5
E) either e1, e4, or e5
ANSWER: D
Explanaton: D) The BufferedReader instructon tries to open an input stream to a given fle. If the flename is
incorrect, a FileNotFoundExcepton is thrown. If some other unexpected IO situaton exists, such as no disk in the
disk drive or invalid stream, then an IOExcepton is thrown.
4) An excepton raised by the instructon in i2 would be caught by the catch statement labeled
A) e1
B) e2
C) e3
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
D) e5
E) either e2 or e5
ANSWER: E
Explanaton: E) This instructon frst reads from the fle, then parses the value and converts it into an int, and then
stores the resultng value in an int variable. An excepton could be thrown by the fle read, which is an IOExcepton,
or by the conversion if the String value read cannot be converted into an int, which is a NumberFormatExcepton.
5) An excepton raised by the instructon in i3 would be caught by the catch statement labeled
A) e2
B) e3
C) e4
D) either e3 or e4
E) either e2, e3, or e4
ANSWER: D
Explanaton: D) If the array is already full, then a[++i] will throw an ArrayIndexOutOfBoundsExcepton and if the
value x is 0, then 1 / x is division by 0 and an Arithmetc Excepton is thrown.
6) An excepton that could also arise in the try statement that does not have an associated catch statement is
A) ClassNotFoundExcepton
B) IllegalArgumentExcepton
C) NegatveArraySizeExcepton
D) NullPointExcepton
E) OutOfMemoryExcepton
ANSWER: D
Explanaton: D) If the array has not yet been instantated, then i3 throws a NullPointerExcepton. The
ClassNotFoundExcepton, IllegalArgumentExcepton and OutOfMemoryExcepton will not be thrown since there is
no code in the try statement that either refers to some unknown class, uses an argument, or deals with the
generaton of new memory. The NegatveArraySizeExcepton will only arise when instantatng an array.
7) A fnally clause will execute
A) only if the try statement that precedes it does not throw an excepton
B) only if the try statement that precedes it throws an excepton that is caught
C) only if the try statement that precedes it throws an excepton that is not caught
D) only if the try statement that precedes it throws an excepton, whether it is caught or not
E) in any circumstance
ANSWER: E
Explanaton: E) A fnally clause, if specifed (because it is optonal) will execute no mater what happens with
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
respect to the try and catch statements.
8) Which of the following messages passed to the String str could throw a StringIndexOutOfBoundsExcepton?
A) str.length( )
B) str.charAt(2);
C) str.replace(‘a’, ‘A’);
D) str.equals(str);
E) any of the above could throw a StringIndexOutOfBoundsExcepton
ANSWER: B
Explanaton: B) The StringIndexOutOfBoundsExcepton is thrown if a parameter of a String method references a
positon in the String that is beyond the bounds of the String (i.e. a negatve int or an int greater than or equal to
the number of characters in the String). This can occur in either charAt or substring methods.
9) The idea that an object can exist separate from the executng program that creates it is called
A) transience
B) statc
C) persistence
D) serializaton
E) fnality
ANSWER: C
Explanaton: C) Objects are stored in memory and are reclaimed by the garbage collector when they are no longer
referenced. When a Java program terminates, no object is referenced and so all objects are reclaimed. It is
desirable, however, to be able to save any given object for future use. This trait is called persistence, and the ability
to do this is by saving the instance data of the object to a fle. This can be done by writng each instance data to a
data fle, but is simplifed using Object Serializaton.
For the questons below, use the following skeletal code.
public statc void main(String[ ] args)
{
try
{
ExceptonThrowerCode etc = new ExceptonThrowerCode( );
etc.m1( );
etc.m2( );
}
catch (ArithmetcExcepton ae) { … }
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
}
public class ExceptonThrowerCode
{

public void m1( )
{

}
public void m2( )
{
try
{
m3( );
}
catch(ArithmetcExcepton ae) {…}
catch(NullPointerExcepton npe) {…}
}
public void m3( )
{
try
{

}
catch(ArithmetcExcepton ae) {…}
}
}
10) If an ArithmetcExcepton arises in the try statement in m3
A) it is caught in main
B) it is caught in m1
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
C) it is caught in m2
D) it is caught in m3
E) it is not caught leading to the program terminatng
ANSWER: D
Explanaton: D) The method m3 has a catch statement for an ArithmetcExcepton, so if one arises in the try
statement in m3, it is caught in the catch statement in m3.
11) If a NullPointerExcepton arises in the try statement in m3
A) it is caught in main
B) it is caught in m1
C) it is caught in m2
D) it is caught in m3
E) it is not caught leading to the program terminatng
ANSWER: C
Explanaton: C) The method m3 has no catch statement for a NullPointerExcepton, and so the excepton is
propagated to the calling method, m2. Method m2 has a catch statement for a NullPointerExcepton, so that is
where the excepton is caught.
12) If a NullPointerExcepton arises in the try statement in m1
A) it is caught in main
B) it is caught in m1
C) it is caught in m2
D) it is caught in m3
E) it is not caught leading to the program terminatng
ANSWER: E
Explanaton: E) The method m1 has no catch statements at all, so any excepton is propagated to the calling
method, main. The method main only has a catch statement for an ArithmetcExcepton, so the
NullPointerExcepton is not caught resultng in the program terminatng.
13) NullPointerExcepton and ArithmetcExcepton are both derived from which class?
A) Error
B) Excepton
C) RuntmeExcepton
D) IllegalAccessExcepton
E) CheckedExcepton
ANSWER: C
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
Explanaton: C) Both of these exceptons are children of RuntmeExcepton, which itself is a child of Excepton.
Error is a Throwable object that is different from Excepton while IllegalAccessExcepton and CheckedExcepton are
children of Excepton but not RuntmeExcepton.
14) In order to have some code throw an excepton, you would use which of the following reserved words?
A) throw
B) throws
C) try
D) Throwable
E) goto
ANSWER: A
Explanaton: A) The reserved word throw is used to throw an excepton when the excepton is detected, as in: if
(score < 0) throw new IllegalTestScoreExcepton(“Input score ” + score + ” is negatve”);
15) Assume Exceptonname is a checked excepton. If a method uses a class that can generate
Exceptonname,
then either the method must include try and catch statements where a catch statement catches
Exceptonname, or
the method header must include the statement
A) throw
Exceptonname
B) throws Exceptoname
C) catch Exceptonname
D) catches Exceptonname
E) implements Exceptonname
ANSWER: B
Explanaton: B) A checked excepton must be caught somewhere and so, if not caught in the method that might
generate the excepton, the excepton must be thrown to whatever called the method. This is accomplished by
statng that the method throws
Exceptonname.
16) Which of the following is not true of the RuntmeExceptons class?
A) All RuntmeExceptons throw checked exceptons
B) All RuntmeExceptons are Throwable objects
C) RuntmeExcepton has child classes ArithmetcExcepton and NullPointerExcepton
D) RuntmeExcepton objects are not Error objects
E) All of the above are true
ANSWER: A
Explanaton: A) The answers in B, C and D are all true, RuntmeExceptons are Throwable objects and are not part
of the Error class, and two types of RuntmeExceptons are ArithmetcExcepton and NullPointerExcepton.
Exceptons that are not RuntmeExceptons include various checked exceptons, but RuntmeExceptons are not
checked exceptons.
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
17) Character streams manage
A) byte-sized data
B) binary data
C) Unicode characters
D) ASCII characters
E) compressed data
ANSWER: C
Explanaton: C) Character streams are used to manage 16-bit Unicode characters. This differs from a byte stream
that is used to manage any kind of byte-sized data, including ASCII characters and binary data of other types.
18) A processing stream is a data stream that
A) can manage both input streams and output streams at the same tme
B) performs some manipulaton or process on the data
C) can only manage input streams
D) operates on input and output devices but not fles
E) can manage byte streams and character streams at the same tme
ANSWER: B
Explanaton: B) A data stream represents a partcular source or destnaton stream and is used for input or output.
A processing stream is like a data stream where some additonal process(es) is(are) added to the input or output.
For example, a processing byte stream might input all items from a fle and remove any ASCII characters that are
not digits so that an input expected to be a number will not throw a NumberFormatExcepton.
19) System.err is a(n)
A) input stream
B) GUI dialog box that indicates when an error has arisen
C) object
D) Error subclass
E) RuntmeExcepton subclass
ANSWER: C
Explanaton: C) There are three default streams available in Java, System.in, System.out, and System.err. All of
these are objects with System.in being an input stream, System.out being an output stream and System.err being
an error stream (which is also an output stream).
20) The Scanner class provides an abstracton for input operatons by
A) using try and catch statements to catch any IOExcepton instead of throwing the Excepton elsewhere
B) parsing input lines into individual tokens
C) performing conversion operatons from String to the appropriate type as specifed in the Scanner message
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
D) inputng from the standard input stream if create is called using System.in
E) all of the above
ANSWER: E
Explanaton: E) Input into a Java program is difcult because it requires a lot of overhead. The Scanner class
implements all of that overhead so that the programmer does not have to see it. Thus, Scanner is an abstracton
for performing input operatons without the details. These details include importng java.io classes, handling
IOExceptons in some way, inputng from the standard input stream, dividing the input into individual tokens and
convertng each token as needed into the requestng form.
21) The term “excepton propagaton” means
A) an excepton is caught by the frst catch clause
B) an excepton not caught by the frst catch clause is caught by an outer (enclosing) catch clause
C) exceptons are caught, sequentally, by catch clauses in the current try block
D) exceptons always are caught by the outermost try block
E) none of the above
ANSWER: E
Explanaton: E) Excepton propagaton means that an excepton is caught by a matching catch clause at the current
try block level, and if none matches, then at the next enclosing try block level, and so forth, untl the excepton
either has been caught by a matching clause or the excepton passes out of the main routne and is caught by the
Java Virtual Machine.
22) Assume infle is a BufferedReader for a textile and that the textile is empty. What is returned from the
message infle.readLine( ); ?
A) 0
B) null
C) a special character known as the End-of-fle marker (EOF)
D) none of the above, the message causes a NullPointerExcepton to be thrown
E) none of the above, the message causes a EndOfFileExcepton to be thrown
ANSWER: B
Explanaton: B) The readLine( ) method returns a String equal to the next text item in the fle. If the fle is empty,
then null is returned.
23) Which of the following classes would you use to open a GUI dialog box, which is then used to select a fle to
open?
A) JOptonPane
B) JTextArea
C) showOpenDialog
D) JFileChooser
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
E) JFileReader
ANSWER: D
Explanaton: D) The JFileChooser class creates dialog boxes that allows the user to select a fle or browse the
directory structure in search of a fle.
24) To implement the KeyListener interface, you must implement all of the following methods except for which
one?
A) keyEvent
B) keyPressed
C) keyTyped
D) keyReleased
E) all of the above methods must be implemented
ANSWER: A
Explanaton: A) Like the MouseListener interface, the KeyListener interface listens for a KeyEvent, which is caused
by pressing or releasing a key, or typing a key which is both a press and a release acton. KeyEvent is an object
generated by any of these actons, but keyEvent is not the name of an abstract method in the KeyListener interface.
25) A Timer object generates ________ at regular intervals.
A) ActonEvents
B) MouseEvents
C) RuntmeExceptons
D) non-throwable Excepton
E) KeyEvents
ANSWER: A
Explanaton: A) An ActonEvent is a type of event associated with any acton (whether it is a mouse acton or
other). The Timer generates an ActonEvent which can then be used by an actonPerformed method to implement
ActonListener.
26) The Timer object should be used to support which of the following types of applicatons?
A) animaton
B) GUI input from the mouse
C) any applet applicaton
D) input from and output to text fles
E) any applicaton that waits for user input via the keyboard
ANSWER: A
Explanaton: A) Animaton requires that a series of images be displayed at tmed intervals where each image is
slightly different than the previous one, resultng in a fluid moton. A Timer object generates ActonEvents in tmed
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
intervals. An actonPerformed method can then alter the output by displaying a slightly altered version of the
image (perhaps by using a different ImageIcon) afer every ActonEvent is generated by the Timer.
27) When a program terminates because a thrown excepton is not handled, the program
A) starts up again automatcally
B) opens a dialog box, which asks the user whether the program should start again, end, or enter a debugging
mode
C) saves all output to a disk fle called the “runStackTrace.txt”
D) opens a dialog box for the user to specify a disk fle name, and all output is stored to that disk fle
E) outputs a message indicatng what and where the excepton was thrown
ANSWER: E
Explanaton: E) If a thrown excepton is not caught anywhere in the program, the program terminates, displaying
the contents of the run stack trace. The frst item on the run stack trace is the excepton that was thrown and
where it was thrown (the line number of the method of the class where the excepton was raised).
28) A method that uses the Scanner class to obtain input does not require either catching or throwing an
IOExcepton. This is because
A) the Scanner class does not call upon any classes that throw checked exceptons
B) the Scanner class’ methods call input methods in try statements and catch IOExceptons so that they are handled
directly in the Scanner class
C) the Scanner class uses JOptonPane dialog boxes instead of java.io classes so that it does not have to deal with
IOExceptons
D) the Scanner class overrides the class IOExcepton making it an unchecked excepton
E) none of the above, methods do require handling IOExcepton even if thrown by a method in a Scanner class
ANSWER: B
Explanaton: B) By having its own catch (IOExcepton…) catch statement, any code in the Scanner class that causes
an IOExcepton is caught by the Scanner class so that your classes that might use the Scanner class do not have to
handle this checked excepton.
29) The showDialog method is part of which class?
A) JOptonPane
B) JColorChooser
C) JTextArea
D) Scanner
E) all of the above
ANSWER: B
Explanaton: B) JColorChooser has a showDialog that displays a color palete for the user to select a color.
JOptonPane has a showInputDialog method but not a showDialog method. JTextArea does not have a comparable
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
method.
30) PrintWriter is a beter output stream class that PrintStream because PrintWriter
A) has both print and println methods and PrintStream only has print
B) can output both byte and character streams and PrintStream can only output byte streams
C) has error checking mechanisms as part of the class and PrintStream does not
D) will not throw checked exceptons and PrintStream will
E) all of the above
ANSWER: C
Explanaton: C) The PrintWriter class is a Writer class while the PrintStream class is a Stream class. The main
difference is that PrintWriter is intended specifcally for fles and so has error checking mechanisms that are not a
part of PrintStream.
31) The difference between a checked and an unchecked excepton is
A) checked exceptons need not be listed in a throws clause
B) unchecked exceptons must be listed in a throws clause
C) neither kind of excepton follows the rules of excepton propagaton
D) an unchecked excepton requires no throws clause
E) a checked excepton always must be caught by a try block; an unchecked excepton does not
ANSWER: D
Explanaton: D) A checked excepton must either be caught or it must be listed in a throws clause. An unchecked
excepton requires no throws clause. Both kinds of exceptons follow the rules of excepton propagaton.
32) Which statement is true about BufferedWriters
A) BufferedWriters are used because they improve runtme efciency
B) BufferedWriters are used because they improve compile tme efciency
C) BufferedWriters can be used with input streams as well as with output streams
D) using a BufferedWriter obviates the necessity for catching IOExceptons
E) none of the above
ANSWER: A
Explanaton: A) BufferedWriters are provided as one way to improve the efciency of a program during executon.
They allow output to be accumulated untl a buffer is full and it becomes “worthwhile” to initate an output
operaton.
33) A Swing tool tp is
A) a mechanism to aid the programmer during the creaton of the source code for a program
B) a short line of text that appears momentarily when the cursor is rested momentarily on a component
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
C) a graphic that appears when the cursor is rested momentarily on a component
D) available to AWT components as well as to Swing components
E) none of the above
ANSWER: B
Explanaton: B) Any Swing component can have a tool tp a short line of text that appears afer the cursor has

rested on a component for a few moments.
34) A disabled component is
A) one that is grayed out
B) one that no longer is actve
C) one that is stll visually apparent, but no longer functons if clicked
D) provides an indicaton of functonality that is not currently available
E) all of the above
ANSWER: E
Explanaton: E) Components that are disabled appear grayed out; they are disabled for the moment, but remain
visually apparent. They provide an indicaton of functonality that can/will be enabled at some other point in tme.
35) A mnemonic is
A) always a single character
B) can be a collecton of characters and/or other keys
C) represents an inactve or disabled component
D) can be used instead of a tool tp
E) none of the above
ANSWER: B
Explanaton: B) A mnemonic is an “abbreviaton” or a “hint” in concise form that represents a command that may
be issued. The command may be a single character or it may be a collecton of characters plus additonal keys such
as Shif, Ctrl, Alt.
11.2 True/False Questons
1) All run-tme Errors throw Exceptons.
ANSWER: FALSE
Explanaton: Java classifes any Throwable object as either an Error or an Excepton, and so no run-tme Errors
throw an Excepton. Run-tme Errors cause terminaton of the program. Exceptons can be handled so that the
program contnues executng (but only if the Excepton is handled properly).
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
2) If an excepton is thrown and is not caught anywhere in the program, then the program terminates.
ANSWER: TRUE
Explanaton: Exceptons are events of interest or are run-tme situatons that cannot be handled normally without
an excepton handler. An excepton is caught by an associated excepton handler. If the excepton is thrown but
not handled, then the program must terminate.
3) A try statement must have at least one catch statement, but could have many catch statements, and may or may
not have a fnally clause.
ANSWER: TRUE
Explanaton: All try statements must have at least one catch statement or there is no reason to have the try
statement. There can be one catch statement for each type of excepton that might be thrown. The programmer
may specify as many catch statements as is felt necessary. Further, a try statement may have a fnally clause, but
does not need one.
4) Programmers can defne their own Exceptons by extending the Excepton class or one of the descendants of the
Excepton class.
ANSWER: TRUE
Explanaton: Java predefnes a number of Excepton classes so that many of the types of Exceptons that can cause
a program to terminate are handled. However, Java allows programmers to add to the language by defning their
own Exceptons for whatever unique situatons they might encounter. These new Exceptons will either be children
of the Excepton class, or children of subclasses or descendants of Excepton.
5) In order to defne a keyboard input object, keyboard, you could use the instructon:
BufferedReader keyboard = new BufferedReader(System.in);
ANSWER: FALSE
Explanaton: A BufferedReader object must be constructed with a Reader object. System.in is an input stream
object instead. In order to use the above defniton, the object in the BufferedReader constructor must be changed
to be (new InputStreamReader(System.in)). A legal statement would be
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
6) The following defnes a new Excepton called AnewExcepton.
public Excepton ANewExcepton
{
public ANewExcepton(String message)
{
super(message);
}
}
ANSWER: FALSE
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
Explanaton: The defniton is nearly correct, but it must defne a class, not an Excepton. Excepton is a class and
ANewExcepton should extend Excepton. The header of the class defniton should be public class ANewExcepton
extends Excepton.
7) An image (such as a jpg or gif) can be added a JLabel and JButon but not a JTextArea.
ANSWER: TRUE
Explanaton: Constructors of JLabel and JButon permit the inserton of an image as in new JLabel(new
ImageIcon(flename)); but JTextAreas only display text of some kind, so they do not have this capability.
8) If an excepton arises in a catch statement, and the excepton is of the type caught by the catch statement, then
the catch statement catches the same excepton. For instance, if the following catch statement frst catches an
ArithmetcExcepton and, while executng, throws another ArithmetcExcepton, it is able to catch the second
ArithmetcExcepton as well the frst.
catch (ArithmetcExcepton ex) {…}
ANSWER: FALSE
Explanaton: An excepton causes the current statement to stop executng and control transfers outside to the frst
catch (afer the current statement) that can catch the excepton. So a catch statement will not catch exceptons
that are thrown from inside of itself although a catch statement can have nested inside of it additonal try and
catch statements.
9) While the Excepton class is part of java.lang, IOExcepton is part of java.io.
ANSWER: TRUE
Explanaton: Excepton is the ancestor class of all Exceptons. One child of Excepton is IOExcepton, which is a
checked excepton that is thrown from various io methods. So, while the Excepton class is defned in the java.lang
package, the IOExcepton class is defned with the rest of the io methods, in java.io.
10) A JTextArea can be used to display text, but not to edit text by the user.
ANSWER: FALSE
Explanaton: A JTextArea is a GUI that displays text that can be edited. To permit text in a JTextArea to be edited,
one of the messages enable(true) or setEnable(true) must be passed to the JTextArea (although if not explicitly
stated, the JTextArea defaults to being editable).
11) A combo box allows the user to select one of several optons from a “drop down” menu.
ANSWER: TRUE
Explanaton: A combo box is defned by the JComboBox class which provides the user with the ability to select

one of several optons from a drop-down list.
12) A combo box generates an item event when the user makes a selecton.
ANSWER: FALSE
Explanaton: A combo box generates an acton event not an item event when the user makes a selecton.
 
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
13) Scroll panes automatcally will scroll vertcally, but special code needs to be used if a scroll pane is to scroll
horizontally.
ANSWER: FALSE
Explanaton: Scroll panes automatcally scroll both vertcally and horizontally; no special code is required to
provide this functonality.
14) The difference between a scroll pane and a split pane is that the former includes a dividing line while the later
does not.
ANSWER: FALSE
Explanaton: This is backwards! The split pane provides an automatc dividing line; scroll panes are single panes.
15) The difference between the throw reserved word and the throws reserved word is that throw is used within a
method body, while throws is used within a method header.
ANSWER: TRUE
Explanaton: Throw is an imperatve command that is used within a method to create and throw a new excepton.
Throws is a compiler directve that tells the compiler that the current method may issue a throw that is not caught
within the method and thus may escape to an outer level.

11.3 Free-Form Questons
1) Write code that will create a BufferedReader object to input from standard input (System.in) an int, a double and
a char.
ANSWER: BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
int anInt = Integer.parseInt(keyboard.readLine( ));
double aDouble = Double.parseDouble(keyboard.readLine( ));
char aCharacter = keyboard.readLine( ).charAt(0);
2) Write code with a try statement and proper catch statements to atempt to take the square root of an int value
input using the BufferedReader keyboard. Catch all Exceptons that could possibly be thrown.
ANSWER: try
{
int x = Integer.parseInt(keyboard.readLine( ));
double y = Math.sqrt(x);
}
catch (ArithmetcExcepton ex) {System.out.println(“Cannot take the square root of ” + x); }
catch (NumberFormatExcepton ex) {System.out.println(“The input value ” + x + ” is not an int”);
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
}
catch (IOExcepton ex) {System.out.println(“IO Excepton thrown”); }
3) Explain or provide an example showing how each of the following Exceptons could arise.
a) ArithmetcExcepton
b) NullPointerExcepton
c) NumberFormatExcepton
d) IndexOutOfBoundsExcepton
e) IOExcepton
ANSWER: a) An arithmetc operaton could not take place because of an illegal acton such as division by zero
or square root of a negatve number
b) An object was not instantated (it had the value null) before a message was passed to it
c) An expected value for a numeric operaton was not a legal number, such as trying to parse a String value to
create an equivalent int where the String contains a non-digit character
d) A numeric parameter used as an index into an object such as an array, String or Vector was out of range, such
as charAt(-1)
e) A mishap arose when inputng from keyboard or inputng or outputng to disk such as disk not in disk drive.
4) Rewrite the following code using try and catch statements, catching any exceptons that might be thrown.
Assume keyboard is a BufferedReader.
for (j=0;j<limit;j++)
{
x = Integer.parseInt(keyboard.readLine( ));
y[j] = 1 / x;
}
ANSWER: try
{
for (j=0; j<limit; j++)
{
x = Integer.parseInt(keyboard.readLine( ));
y[j] = 1 / x;
}
}
catch (ArithmetcExcepton ex) { y[j] = x;}
catch (NumberFormatExcepton ex) {x = 0; y[j] = 0;}
catch (IOExcepton ex) {System.out.println(“IO Excepton, cannot contnue”);}
catch (ArrayIndexOutOfBoundsExcepton ex) {System.out.println(“Array full”); }
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
5) Rewrite the following method using try and catch statements instead of the throws clause in the method’s
header.
public String getInput(String flename) throws IOExcepton
{
BufferedReader infle = new BufferedReader(new FileReader(flename));
String response = infle.readLine( );
infle.close( );
return response;
}
ANSWER: public String getInput(String flename)
{
String response = null;
try
{
BufferedReader infle = new BufferedReader(new FileReader(flename));
response = infle.readLine( );
infle.close( );
}
catch (IOExcepton ex) { response = null; }
fnally { return response; }
}
6) Test scores should fall between 0 and 100. Assume an Excepton called TestScoreExcepton has been
implemented and imported. Write code to input 10 test scores, compute their average, but throw a
TestScoreExcepton in case any inputs violate the proper range. Assume keyboard is a BufferedReader, already
instantated.
ANSWER: int sum = 0;
int value;
for (int j = 0; j < 10; j++)
{
System.out.println(“Enter the next score”);
value = Integer.parseInt(keyboard.readLine( ));
if (value < 0 || value > 100) throw new TestScoreExcepton(value + ” is out of range”);
else sum += value;
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
}
double average = (double) sum / 10;
For the questons below, consider a class Student that implements Serializable. Student has instance data name,
ssn, major, minor, gpa, hours, and classRank.
7) Assume that you will want to save, using object serializaton, a Student’s name, ssn, major and minor to a disk
fle. Write the instance data defnitons for Student.
ANSWER: The queston is really asking which of the instance data need to be transient. Since you want to save
name, ssn, major and minor, the others (gpa, hours, classRank) will be transient instance data.
private String name;
private String ssn;
private String major;
private String minor;
private transient double gpa;
private transient int hours;
private transient String classRank;
8) Write a save method that will save a given student to the String flename passed as a parameter.
ANSWER: public void save(String flename) throws IOExcepton
{
ObjectOutputStream outile = new ObjectOutputStream(new FileOutputStream(flename));
outile.writeObject(this);
outile.close( );
}
9) Write a set of code that will allow a user to select a fle through a JFileChooser, read each item of the fle,
outputng each item to the screen, and close the fle at the end.
ANSWER: JFileChooser jfc = new JFileChooser( );
jfc.showOpenDialog(null);
File fle = jfc.getSelectedFile( );
BufferedReader infle = new BufferedReader(new FileReader(fle));
String x = infle.readLine( );
while (x!=null)
{
System.out.println(x);
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
x = infle.readLine( );
}
infle.close( );
10) Write a set of code that will allow a user to select a fle through a JFileChooser and store all items in the String
array list to the selected fle, closing the fle when done.
ANSWER: JFileChooser jfc = new JFileChooser( );
jfc.showOpenDialog(null);
File fle = jfc.getSelectedFile( );
PrintWriter outile = new PrintWriter(new FileWriter(fle));
for (int j = 0; j<list.length; j++)
outile.println(list[j]);
outile.close( );
11) Write a set of code that will allow a user to select an input image and then place this image in a JLabel lab1 and
add lab1 to a JPanel as the northern component in a JFrame using BorderLayout. The JFrame has already been
instantated as jf and the BorderLayout already established. Hint: a JFileChooser returns a File and JLabel requires
the String name of a fle as an argument. A File can return its name using File class’ method getAbsolutePath( )
ANSWER: JFileChooser jfc = new JFileChooser( );
jfc.showOpenDialog(null);
File f = jfc.getSelectedFile();
ImageIcon im = new ImageIcon(f. getAbsoluteFile());
JLabel lab1 = new JLabel(im);
jp.add(lab1, BorderLayout.NORTH);
jf.getContentPane().add(jp);
jf.pack(); jf.show();
12) Write code to display the contents of the String array stuff to a JTextArea where each element of the array is
placed on individual lines. Assume that no String is more than 25 characters long.
ANSWER: JTextArea jta = new JTextArea(stuff.length, 25);
String temp = stuff[0];
for (int j = 0; j < stuff.length; j++)
temp += “n” + stuff[j];
jta.setText(temp);
13) Explain how you would use a Timer to create animaton in a JLabel.
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
ANSWER: The Timer will create ActonEvents at tmed intervals. First, create a Timer whose delay is set to the
amount of tme you want between movements in the animaton. Next, create a JLabel and insert it into an
appropriate JFrame container. Now, implement an ActonListener whose actonPerformed method will create a
new ImageIcon every tme it is called where the new image fle is loaded from one of a set of fles, each fle being a
different part of the animaton sequence. Replace the old JLabel with one that has the new ImageIcon and replace
the old JLabel with the new JLabel in the JFrame.
14) Write a set of code that will create 4 JButons and add each of these to a JPanel so that they appear in a 2×2
grid. The JButons will not have any text appear in them (i.e. no commands or names) but instead, will each appear
as a color set by the user by using JColorChooser.
ANSWER: JButon b1 = new JButon( );
JButon b2 = new JButon( );
JButon b3 = new JButon( );
JButon b4 = new JButon( );
b1.setBackground(JColorChooser.showDialog(jf, “Select Color for Buton 1”, Color.white));
b2.setBackground(JColorChooser.showDialog(jf, “Select Color for Buton 2”, Color.white));
b3.setBackground(JColorChooser.showDialog(jf, “Select Color for Buton 3”, Color.white));
b4.setBackground(JColorChooser.showDialog(jf, “Select Color for Buton 4”, Color.white));
jp.add(b1);
jp.add(b2);
jp.add(b3);
jp.add(b4);
15) By now you almost certainly have run a Java program that has experienced a NullPointerExcepton. Explain the
reason(s) that a NullPointerExcepton may be generated.
ANSWER: NullPointerExceptons occur when a reference is used before the reference has been initalized. More
frequently they occur when a reference is used while the reference contains a null value.
16) What are the three standard I/O streams and what purposes do they fulfll?
ANSWER: The three standard I/O streams are System.in, System.out, and System.err. System.in is the standard
system input stream. Most usually it is connected to the keyboard. System.out is the standard system output
stream. It usually is connected to the display. Both System.in and System.out are used for “normal” input and
output. System.err usually is connected to the standard error output. This, too, usually is connected to the display.
It is used for the display of warning and error messages that otherwise might become “lost” due, perhaps, to
output redirecton.
17) What is a mnemonic? What are they used for?
ANSWER: A mnemonic is a short character sequence (one to three keys, including non-printng keys such as Shif,
Alt, Ctrl) that are used to abbreviate a command that is already provided via some other method such as a

buton, or an item in a list. It is a shortcut which is entrely equivalent to the corresponding command. Mnemonics
provide keyboard equivalents to actons that otherwise might require a mouse acton, including perhaps a click or
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
double-click.
18) Why might you want to create your own excepton class? What purpose would it serve?
ANSWER: If you have a collecton of error conditons that pertain to a specifc functon or group of functons that a
porton of a program may generate, it might be very wise to create an excepton class for that collecton of error
conditons. Then you would not need to test explicitly for error conditons within that code you’d protect the

code with try-catch blocks. This would make the code far cleaner, easier to understand, and easier to maintain.
MITS4002 – Object Oriented Software Development
Victorian Institute of Technology Pty Ltd
ABN: 41 085 128 525 RTO No: 20829 TEQSA ID: PRV14007 CRICOS Provider Code: 02044E
Practcal
19. Reconsider BankAccount example introduced earlier. If we try to construct an account by
specifying a negative balance, the program contines to work even if it is illogical. To prevent
this from happening, the constuctor should cause an exception to be “thrown”.
a. Rewrite
BankAccount1 call it BankAccount10. The constructor of this class would
throw a generic Exception when invalid construction is attempted.
b. Write a driver class called
BankApp10
i. Test the working of the working (or more precisely the failure!) of an invalid
construction.
ii. Use a try … catch construct to gracefully exit the program.
c. Create a custom Exception class called
InvalidBakAccountException and use it to
rewrite (a) and (b).
What new concepts have we learnt in Question Eleven?
Exception handling
Customised Exception classes.
MITS4002 – Object Oriented Software Development

Tags: , , , , , , ,