java 2 test 2 (ch 10,11,15)

Ace your homework & exams now with Quizwiz!

Why would an inner class method want to access a variable from a surrounding scope?

Direct access is simpler than the alternative — passing the variable as an argument to a constructor or method.

Suppose you want to use the average method to find the average salary of an array of Employee objects. What condition must the Employee class fulfill?

It must implement the Measurable interface, and its getMeasure method must return the salary.

What is wrong with this code? Measurable meas = new Measurable(); System.out.println(meas.getMeasure());

Measurable is not a class. You cannot construct objects of type Measurable.

The ArrayList class implements the ____ interface. A. Stack B. Queue C. List D. Set

list

If the program is invoked with java CaesarCipher -d file1.txt, what are the elements of args?

args[0] is "-d" and args[1] is "file1.txt"

What is the value of the reverse Polish notation expression 2 3 4 + 5 × ×?

70

What does this code print? Queue<String> q = new LinkedList<>(); q.add("A"); q.add("B"); q.add("C"); while (q.size() > 0) { System.out.print(q.remove() + " "); }

A B C

What is a checked exception? What is an unchecked exception? Give an example for each. Which exceptions do you need to declare with the throws reserved word?

A checked exception indicates something beyond your control has gone wrong. Methods that throw these types of exceptions must specify that they do so by using the throws reserved word. An example is FileNotFoundException. An unchecked exception indicates an error in the code and does not need to be explicitly handled with a try-catch block. An example is IndexOutOfBoundsException.

As you can see from Figure 1, the Java collections framework does not consider a map a collection. Give a reason for this decision.

A collection stores elements, but a map stores associations between elements.

A gradebook application stores a collection of quizzes. Should it use a list or a set?

A list is a better choice because the application will want to retain the order in which the quizzes were given.

An invoice contains a collection of purchased items. Should that collection be implemented as a list or set? Explain your answer.

A list is a good choice here. A list will allow duplicate items to be listed, a likely possibility on an invoice, and implies an order which also may be important for an invoice.

Consider a program that manages an appointment calendar. Should it place the appointments into a list, stack, queue, or priority queue? Explain your answer.

A list is also a good choice here. A useful appointment calendar application will allow the user to browse appointments; although this is possible with stack or queue implementation, it would be awkward.

Why does the measure method of the Measurer interface have one more argument than the getMeasure method of the Measurable interface?

A measurer measures an object, whereas getMeasure measures "itself", that is, the implicit parameter.

A student information system stores a collection of student records for a university. Should it use a list or a set?

A set is a better choice. There is no intrinsically useful ordering for the students. For example, the registrar's office has little use for a list of all students by their GPA. By storing them in a set, adding, removing, and finding students can be efficient.

What is the difference between a set and a map?

A set stores elements. A map stores associations between keys and values.

When using a list iterator, on which condition will the NoSuchElementException be thrown? A. Calling next when you are past the end of the list. B. Calling remove after calling add. C. Calling remove after calling previous. D. Calling next when the iterator points to the last element.

A. Calling next when you are past the end of the list.

What is recommended if the standard library does not have an exception class that describes your particular error situation? A. Design your own exception class as a subclass of an existing exception class. B. Choose RunTimeException from the standard library because it is unchecked and represents a generic exception. C. Design your own exception class by implementing the Throwable interface. D. Design your own exception class as a superclass of an existing exception class.

A. Design your own exception class as a subclass of an existing exception class.

Which of the following statements about exception handling is recommended? A. Throw an exception as soon as a problem is detected, but only catch exceptions when the problem can be handled. B. All exceptions should be handled at the top of the chain of methods. C. All exceptions should be handled where they are first detected. D. Throw an exception only when the problem can be handled.

A. Throw an exception as soon as a problem is detected, but only catch exceptions when the problem can be handled.

Assume that you have declared a queue named myQueue to hold String elements. Which of the following statements will correctly insert an element into myQueue? A. myQueue.add("apple"); B. myQueue.push("apple"); C. myQueue.put("apple"); D. myQueue.insert("apple");

A. myQueue.add("apple");

You need to write a program to manage a waiting list of patrons at a restaurant. Which data structure would be most appropriate to model this situation? A. queue B. map C. stack D. linked list

A. queue

A method that has no implementation is called a/an ____ method. A. abstract B. overloaded C. interface D. implementation

Abstract

How do you modify the program so that it shows the average, not the total, of the inputs?

Add a variable count that is incremented whenever a number is read. At the end, print the average, not the total, as out.printf("Average: %8.2f\n", total / count); Because the string "Average" is three characters longer than "Total", change the other output to out.printf("%18.2f\n", value).

How can you modify the Total program so that it writes the values in two columns, like this:

