Java 2 Exam 2 2019
If, within one try statement you want to have catch clauses that catch exceptions of the following types, in which order should they appear in your program? (1) Throwable (2) Exception (3) RuntimeException (4) NumberFormatException
A. 4, 3, 2, 1
To read data from a binary file you create objects from the following classes:
A. FileInputStream and DataInputStream
The exception classes are in packages in the _____________.
A. Java API
When writing a string to a binary file or reading a string from a binary file, it is recommended that you use
A. Methods that use UTF-8 encoding
What is demonstrated by the following code? try { (try block statements . . .) } catch(NumberFormatException | IOException ex) { respondToError(); }
A. Multi-catch, a catch clause that can handle more than one exception, beginning in Java 7
The numeric classes' "parse" methods all throw an exception of this type if the string being converted does not contain a convertible numeric value.
A. NumberFormatException
Unchecked exceptions are those that inherit from:
A. a. the Error class or the RuntimeException class.
Classes that inherit from the Error class are:.
A. for exceptions that are thrown when a critical error occurs, and the application program should not try to handle them.
An exception's default error message can be retrieved using this method.
A. getMessage()
When you write a method that throws a checked exception, you must:
A. have a throws clause in the method header.
The ability to catch multiple types of exceptions with a single catch is known as ____________, and was introduced in Java 7.
A. multi catch
The catch clause:
All of the above.
Look at the following method header: void displayPoint(Point<? extends Number> myPoint) Which of the following objects can be passed as an argument to the displayPoint method?
All of these
Look at the following method header: void displayPoint(Point<? super Double> myPoint) Which of the following objects can be passed as an argument to the displayPoint method?
All of these
Which of the following statements are true? A) All of these B) You can declare references to arrays whose elements are of a generic type C) You cannot create arrays whose elements are instances of a generic type D) You cannot instantiate an object of a generic type
All of these
Which of the following statements are true? A) Generic types do not exist at the byte code level B) The compiler often has to insert type casts into code that results from translating generic code Correct Answer C) All of these Incorrect Response D) The compiler translates generic code by replacing generic types with Object, or with the upper bounds of those types
All of these
Which of the following statements is true?
All of these statements are true
If, within one try statement you want to have catch clauses of the following types, in which order should they appear in your program: (1) Exception (2) IllegalArgumentException (3) RuntimeException (4) Throwable
B. 2 3 1 4
Why does the following code cause a compiler error? try { number = Integer.parseInt(str); } catch (IllegalArgumentException e) { System.out.println("Bad number format."); } catch (NumberFormatException e) { System.out.println(str + " is not a number."); }
B. Because NumberFormatException inherits from IllegalArgumentException. The code should handle NumberFormatException before IllegalArgumentException.
Look at the following code: FileInputStream fstream = new FileInputStream("MyInfo.dat"); DataInputStream inputFile = new DataInputStream(fstream); This code can also be written as:
B. DataInputStream inputFile = new DataInputStream(new FileInputStream("MyInfo.dat"));
What will be the result of the following code? FileOutputStream fstream new FileOutputStream("Output.dat"); DataOutputStream outputFile = new DataOutputStream(fstream);
B. The outputFile variable will reference an object that is able to write binary data to the Output.dat file.
All exceptions are instances of classes that extend this class
B. Throwable
To serialize an object and write it to the file, use this method of the ObjectOutputStream class.
B. WriteObject
A collection whose elements are pairs of keys and values is called a. an enumerator b. a map c. a hash list d. a paired collection
B. a map
The IllegalArgumentException class extends the RuntimeException class, and is therefore:
B. an unchecked exception class
A(n) ________ is an object that is generated in memory as the result of an error or an unexpected event.
B. exception
The try statement may have an optional ____________ clause, which must appear after all of the catch clauses.
B. finally
If the program does not handle an unchecked exception:
B. the program is halted and the default exception handler handles the exception.
In a catch statement, what does the following code do? System.out.println(e.getMessage());
B.It prints the error message for an exception.
What will be the result of the following statements? FileInputStream fstream = new FileInputStream("DataIn.dat"); DataInputStream inFile = new DataInputStream(fstream);
B.The inFile variable will reference an object that is able to read binary data from the Input.dat file.
What will the following code display? String input = "99#7"; int number; try { number = Integer.parseInt(input); } catch(NumberFormatException ex) { number = 0; } catch(RuntimeException ex) { number = 1; } catch(Exception ex) { number = -1; }
C. 0
In the following code, assume that inputFile references a Scanner object that has been successfully used to open a file: double totalIncome = 0.0; while (inputFile.hasNext()) { try { totalIncome += inputFile.nextDouble(); } catch(InputMismatchException e) { System.out.println("Non-numeric data encountered " + "in the file."); inputFile.nextLine(); } finally { totalIncome = 35.5; } } What will be the value of totalIncome after the following values are read from the file? 2.5 8.5 3.0 5.5 abc 1.0
C. 35.5
If your code does not handle and exception when it is thrown, this prints an error message and crashes the program.
C. Default exception handler
To write data to a binary file you create objects from the following classes:
C. FileOutputStream and DataOutputStream
Assume that the classes BlankISBN, NegativePrice, and NegativeNumberOrdered are exception classes that inherit from Exception. The following code is a constructor for the Book class. What must be true about any method that instantiates the Book class with this constructor? public Book(String ISBNOfBook, double priceOfBook, int numberOrderedOfBook) throws BlankISBN, NegativePrice, NegativeNumberOrdered { if (ISBNOfBook == "") throw new BlankISBN(); if (priceOfBook < 0) throw new NegativePrice(priceOfBook); if (numberedOrderedOfBook < 0) throw new NegativeNumberOrdered(numberOrderedv); ISBN = ISBNOfBook; price = priceOfBook; numberedOrdered = numberOrderedOfBook; }
C. It must handle all of the possible exceptions thrown by the constructor or have its own throws clause specifying them.
In order for an object to be serialized, its class must implement this interface.
C. Serializable
If the IOData.dat file does not exist, what will happen when the following statement is executed? RandomAccessFile randomFile = new RandomAccessFile("IOData.dat", "rw");
C. The file IOData.dat will be created
The following catch statement can: catch (Exception e) {...}
C. handle all exceptions that are instances of the Exception class or a subclass of Exception.
When an exception is thrown:
C. it must be handled by the program or by the default exception handler.
When an exception is thrown by code in the try block, the JVM begins searching the try statement for a catch clause that can handle it and passes control of the program to
C. the first catch clause that can handle the exception.
In a try/catch construct, after the catch statement is executed:
C. the program resumes at the statement that immediately follows the try/catch construct.
In a multi-catch, (introduced in Java 7) the exception types are separated in the catch clause by this symbol:
C. |
If a method does not handle a possible checked exception, what must the method have?
D. A throws clause in its header
Given the following constructor code, which of the statements are true? public Book(String ISBNOfBook, double priceOfBook, int numberOrderedOfBook) { if (ISBNOfBook == "") throw new BlankISBN(); if (priceOfBook < 0) throw new NegativePrice(priceOfBook); if (numberedOrderedOfBook < 0) throw new NegativeNumberOrdered(numberOrderedv); ISBN = ISBNOfBook; price = priceOfBook; numberedOrdered = numberOrderedOfBook; }
D. All of the above
If the code in a method can potentially throw a checked exception, then that method must:
D. Either A or B
This is a section of code that gracefully responds to exceptions when they are thrown
D. Exception handler
Under Windows, which of the following statements will open the file InputFile.txt that is in the root directory on the C: drive?
D. FileReader freader = new FileReader("C:\\InputFile.txt");
All of the exceptions that you will handle are instances of classes that extend this class
D. exception
If a random access file contains a stream of characters, which of the following would you use to set the pointer on the fifth character?
D. file.seek(8);
A catch clause that uses a parameter variable of the Exception type is capable of catching any exception that extends the Error class.
F
The throw statement informs the compiler that a method throws one or more exception.
F
The throws clause causes an exception to be thrown.
F
Which of the following statements is true?
Generic types do not exist at the byte code level
The Java notation MyClass<Student> means that
MyClass is a generic class
Suppose that Point<T> is a generic type, and that we have a method of the form void printPoint(Point<?> p) { // Code not shown }
None of these
The clause catch(Exception<T> e) { }
None of these
Let Point<T> be a generic type. We want to write a method that takes as parameter Point objects whose type parameter is the Number class, or any subclass of Number. We can do this by declaring the type of the method parameter as
Point<? extends Number>
Let Point<T> be a generic type. We want to write a method that takes as parameter Point objects whose type parameter is the Number class, or any superclass of Number. We can do this by writing
Point<? super Number>
Consider a method of the form void printPoint(Point<Number> p) { //Code not shown } where Point<T> is a generic type. When the method is called, the only objects that may be passed for the parameter p are
Point<Number> objects only
A class must implement the Serializable interface in order for objects of the class to be serialized.
T
Beginning in Java 7, multi-catch can reduce a lot of duplicated code in a try statement that needs to catch multiple exceptions, but perform the same operation for each one.
T
If the class SerializedClass contains references to objects of other classes as fields, those classes must also implement the Serializable interface in order to be serialized.
T
In versions of Java prior to Java 7, each catch clause can handle only one type of exception.
T
The call stack is an internal list of all the methods that are currently executing.
T
When an exception is thrown by a method that is executing under several layers of method calls, a stack trace indicates the method executing when an exception occurred and all of the methods that were called in order to execute that method.
T
When an object is serialized, it is converted into a series of bytes that contain the object's data.
T
When deserializing an object using the readObject method, you must cast the return value to the desired class type.
T
When the code in a try block may throw more than one type of exception, you need to write a catch clause for each type of exception that could potentially be thrown.
T
Which of the following statements is true?
The keyword implements cannot be used do describe a type parameter that implements an interface
Which of the following generic type notations uses a wildcard?
Which of the following generic type notations uses a wildcard?
The declaration class Point<T extends Number> { } is an example of
a generic class extending a non-generic class
The class public class Point3D<T extends Number> extends Point<T> { } is an example of
a generic class extending another generic class
Which of the following is true? a. Both the Set and List interfaces extend the Collection interface b. Both the Set and Map interfaces extend the Collection interface c. Both the List and Map interfaces extend the Collection interface d. None of the above
a. Both the Set and List interfaces extend the Collection interface
Which of the following is true? a. The ListIterator interface is a subinterface of the Iterator interface b. The ListIterator interface is a superinterface of the Iterator interface c. The ListIterator interface extends the List interface d. None of the above
a. The ListIterator interface is a subinterface of the Iterator interface
An object that is used to retrieve objects from a collection is called a. an iterator b. a collector c. an accessor d. All of the above
a. an iterator
The three major categories of Java collections are a. lists, sets, and maps b. hash lists, hash tables, and sets c. sets, collections, and maps d. tree sets, list sets, and hash maps
a. lists, sets, and maps
A collection that does not impose a positional order on its elements, and does not allow duplicates is called a a. set b. linked list c. non-positional map d. hash map
a. set
One of the advantages of using generics is a. that more type problems can be uncovered at compile-time rather than at run time b. that programs that use generics are smaller when translated to byte code c. that program that use generics execute faster than programs that do not d. that programs that use generic code require less effort in design and development
a. that more type problems can be uncovered at compile-time rather than at run time
When a generic class with an unconstrained type parameter is instantiated without specifying an actual type argument, a. the type Object is used for the unspecified type b. the compiler generates an error c. the computer throws a ClassCastException d. None of the above
a. the type Object is used for the unspecified type
When the next() method of Iterator is called at the end of a collection, it a. throws NoSuchElementException b. returns null c. wraps around to the beginning of the collection and returns the first element d. returns the a copy of the last element returned
a. throws NoSuchElementException
The generic method public static <E extends Number> void displayArray(E[] array) { for (E element : array) System.out.println(element); } can be passed
an array whose element type is Integer
Exceptions of a generic type
are not permitted in Java
When a generic class is instantiated without specifying an actual type argument, the generic class is being used
as a raw type
The automatic conversion of a primitive type to the corresponding wrapper type when being passed as parameter to a generic class is called
autoboxing
Which of the following is true? a. The retrieve() method of an iterator can only be called after isEmpty() has returned false b. The remove() method of an iterator can only be called after next() has been called c. Any iterator can move forward as well as backwards through a collection d. Once an iterator has reached the end of the collection, calling any of its methods will throw a NoSuchElement exception
b. The remove() method of an iterator can only be called after next() has been called
If you try to add an item to an ArrayList whose size is equal to its capacity a. an exception that indicates that the ArrayList is full is thrown b. a new ArrayList object with twice the capacity is created, and the elements are moved to this new ArrayList. c. The method for adding the new item returns false d. The method for adding the new item returns null
b. a new ArrayList object with twice the capacity is created, and the elements are moved to this new ArrayList.
An object that permits a pipeline of operations to be applied to a sequence of elements drawn from a source is called a. an operator pipeline b. a stream c. a sequential operator d. a flow
b. a stream
The default implementation of hashCode in Java returns a. a value determined from the class type of the object b. a value derived from the memory address of the object c. a value determined from the values of the fields in the object d. None of the above
b. a value derived from the memory address of the object
The ListIterator interface a. specializes the Iterator interface to work with lists, but adds no new methods b. adds to Iterator the ability to move backwards in the collection c. adds to Iterator the ability to iterate over several collections, if those collections are lists d. None of the above
b. adds to Iterator the ability to move backwards in the collection
A hashcode of an object a. is the value returned when you store the object into a HashSet collection b. is an integer that can be used to characterize an object and help identify it c. is useful when storing objects in HashMap, HashSet, and List collections d. None of the above
b. is an integer that can be used to characterize an object and help identify it
When you create an instance of a generic class, what types can you pass as arguments for the class type parameters? a. primitive types only b. reference types only c. interface types only d. primitive, reference, and interface types
b. reference types only
A LinkedList is the right kind of list to use when a. most of the elements added to the list are being added at the end b. there are lots of insertions and deletions in the middle of the list c. elements are added to the list in groups of twos, threes, or more d. each element added is a reference to another item
b. there are lots of insertions and deletions in the middle of the list
In a generic method, a type parameter is defined
before the method's return type
If you want to append data to the existing binary file, BinaryFile.dat, use the following statements to open the file.
c. FileOutputStream fstream = new FileOutputStream("BinaryFile.dat", true); DataOutputStream binaryOutputFile = new DataOutputStream(fstream);
The concrete classes that implement the List interface are a. AbstractList, AbstractSequentialList, and List b. LinkedList, ArrayList, and AbstractList c. LinkedList and ArrayList d. None of the above
c. LinkedList and ArrayList
In a generic method, a type parameter is defined a. inside the parentheses, along with the method's parameter variables. b. after the method's return type, and before the method's name c. before the method's return type d. inside the body of the method, but before any local variables are declared
c. before the method's return type
A class is generic a. if it is a subclass of the Object class b. if it is a superclass of the Object class c. if it has type parameters d. if it has method parameters
c. if it has type parameters
An advantage of using generic types is a. lower compile-time overhead b. increased portability of Java programs c. increased type-safety without the need to do typecasts at run time d. faster execution of programs that use generics
c. increased type-safety without the need to do typecasts at run time
A Java collection a. is a class that is defined in the java.awt package b. is an abstract class in the java.collect package c. is an object that is used as a container for other objects d. None of the above
c. is an object that is used as a container for other objects
An index a. is a list of keys that allows fast look up of values in a map b. is an object that indicates which one of a group of collections contains a given value c. is the position of an element within a list d. is used with generic collections to quickly find stored values
c. is the position of an element within a list
A generic class
can extend generic and non-generic classes
A static method of a generic class
cannot refer to any of the type parameters of its class
The declaration ArrayList<int> aL = new ArrayList<int>();
causes a compile-time error
An entry in a map a. is called a mapping b. associates a key with a value c. may not share a key value with any other entry in the map d. All of the above
d all of the above
Which of the following is true? a. A set allows duplicate values to be stored b. A map allows duplicate keys to be stored c. No Java collection allows duplicate values to be stored d. A list allows duplicate values to be stored
d. A list allows duplicate values to be stored
Which of the following generic type notations uses a wildcard? a. Point<W> b. Point<T extends Number> c. Point<T super Integer> d. Point<?>
d. Point<?>
The automatic conversion of a primitive type to the corresponding wrapper type when being passed as parameter to a generic class is called a. type promotion b. type wrapping c. autoconversion d. autoboxing
d. autoboxing
A collection that stores its elements in an (ordered) sequence, and allows access to each element by its position in the sequence is called a: a. map b. positional map c. ordered set d. list
d. list
Constraining a type parameter in a generic class a. causes programs to compile faster b. was added to Java in version 1.3 of the language c. can only be used when the generic class will be used as a superclass for other classes d. restricts the types that can be used as type arguments
d. restricts the types that can be used as type arguments
The notation <E extends Comparable<E>>
declares a generic type that implements the Comparable interface
The process used by the Java compiler to remove generic notation and substitute actual type arguments for formal type parameters is called
erasure
The process of erasure
helps generic code coexist with older code written in pre 1.5 versions of Java
A class is generic
if it has type parameters
An advantage of using generic types is
increased type-safety without the need to do typecasts at run time
The code fragment class MySArrayList extends ArrayList<String> { }
is a correct way to extend a class
Comparable<T> is
is an interface defined in the Java class libraries
A generic class
may not create instances of any of its type parameters
A static field of a generic class
may not have as its type one of the type parameters of the class
When you create an instance of a generic class, what types can you pass as arguments for the class type parameters?
reference types only
Erasure is the process of
replacing generic types with their upper bound, or with Object, during compilation
Constraining a type parameter in a generic class
restricts the types that can be used as type arguments
In the notation <T super Number> the Number class
specifies a lower bound for the parameter type T
In the notation <T extends Number>, the Number class
specifies an upper bound for the parameter type T
One of the advantages of using generics is
that more type problems can be uncovered at compile-time rather than at run time
When a generic method is called,
the compiler determines the actual types to use for the type parameters from the context
When a generic class with an unconstrained type parameter is instantiated without specifying an actual type argument,
the type Object is used for the unspecified type
The automatic conversion of a wrapper type to the corresponding primitive type when the wrapper type is assigned to a variable of the primitive type is called
unboxing
The notation <E implements Comparable<E>>
will be rejected by the Compiler as an error
Consider the class class Value <T extends Number> { private T v; public Value(T v1) { v = v1; } public void output() { System.out.println(v); } } The code Value<Number> nV1 = new Value<Double>(34.5);
will cause a compiler error
Consider the class class Value <T extends Number> { private T v; public Value(T v1) { v = v1; } public void output() { System.out.println(v); } } The code Value<Number> nV = new Value<Number>(12);
will compile and run correctly
Consider the class class Value <T extends Number> { private T v; public Value(T v1) { v = v1; } public void output() { System.out.println(v); } } The code Value<Double> nV1 = new Value<Double>(34.5);
will compile and run correctly
The code public class MyClass<T> { public MyClass() { T myObject = new T(); } }
will not compile
The code ArrayList<String> [ ] a = new ArrayList<String>[100];
will not compile
A type parameter can be constrained
with an upper bound and a lower bound, but not at the same time
A reference to a subclass object can be assigned to a superclass variable
with no restrictions on the genericity of the subclass or superclass