Add a variable count that is incremented whenever a number is read. Only write a new line when it is even. count++; out.printf("%8.2f", value); if (count % 2 == 0) { out.println(); } At the end of the loop, write a new line if count is odd, then write the total: if (count % 2 == 1) { out.println(); } out.printf("Total: %10.2f\n", total);

Arrays and lists remember the order in which you added elements; sets do not. Why would you want to use a set instead of an array or list?

Adding and removing elements as well as testing for membership is more efficient with sets.

What is the difference between an ActionEvent and a MouseEvent?

An ActionEvent is generated when the user-interface library has detected a particular user intent, such as clicking on a button or hitting ENTER in a text field. A MouseEvent is generated whenever the user moves or clicks the mouse.

Why does the ActionListener interface have only one method, whereas the Mouse Listener has five methods

An ActionListener is only interested in one notification: when the action happens. A MouseListener has multiple methods because there are several potentially interesting mouse events, such as pressing, releasing, or clicking the mouse button.

What is an event object? An event source? An event listener?

An event is an external activity to which a program may want to react. For example, "user clicked on button X" is an event. An event source is the user-interface component that generates a particular event. Event sources report on events. When an event occurs, the event source notifies all event listeners. An event listener belongs to a class that is provided by the application programmer. Its methods describe the actions to be taken when an event occurs.

What is the difference between throwing an exception and catching an exception?

An exception is thrown to report an error. When an exception is thrown, control continues at the nearest enclosing exception handler that is capable of handling the specified exception type. If no such handler exists, then the program terminates. Catching an exception is the means by which to handle the reported error. An exception is caught and handled (processed), ideally, at a point in the program where the error can be addressed.

Which of the following is true about interface types and abstract classes? A. An interface type cannot be instantiated whereas an abstract class can. B. An interface type cannot have instance variables whereas an abstract class can. C. An abstract class can provide method implementation whereas an interface type cannot. D. An interface type cannot have constants whereas an abstract class can.

B. An interface type cannot have instance variables whereas an abstract class can.

Consider the following code snippet: PrintWriter out = new PrintWriter("output.txt"); If a file named "output.txt" already exists, which of the following statements about the PrintWriter object is correct? A. An exception will occur. B. Existing data will be deleted before data are added to the file. C. A new file named "output_1.txt" will be created and used. D. Data will be added at the end of the file.

B. Existing data will be deleted before data are added to the file.

Consider the following code snippet: PrintWriter outputFile = new PrintWriter(filename); writeData(outputFile); outputFile.close(); How can the program ensure that the file will be closed if an exception occurs on the writeData call? A. The program should place the outputFile.close() statement within a try block to ensure that the file will be closed. B. The program should declare the PrintWriter variable in a try-with-resources statement to ensure that the file is closed. C. It is not possible to ensure that the file will be closed when the exception occurs. D. The program does not need to take any action, because the output file will be automatically closed when the exception occurs.

B. The program should declare the PrintWriter variable in a try-with-resources statement to ensure that the file is closed.

You intend to use a hash set with your own object class. Which of the following statements is correct? A. You cannot override the hashCode method in the Object class. B. You can use the hash method of the Objects class to create your own hashCode method by combining the hash codes for the instance variables. C. You can override the hash method for your class provided that it is compatible with its equals method. D. Your class's hashCode method does not need to be compatible with its equals method.

B. You can use the hash method of the Objects class to create your own hashCode method by combining the hash codes for the instance variables.

Insert the missing code in the following code fragment. This fragment is intended to read floating-point numbers from a text file. Scanner in = new Scanner(. . .); while (____________) { double hoursWorked = in.nextDouble(); System.out.println(hoursWorked); } A. in.getNextDouble() B. in.hasNextDouble() C. in.hasNextInt() D. in.peek()

B. in.hasNextDouble()

Using the following definitions of the Measurable and Named interfaces. public interface Measurable { double getMeasure(); } public interface Named { double getName(); } Assume BankAccount provides the code for the getMeasure() and getName() methods. Which of the following could correctly represent the class header for BankAccount? A. public class BankAccount extends Measurable implements Named B. public class BankAccount implements Measurable, Named C. public interface BankAccount implements Measurable, Named D. public class BankAccount extends Measurable, Named

B. public class BankAccount implements Measurable, Named

Insert the missing code in the following code fragment. This fragment is intended to read an input file named dataIn.txt. public static void main(String[] args) __________________ { String inputFileName = "dataIn.txt"; File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); . . . } A. finally FileNotFoundException B. throws FileNotFoundException C. extends FileNotFoundException D. catches FileNotFoundException

B. throws FileNotFoundException

Write a call to the method of Self Check 14 that computes the larger of two bank accounts, then prints its balance.

BankAccount larger = (BankAccount) max(first, second); System.out.println(larger.getBalance()); Note that the result must be cast from Comparable to BankAccount so that you can invoke the getBalance method.

Suppose the input contains the characters 995.0 Fred. What are the values of number and input after this code fragment? int number = 0; if (in.hasNextInt()) { number = in.nextInt(); } String input = in.next();

Because 995.0 is not an integer, the call in.hasNextInt() returns false, and the call in.nextInt() is skipped. The value of number stays 0, and input is set to the string "995.0".

Suppose you read bank account data from a file. Contrary to your expectation, the next input value is not of type double. You decide to implement a BadDataException. Which exception class should you extend?

Because file corruption is beyond the control of the programmer, this should be a checked exception, so it would be wrong to extend RuntimeException or IllegalArgumentException. Because the error is related to input, IOException would be a good choice.

Why is the collection of the values of a map not a set?

Because it might have duplicates

Why is an ArrayIndexOutOfBoundsException not a checked exception?

Because programmers should simply check that their array index values are valid instead of trying to handle an ArrayIndexOutOfBoundsException.

Why was the moveRectangleBy method in the RectangleComponent replaced with a moveRectangleTo method?

Because you know the current mouse position, not the amount by which the mouse has moved.

Which of the following statements about sets is correct? A. Attempting to remove an element that is not in the set generates an exception. B. You can add an element to a specific position within a set. C. A set is a collection of unique elements organized for efficiency. D. A set allows duplicate values

C. A set is a collection of unique elements organized for efficiency.

Which expression converts the string input containing floating-point digits to its floating-point value? A. input.parseFloat() B. input.parseDouble() C. Double.parseDouble(input) D. Float.parseFloat(input)

C. Double.parseDouble(input)

Complete the following code, which is intended to print out all key/value pairs in a map named myMap that contains String data for student IDs and names: Map<String, String> myMap = new HashMap<>(); . . . _______________________________ for (String aKey : mapKeySet) { String name = myMap.get(aKey); System.out.println("ID: " + aKey + "->" + name); } A. Map<String, String> mapKeySet = myMap.keySet(); B. Set<String, String> mapKeySet = myMap.keySet(); C. Set<String> mapKeySet = myMap.keySet(); D. Set<String> mapKeySet = myMap.getKeySet();

C. Set<String> mapKeySet = myMap.keySet();

Consider the following code snippet, assuming that filename represents the name of the output file and writeData outputs the data to that file: try (PrintWriter outputFile = new PrintWriter(filename)) { writeData(outputFile); } Which of the following statements about this code is correct? A. The close method of the outputFile object will be automatically invoked when the try block ends, but only if no exception occurred. B. The program will terminate with an unhandled exception if the PrintWriter constructor fails. C. The close method of the outputFile object will be automatically invoked when the try block ends, whether or not an exception has occurred. D. The close method of the outputFile object will be automatically invoked when the try block ends, but only if an exception occurs.

C. The close method of the outputFile object will be automatically invoked when the try block ends, whether or not an exception has occurred.

Consider the following code snippet: LinkedList<String> words = new LinkedList<>(); words.addLast("abc"); words.addLast("def"); words.addLast("ghi"); System.out.print(words.removeLast()); System.out.print(words.removeFirst()); System.out.print(words.removeLast()); What will this code print when it is executed? A. abcdefghi B. defghiabc C. ghiabcdef D. abcghidef

C. ghiabcdef

Your program must read in an existing text file. You want the program to terminate if any exception related to the file occurs. Which of the following indicates the correct code for the header of the main method? A. public static void main(String[] args) throws FileNotFoundException B. public static void main(String[] args) C. public static void main(String[] args) throws IOException D. public static void main(String[] args) throws UnknownFileException

C. public static void main(String[] args) throws IOException

Which of the following code snippets about exceptions is correct? A. public void read(String filename) throw (IOException, ClassNotFoundException) B. public void read(String filename) throw IOException, ClassNotFoundException C. public void read(String filename) throws IOException, ClassNotFoundException D. public void read(String filename) throws IOException, throws ClassNotFoundException

C. public void read(String filename) throws IOException, ClassNotFoundException

Insert the missing code in the following code fragment. This code is intended to open a file and handle the situation where the file cannot be found. String filename = . . .; try (Scanner in = new Scanner(new File(filename))) { . . . } ___________________ { exception.printStackTrace(); } A. catch (IllegalArgumentException exception) B. catch (new exception (IOException)) C. catch (IOException) D. catch (IOException exception)

D. catch (IOException exception)

Which method of an exception object will retrieve a description of the exception that occurred? A. printStackTrace() B. printMessage() C. getDescription() D. getMessage()

D. getMessage()

Which of the following statements is correct about inheritance and interfaces? A. A class can extend multiple classes and can implement multiple interfaces. B. A class can extend at most one class and can implement at most one interface. C. A class can extend multiple classes and can implement at most one interface. D. A class can extend at most one class and can implement multiple interfaces.

D. A class can extend at most one class and can implement multiple interfaces.

You need to access values by an integer position. Which collection type should you use? A. Queue B. Map C. Hashtable D. ArrayList

D. ArrayList

We might choose to use a linked list over an array list when we will not require frequent ____. I random access II inserting new elements III removing of elements A. III only B. II only C. II and III only D. I only

D. I only

Which of the following statements about using the PrintWriter object is correct? A. If the output file does not exist, a FileNotFoundException will occur. B. If the output file already exists, the new data will be appended to the end of the file. C. If the output file does not exist, an IllegalArgumentException will occur. D. If the output file already exists, the existing data will be discarded before new data are written into the file.

D. If the output file already exists, the existing data will be discarded before new data are written into the file.

Consider the following code snippet: Stack<String> stringStack = new Stack<>(); stringStack.push("ab"); stringStack.push("abc"); stringStack.push("a"); while (!stringStack.empty()) { System.out.print(stringStack.pop() + ","); } What output will be produced when this code is executed? A. abc,ab,a, B. a,ab,abc, C. ab,abc,a, D. a,abc,ab,

D. a,abc,ab,

When reading words using a Scanner object's next method, ____. A. the program must discard white space characters at the beginning of the input before calling the next method B. any characters that are considered to be white space within the word become part of the word C. any characters at the beginning of the input that are considered to be white space are consumed and become part of the word being read D. any characters at the beginning of the input that are considered to be white space are consumed and do not become part of the word being read

D. any characters at the beginning of the input that are considered to be white space are consumed and do not become part of the word being read

When reading words with a Scanner object, a word is defined as ____. A. any sequence of characters consisting of letters only. B. any sequence of characters consisting of letters, numbers, and punctuation symbols only. C. any sequence of characters consisting of letters and numbers only. D. any sequence of characters that is not white space.

D. any sequence of characters that is not white space.

Select an appropriate expression to complete the following method, which is designed to visit the elements in theList and replace each occurrence of the string "hello" with the string "goodbye". public static void helloGoodbye(LinkedList<String> theList) { ListIterator<String> iterator = theList.listIterator(); while (iterator.hasNext()) { if (iterator.next().equals("hello")) { _____________________________ } } } A. iterator.next() = "goodbye"; B. iterator.previous("goodbye"); C. iterator.replace("hello", "goodbye"); D. iterator.set("goodbye");

D. iterator.set("goodbye");

Assume you have created a linked list named myList that currently holds some number of String objects. Which of the following statements correctly removes an element from the end of myList? A. myList.remove(); B. myList.getLast(); C. myList.pop(); D. myList.removeLast();

D. myList.removeLast();

You need a data structure in your program for finding a path out of a maze using backtracking. Which data structure would be most appropriate to model this situation? A. array B. queue C. list D. stack

D. stack

Which String class method will remove spaces from the beginning and the end of a string? A. clean() B. strip() C. truncate() D. trim()

D. trim()

Why wouldn't you want to use an array list for implementing a queue?

Depending on whether you consider the 0 position the head or the tail of the queue, you would either add or remove elements at that position. Both are inefficient operations because all other elements need to be moved.

Explain what the following code prints. Draw a picture of the linked list and the iterator position after each step. LinkedList<String> staff = new LinkedList<>(); ListIterator<String> iterator = staff.listIterator(); iterator.add("Tom"); iterator.add("Diana"); iterator.add("Harry"); iterator = staff.listIterator(); if (iterator.next().equals("Tom")) { iterator.remove(); } while (iterator.hasNext()) { System.out.println(iterator.next()); }

Diana Harry

Explain what the following code prints. Draw a picture of the linked list and the iterator position after each step. LinkedList<String> staff = new LinkedList<>(); ListIterator<String> iterator = staff.listIterator(); iterator.add("Tom"); iterator.add("Diana"); iterator.add("Harry"); iterator = staff.listIterator(); iterator.next(); iterator.next(); iterator.add("Romeo"); iterator.next(); iterator.add("Juliet"); iterator = staff.listIterator(); iterator.next(); iterator.remove(); while (iterator.hasNext()) { System.out.println(iterator.next()); }

Diana Romeo Harry Juliet

Explain what the following code prints. Draw a picture of the linked list after each step. LinkedList<String> staff = new LinkedList<>(); staff.addFirst("Harry"); staff.addLast("Diana"); staff.addFirst("Tom"); System.out.println(staff.removeLast()); System.out.println(staff.removeFirst()); System.out.println(staff.removeLast());

Diana Tom Harry

How do you place the "balance: . . ." message to the left of the "Add Interest" button?

First add label to the panel, then add button.

How many class files are produced when you compile the MeasurerTester program from this section?

Four: one for the outer class, one for the inner class, and two for the Data and Measurer classes.

Explain what the following code prints. Draw a picture of the linked list after each step. LinkedList<String> staff = new LinkedList<>(); staff.addFirst("Harry"); staff.addFirst("Diana"); staff.addFirst("Tom"); System.out.println(staff.removeLast()); System.out.println(staff.removeFirst()); System.out.println(staff.removeLast());

Harry Tom Diana

How can you sort an array of Country objects by increasing area?

Have the Country class implement the Comparable interface, as shown below, and call Arrays.sort. public class Country implements Comparable { . . . public int compareTo(Object otherObject) { Country other = (Country) otherObject; if (area < other.area) { return -1; } if (area > other.area) { return 1; } return 0; } }

What happens if an exception does not have a matching catch clause?

If an exception does not have a matching catch clause, the current method terminates and throws the exception to the next higher level. If there is no matching catch clause at any higher level, then the program terminates with an error.

What happens if you try to open a file for reading that doesn't exist? What happens if you try to open a file for writing that doesn't exist?

If you open a file for reading that doesn't exist, Java will throw a FileNotFoundException. If you open a file for writing that doesn't exist, Java will create a new empty file.

How can you use the average method of this section to find the average length of String objects?

Implement a class StringMeasurer that implements the Measurer interface.

Why would you use an inner class instead of a regular class?

Inner classes are convenient for insignificant classes. Also, their methods can access local and instance variables from the surrounding scope

Assuming that the string input contains the digits of an integer, without any additional characters, which expression obtains the corresponding numeric value? A. Integer.parseInteger(input) B. Integer.parseInt(input) C. Int.parseInt(input) D. input.parseInt()

Integer.parseInt(input)

What is a Map<String, HashSet<String>>? Give a possible use for such a structure.

It associates strings with sets of strings. One application would be a thesaurus that lists synonyms for a given word. For example, the key "improve" might have as its value the set ["ameliorate", "better", "enhance", "enrich", "perfect", "refine"].

Why must the MousePressListener class supply five methods?

It implements the MouseListener interface, which has five methods

Suppose balance is 100 and amount is 200. What is the value of balance after these statements? if (amount > balance) { throw new IllegalArgumentException("Amount exceeds balance"); } balance = balance - amount;

It is still 100. The last statement was not executed because the exception was thrown.

Why does the branch for the subtraction operator in the Calculator program not simply execute? results.push(results.pop() - results.pop());

It would then subtract the first argument from the second. Consider the input 5 3 -. The stack contains 5 and 3, with the 3 on the top. Then results.pop() - results.pop() computes 3 - 5.

You are given a linked list of strings. How do you remove all elements with length less than or equal to three?

Iterator<String> itr - list.iterator(); while (itr.hasNext()) { String item = itr.next(); if (item.length() <= 3) { itr.remove(); } }

What happens if you try to open a file for writing, but the file or device is writeprotected (sometimes called read-only)? Try it out with a short test program.

Java will throw a FileNotFoundException whose error message says "(Access is denied)".

Write a loop that removes all strings with length less than four from a linked list of strings called words.

ListIterator<String> iter = words.iterator(); while (iter.hasNext()) { String str = iter.next(); if (str.length() < 4) { iter.remove(); } }

Write a loop that prints every second element of a linked list of strings called words

ListIterator<String> iter = words.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); if (iter.hasNext()) { iter.next(); // Skip the next element } }

How can you remove spaces from the country name in Section 11.2.4 without using the trim method?

Locate the last character of the country name: int j = i - 1; while (!Character.isWhiteSpace(line.charAt(j))) { j--; } Then extract the country name: String countryName = line.substring(0, j + 1);

Suppose you want to track how many times each word occurs in a document. Declare a suitable map variable.

Map<String, Integer> wordFrequency;

Why is it impossible to construct a Measurable object?

Measurable is an interface. Interfaces have no instance variables and no method implementations.

Can you use the Arrays.sort method to sort an array of String objects? Check the API documentation for the String class.

Yes, you can, because String implements the Comparable interface type.

If both BankAccount and Country implement the Measurable interface, can a Country reference be converted to a BankAccount reference?

No — a Country reference can be converted to a Measurable reference, but if you attempt to cast that reference to a BankAccount, an exception occurs.

In the algorithm of Section 15.6.3, are the operators on the operator stack always in increasing precedence?

No, because there may be parentheses on the stack. The parentheses separate groups of operators, each of which is in increasing precedence.

Can you use the Arrays.sort method to sort an array of Rectangle objects? Check the API documentation for the Rectangle class.

No. The Rectangle class does not implement the Comparable interface.

Is there a difference between catching checked and unchecked exceptions?

No. You can catch both exception types in the same way, as you can see in the code example on page 536.

Suppose C is a class that implements the interfaces I and J, and suppose i is declared as: I i = new C(); Which of the following statements will throw an exception? a. C c = (C) i; b. J j = (J) i; c. i = (I) null;

None of them will throw an exception.

Can you use a cast (BankAccount) meas to convert a Measurable variable meas to a BankAccount reference?

Only if meas actually refers to a BankAccount object.

Suppose you wanted to add the total to an existing file instead of writing a new file. Self Check 1 indicates that you cannot simply do this by specifying the same file for input and output. How can you achieve this task? Provide the pseudocode for the solution.

Open a scanner for the file. For each number in the scanner Add the number to an array. Close the scanner. Set total to 0. Open a print writer for the file. For each number in the array Write the number to the print writer. Add the number to total. Write total to the print writer. Close the print writer.

Do linked lists take more storage space than arrays of the same size?

Yes, for two reasons. A linked list needs to store the neighboring node references, which are not needed in an arry. Moreover, there is some overhead for storing an object. In a linked list, each node is a separate object that incurs this overhead, whereas an array is a single object.

Your input file contains a sequence of numbers, but sometimes a value is not available and marked as N/A. How can you read the numbers and skip over the markers?

Read them as strings, and convert those strings to numbers that are not equal to N/A: String input = in.next(); if (!input.equals("N/A")) { double value = Double.parseDouble(input); Process value }

Write a call to the method of Self Check 19 that computes the larger of two rectangles, then prints its width and height.

Rectangle larger = (Rectangle) max(first, second, areaMeas); System.out.println(larger.getWidth() + " by " + larger.getHeight());

Why are set iterators different from list iterators?

Sets do not have an ordering, so it doesn't make sense to add an element at a particular iterator position, or to traverse a set backward.

Suppose you need to keep a collection of appointments. Would you use a linked list or an array list of Appointment objects?

Since appointments are often added and removed, one would probably prefer a linked list. The linked list will allow easy addition and removal of appointments.

Why wouldn't you want to use a stack to manage print jobs?

Stacks use a "last-in, first-out" discipline. If you are the first one to submit a print job and lots of people add print jobs before the printer has a chance to deal with your job, they get their printouts first, and you have to wait until all other jobs are completed.

Why can you nevertheless declare a variable whose type is Measurable?

That variable never refers to a Measurable object. It refers to an object of some class—a class that implements the Measurable interface.

In the evaluation of the expression 3 - 4 + 5 with the algorithm of Section 15.6.3, which operator gets evaluated first?

The - gets executed first because + doesn't have a higher precedence.

Why is it legal to assign a ClickListener object to a variable of type ActionListener?

The ClickListener class implements the ActionListener interface.

What is wrong with this code? Measurable meas = new Country("Uruguay", 176220); System.out.println(meas.getName());

The variable meas is of type Measurable, and that type has no getName method.

Why can't the average method have a parameter variable of type Object[]?

The Object class doesn't have a getMeasure method, and the average method invokes the getMeasure method.

Consider the method public static void main(String[] args) { try { Scanner in = new Scanner(new File("input.txt")); int value = in.nextInt(); System.out.println(value); } catch (IOException exception) { System.out.println("Error opening file."); } } Suppose the file with the given file name exists and has no contents. Trace the flow of execution.

The Scanner constructor succeeds because the file exists. The nextInt method throws a NoSuchElementException. This is not an IOException. Therefore, the error is not caught. Because there is no other handler, an error message is printed and the program terminates.

Suppose you want to use the average method of Section 10.1 to find the average length of String objects. Why can't this work?

The String class doesn't implement the Measurable interface.

Why was it not necessary to declare the button variable as final?

The actionPerformed method does not access that variable

Which objects are the event source and the event listener in the ButtonViewer program?

The button object is the event source. The listener object is the event listener.

Classes such as Rectangle2D.Double, Ellipse2D.Double, and Line2D.Double implement the Shape interface. The Shape interface has a method Rectangle getBounds() that returns a rectangle completely enclosing the shape. Consider the method call: Shape s = . . .; Rectangle r =s.getBounds(); Explain why this is an example of polymorphism.

The call Rectangle r = s.getBounds(); is an example of polymorphism because the Shape interface declares the method, and each class that implements the interface (Rectangle2D.Double, Ellipse2D.Double, Line2D.Double, etc.) provides its own implementation of the method. The correct implementation is picked at run time.

What does this code fragment print? Why is this an example of polymorphism? Measurable[] data = { new BankAccount(10000), new Country("Belgium", 30510) }; System.out.println(average(data));

The code fragment prints 20255. The average method calls getMeasure on each object in the array. In the first call, the object is a BankAccount. In the second call, the object is a Country. A different getMeasure method is called in each case. The first call returns the account balance, the second one the area, which are then averaged.

What happens when an inner class tries to access a local variable that assumes more than one value? Try it out and explain your findings

The compiler gives an error saying that the local variable is accessed from within inner class and needs to be declared final:

Consider this toplevel and inner class. Which variables can the f method access? public class T { private int t; public void m(final int x, int y) { int a; final int b; class C implements I { public void f() { . . . } } final int c; . . . } }

The f method can access the variables b, t, and x.

If an inner class accesses a local variable from a surrounding scope, what special rule applies?

The local variable must not change. Prior to Java 8, it must be declared as final.

What would happen if you omitted the call to repaint in the moveBy method?

The moved rectangles won't be painted, and the rectangle will appear to be stationary until the frame is repainted for an external reason.

When your program executes a throw statement, which statement is executed next?

The next line of code processed after a throw statement is the first line in the first catch block hierarchy that processes that type of exception.

Why is the collection of the keys of a map a set and not a list?

The ordering does not matter, and you cannot have duplicates

What happens when you supply the name of a nonexistent input file to the Total program? Try it out if you are not sure.

The program throws a FileNotFoundException and terminates.

Suppose you changed line 40 of the SpellCheck program to use a TreeSet instead of a HashSet. How would the output change?

The words would be listed in sorted order.

What is wrong with the following code, and how can you fix it? public static void writeAll(String[] lines, String filename) { PrintWriter out = new PrintWriter(filename); for (String line : lines) { out.println(line.toUpperCase()); } out.close(); }

There are two mistakes. The PrintWriter constructor can throw a FileNotFoundException. You should supply a throws clause. And if one of the array elements is null, a NullPointerException is thrown. In that case, the out.close() statement is never executed. You should use a try-with-resources statement.

Why would you want to declare a variable as Queue<String> q = new LinkedList<>(); instead of simply declaring it as a linked list?

This way, we can ensure that only queue operations can be invoked on the q object.

What is the purpose of the call super(message) in the second InsufficientFundsException constructor?

To pass the exception message string to the IllegalArgumentException superclass.

Explain what the following code prints. Draw a picture of the linked list after each step. LinkedList<String> staff = new LinkedList<>(); staff.addFirst("Harry"); staff.addFirst("Diana"); staff.addFirst("Tom"); System.out.println(staff.removeFirst()); System.out.println(staff.removeFirst()); System.out.println(staff.removeFirst())

Tom Diana Harry

Why don't we need iterators with arrays?

We can simply access each array element with an integer index.

What happens when you supply the same name for the input and output files to the Total program? Try it out if you are not sure.

When the PrintWriter object is created, the output file is emptied. Sadly, that is the same file as the input file. The input file is now empty and the while loop exits immediately.

When would you place an inner class inside a class but outside any methods?

When the inner class is needed by more than one method of the classes.

What happens when you write to a PrintWriter without closing it?

When the program ends any unwritten data in the buffer will not be written to the file. Closing the PrintWriter flushes the buffer to the file before closing the file.

What is the purpose of the try-with-resources statement? Give an example of how it can be used.

When using the try-with-resources statement, the close method is called on the variable when the try-block is completed. If an exception occurs, the close method is called before it is passed to the handler. try (PrintWriter out = new PrintWriter(filename)) { writeData(out); } //out.close() is always called

Why is a queue of books a better choice than a stack for organizing your required reading?

With a stack, you would always read the latest required reading, and you might never get to the oldest readings.

In the sample code for a priority queue, we used a WorkOrder class. Could we have used strings instead PriorityQueue<String> q = new PriorityQueue<>(); q.add("3 - Shampoo carpets"); q.add("1 - Fix broken sink"); q.add("2 - Order cleaning supplies");

Yes--the smallest string (in lexicographic ordering) is removed first. In the example, that is the string starting with 1, then the string starting with 2, and so on. However, the scheme breaks down if a priority value exceeds 9. For example, a string "10 - Line up braces" comes before "2 - Order cleaning supplies" in lexicographic order.

Can a class be an event source for multiple event types? If so, give an example.

Yes; a class can be the event source for multiple event types. For example, a JButton is the event source for both mouse events and action events.

Why can't you use the average method to find the average length of String objects?

You cannot modify the String class to implement Measurable —String is a library class.

What is wrong with the following test to check whether the Set<String>s contains the elements "Tom", "Diana", and "Harry"? if (s.toString().equals("[Tom, Diana, Harry]")) . .

You do not know in which order the set keeps the elements.

When do you call the actionPerformed method?

You don't. It is called whenever the button is clicked

What happens if you try to use an array of String objects with the Data.average method in Section 10.1?

You will get a compiler error. The String class does not implement the Measurable interface.

Suppose an int value a is two billion and b is -a. What is the result of a - b? Of b - a? What is the result of Integer.compare(a, b)? Of Integer.compare(b - a)?

a) a-b = -294967296 b) b-a = 294967296 c) Integer.compare(a, b) = 1 d) Integer.compare(b, a) = -1

Suppose a double value a is 0.6 and b is 0.3. What is the result of (int)(a - b)? Of (int)(b - a)? What is the result of Double.compare(a, b)? Of Double.compare(b - a)?

a) a-b = 0.3 b) b-a = -0.3 c) Double.compare(a, b) = 1 d) Double.compare(b, a) = -1

Suppose r contains a reference to a new Rectangle(5, 10, 20, 30). Which of the following assignments is legal? (Look inside the API documentation to check which interfaces the Rectangle class implements.) a. Rectangle a = r; b. Shape b = r; c. String c = r; d. ActionListener d = r; e. Measurable e = r; f. Serializable f = r; g. Object g = r;

a. Rectangle a = r; b. Shape b = r; f. Serializable f = r; g. Object g = r;

Suppose the class Sandwich implements the Edible interface, and you are given the variable declarations Sandwich sub = new Sandwich(); Rectangle cerealBox = new Rectangle(5, 10, 20, 30); Edible e = null; Which of the following assignment statements are legal? a. e = sub; b. sub = e; c. sub = (Sandwich) e; d. sub = (Sandwich) cerealBox; e. e = cerealBox; f. e = (Edible) cerealBox; g. e = (Rectangle) cerealBox; h. e = (Rectangle) null;

a. e = sub; c. sub = (Sandwich) e The following statement will compile but throw an exception at run time. f. e = (Edible) cerealBox;

Suppose C is a class that implements the interfaces I and J. Which of the following assignments require a cast? C c = . . .; I i = . . .; J j = . . .; a. c = i; b. j = c; c. i = j;

c = i; // c = (C) i; i = j; // i = (I) j;

public interface Measurable { double getMeasure(); ____________ boolean largerThan(Measurable other) { return getMeasure() > other.getMeasure(); } } Which of the following completes the interface declaration correctly? A. public B. private C. final D. default

default

Write a loop that prints all elements that are in both Set<String>s and Set<String>t.

for (String str : s) { if (t.contains(str)) { System.out.println(str); } }

When depositing an amount into a bank account, we don't have to worry about overdrafts—except when the amount is negative. Write a statement that throws an appropriate exception in that case.

if (amount < 0) { throw new IllegalArgumentException("Negative amount"); }

How can you correctly implement the test of Self Check 12?

if (s.size() == 3 && s.contains("Tom") && s.contains("Diana") && s.contains("Harry")) . . .

Which exceptions can the next and nextInt methods of the Scanner class throw? Are they checked exceptions or unchecked exceptions?

next can throw a NoSuchElementException if no more tokens are available or an IllegalStateException if the scanner is closed. nextInt can throw everything that next can plus an InputMismatchException if the next token does not match the Integer regular expression, or is out of range. These are all unchecked exceptions.

Write a method max that finds the larger of any two Comparable objects

public static Comparable max(Comparable a, Comparable b) { if (a.compareTo(b) > 0) { return a; } else { return b; } }

Write a method max with three arguments that finds the larger of any two objects, using a Measurer to compare them.

public static Object max(Object a, Object b, Measurer m) { if (m.getMeasure(a) > m.getMeasure(b)) { return a; } else { return b; } }

A collection without an intrinsic order is called a ____. A. queue B. stack C. set D. list

set

public interface Measurable { double getMeasure(); ____________ double sum(Measurable[] objects) { // implementation to compute the sum of the Measurable objects } } Which of the following completes the interface declaration correctly? A. final B. private C. static D. public

static

Suppose the input contains the characters Hello, World!. What are the values of word and input after this code fragment? String word = in.next(); String input = in.nextLine();

word is "Hello", and input is "World!"

Suppose the input contains the characters 6E6 6,995.00. What are the values of x1 and x2 after this code fragment? double x1 = in.nextDouble(); double x2 = in.nextDouble();

x1 is set to 6000000. Because a comma is not considered a part of a floating-point number in Java, the second call to nextDouble causes an input mismatch exception and x2 is not set.

Suppose the list letters contains elements "A", "B", "C", and "D". Draw the contents of the list and the iterator position for the following operations: ListIterator<String> iter = letters.iterator(); iter.next(); iter.next(); iter.remove(); iter.next(); iter.add("E"); iter.next(); iter.add("F");

|ABCD A|BCD AB|CD A|CD AC|D ACE|D ACED| ACEDF|


Related study sets

Health Insurance Multi Choice Question Prep

View Set

Ethical Decision-Making in Business

View Set

Chapter 37: Obstetrics and Care of the Newborn

View Set

Article IV-VII: The Role of the Constitution

View Set

US OB Examination Review Questions

View Set

cognitive processes final exam WORKSHEET

View Set

NU144- Chapter 17: Preoperative Nursing Management

View Set

SEMMELWEIS UNIVERSITY, MEDICAL BIOPHYSICS - FINAL EXAM

View Set

CH 13: Contracts for Sale and Closing

View Set

Chapter 48: Nursing Care of the Child With an Alteration in Metabolism/Endocrine Disorder - ML4

View Set