BIG JAVA, EARLY OBJECTS ENHANCED ETEXT 7TH EDITION BY CAY S. HORSTMANN TEST BANK (ANSWERS AT THE END

Page 1


Name:

Class:

Date:

testbank-bj-7-ch1

Indicate the answer choice that best completes the statement or answers the question. 1. Which statement best describes a computer program? a. A program is a sequence of comments. b. A program can decide what task it is to perform. c. A program is a sequence of instructions and decisions that the computer carries out. d. A program can only perform one simple task. 2. Which statement regarding computer programs is correct? a. Computer programs can decide what task to perform. b. Large and complex computer programs are generally written by only one programmer. c. Computer programs are composed of extremely primitive operations. d. Small computer programs are not documented. 3. What is an example of a typical instruction in a computer program? a. Add up two numbers. b. Lay out a term paper. c. Drive a car. d. Display a fancy font. 4. What does CPU stand for? a. Computer Programming Unit b. Computer Processing Unit c. Central Processing Unit d. Central Programming Unit 5. Which one of the following is NOT a function of a CPU? a. Performing arithmetic operations b. Processing data and controlling programs c. Querying a database d. Fetching and storing data from storage and input devices 6. Which type of storage is made from electronic circuits that can store data? a. compact disk (CD) b. hard disk c. primary storage d. secondary storage 7. Which one of the following memory types provides storage that persists without electricity? a. primary storage b. RAM c. memory d. secondary storage 8. Which one of the following memory types provides storage that is slower and less expensive? Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch1 a. primary storage b. secondary storage c. peripheral device d. the transistor 9. Which type of secondary storage consists of rotating platters coated with a magnetic material? a. hard disk b. solid state drive c. compact disk (CD) d. memory 10. Some computers are self-contained units; others are interconnected through what? a. bus b. networks c. peripheral devices d. power lines 11. Which is an example of a peripheral device? a. the CPU b. primary storage c. motherboard d. speakers 12. Which memory type does not provide persistent storage? a. secondary storage b. hard disk c. primary storage d. DVD 13. Where must program instructions and data reside in order for the CPU to directly read and execute them? a. memory b. bus c. hard disk d. somewhere on the computer network 14. What term is used to refer to the computer instructions that are executed by a CPU? a. virtual machine b. machine code c. high-level code d. instruction set 15. What is the Java Virtual Machine? a. A CPU that runs compiled Java code. b. A library that makes it possible to write portable programs. Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch1 c. A program that simulates a real CPU running compiled Java code. d. A program that translates Java code into machine instructions. 16. What is the term used to refer to Java code that runs in a browser? a. applet b. script c. html d. class 17. What term is used to refer to languages that allow programmers to describe tasks at a higher conceptual level than machine code? a. virtual b. high-level c. sophisticated d. conceptual 18. What tool translates high-level instructions into low level machine code? a. debugger b. assembler c. compiler d. linker 19. What tool translates Java source code into files that contain instructions for the Java Virtual Machine? a. linker b. compiler c. assembler d. interpreter 20. Which statement is true about running a Java program on a different CPU? a. You need different Java source code for each CPU. b. You can take code that has been generated by the Java compiler and run it on different CPUs. c. You need to compile the Java program for each CPU. d. You cannot run the program on a different CPU because Java, being a high-level programming language, is machine dependent. 21. When was Java officially introduced? a. 1991 b. 1995 c. 2000 d. 2005 22. Which statement best describes the portability characteristic of Java? a. The same already-compiled Java programs will run on Windows, UNIX, Linux, or Macintosh operating systems without any change. b. The same Java compiler can be used on many operating systems. Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch1 c. There are only small differences between the Java programming language on different operating systems. d. It is easy to change a Java program so that it will work on different operating systems. 23. No matter which Java development environment you use, what happens to the Java source code in order for a Java program to execute? a. The source code is automatically separated into many files. b. The source code is backed up to a network storage facility. c. A Java compiler converts all uppercase letters to lowercase. d. A Java compiler translates the source code into class files. 24. Why should you set aside time to become familiar with the programming environment? a. The time you spend will prevent data loss without the need for backups. b. The tools needed for Java programming are different from other software. c. Although computer systems vary widely, the Java programming environment is always the same. d. The Java libraries are detailed and extensive. 25. Suppose that a computer virus infects your computer and corrupts the files you were going to submit for your current homework assignment. What precaution could have saved you from a disastrously bad grade for this assignment? a. Defragment the hard drive. b. Purchase an anti-virus program to remove the virus from your computer. c. Make regular backups of all your important files. d. Purchase an extended warranty for your computer. 26. Which statement regarding backup strategies for Java files is correct? a. You should have multiple copies of your source files in different locations. b. You should regularly print out your work so you can retype it in case of data loss. c. You should regularly back up the Java virtual machine instructions to prevent loss of valuable work. d. Your compiler automatically makes backups of your source files. 27. The line public class HelloPrinter indicates which declaration below? a. Declaration of the variable class. b. Declaration of the class HelloPrinter. c. Declaration of the variable public. d. Declaration of the class public. 28. Every Java program consists of one or more of these fundamental building blocks. a. class b. CPU c. applet d. parameter 29. What is the name of the file that contains the Java source code for the public class HelloPrinter? a. HelloPrinter b. HelloPrinter.java Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch1 c. HelloPrinter.class d. HelloPrinter.txt 30. A __________ contains sequences of programming instructions that describe how to perform a particular task. a. parameter b. label c. variable d. method 31. What term is used to refer to an individual instruction inside a method? a. statement b. constant c. comment d. object 32. In Java, every statement must end with which symbol? a. . b. ) c. ! d. ; 33. What term is used to refer to a sequence of characters enclosed in quotation marks? a. string b. object c. comment d. variable 34. What term is used to refer to values supplied to a method that are needed to carry out its task? a. class b. object c. argument d. comment 35. Arguments supplied to methods are enclosed by which symbols? a. () b. " " c. {} d. // 36. Whenever a method is called in Java, what must be specified? a. program name, method name b. strings, method name c. method name, arguments d. the main method, arguments Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch1 37. What is the syntax for calling the println method on the object System.out? a. println("Any message").System.out; b. System.out("Any message").println; c. System.out.println("Any message"); d. println(System.out,"Any message"); 38. What is the name of the method in the given method call?

System.out.println("Welcome"); a. "Welcome" b. System c. println d. out 39. What is the argument in the given method call?

System.out.println("Welcome"); a. out b. println c. "Welcome" d. System 40. What is the output of the following Java statement?

System.out.println("4 + 6"); a. 10 b. 46 c. 4 d. 4 + 6 41. What is the output of the following Java statement?

System.out.println(4 + 6); a. 4 + 6 b. 4 c. 10 d. 46 42. Which statement is true about the following Java code fragment:

System.out.println("Hello!); a. There is a run-time error. Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch1 b. There are no errors. c. There is a compile-time error. d. There are multiple errors. 43. Assuming the programmer wishes to display "Hello!" on the screen, which statement is true about the following Java code fragment:

System.out.println("Helo!"); a. There is a run-time error. b. There are no errors. c. There is a compile-time error. d. There are multiple errors. 44. Assuming the programmer wishes to display "Hello!" on the screen, which statement is true about the following Java code fragment:

System.out.println("Hello!"); a. There is a run-time error. b. There are no errors. c. There is a compile-time error. d. There are multiple errors. 45. Assuming the programmer wishes to display "Hello!" on the screen, which statement is true about the following Java code fragment:

System.out.printn("Helo!"); a. There is a run-time error. b. There are no errors. c. There is a compile-time error. d. There are multiple errors. 46. Assume that the following Java statement is contained in the main method of the class named Hello:

System.out.printLine("Hello!"); What is the name of the file generated by the Java compiler? a. Hello.java b. Hello c. No file is generated due to an error. d. Hello.class 47. What is a logic error? a. A violation of the rules of the computer language. Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch1 b. A missing main method. c. A program that is syntactically correct but does not do what it is supposed to do. d. An error that is so severe that it generates an exception. 48. What is the term used to describe an error detected by the compiler that is a violation of the programming language rules? a. logic error b. compile-time error c. run-time error d. typo 49. Other than compile-time error, what is another term used to describe an error detected by the compiler that is a violation of the programming language rules? a. typo b. logic error c. syntax error d. run-time error 50. What is the term used to describe an error causing a program to take an action that the programmer did not intend? a. typo b. run-time error c. compile-time error d. syntax error 51. Other than run-time error, what is another term used to describe an error causing a program to take an action that the programmer did not intend? a. syntax error b. logic error c. mistake d. compile-time error 52. Which statement is true about the following Java statement:

System.out.Println("Welcome!"); a. There are multiple errors. b. There are no errors. c. There is a run-time error. d. There is a compile-time error. 53. Assuming the programmer wishes to output the phrase "Hello!", which of the following is true about the following Java statement:

System.out.println("Welcme!"); a. There are multiple errors. Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch1 b. There is a run-time error. c. There are no errors. d. There is a compile-time error. 54. Assuming the programmer wishes to output the phrase "Welcome!", Which statement is true about the following Java statement:

System.out.println("Welcome!"); a. There are no errors. b. There is a run-time error. c. There are multiple errors. d. There is a compile-time error. 55. Assuming the programmer wishes to output the phrase "Welcome!", which of the following is true about the following Java statement.

System.out.Println("Wlcome!"); a. There are no errors. b. There is a compile-time error. c. There is a run-time error. d. There are multiple errors. 56. Assume that the main method of the class named Welcome does not contain any compile-time errors. What is the name of the file generated by the Java compiler? a. Welcome.class b. Welcome.java c. No additional file is generated. d. Welcome 57. Which statement is true about the compilation process? a. The compiler will generate CPU specific instructions even if it detects an error. b. The compiler will generate Java virtual machine instructions even if it detects an error. c. The compiler will stop compiling when it finds the first error. d. The compiler will continue compiling after it finds an error. 58. Who or what is responsible for inspecting and testing the program to guard against logic errors? a. JVM b. programmer c. end-user d. compiler 59. If you get a sequence of error messages from the compiler that are increasingly off track, you should a. check for division by zero Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch1 b. restructure your code to make it more readable c. check for spelling, capitalization, or missing quotation marks d. include more of your code within themain method 60. The error message "cannot find symbol" is usually a good clue that what kind of error has been made? a. logic b. spelling c. run-time d. division by zero 61. A sequence of steps that contains precise instructions for what to do at each step and where to go next is ______________. a. unambiguous b. terminating c. executable d. documented 62. A sequence of steps that can be carried out in practice is ______________. a. unambiguous b. terminating c. executable d. documented 63. A sequence of steps that eventually comes to an end is ______________. a. unambiguous b. terminating c. executable d. documented 64. What is the purpose of the following algorithm?

input somenum Repeat the following steps for 14 times input variable1 if variable1 < somenum then somenum = variable1 print somenum a. To search for a particular number among 15 numbers. b. To find the largest among 15 numbers. c. To print out the 15 numbers. d. To find the smallest among 15 numbers. 65. Evaluate the given pseudocode to calculate the efficiency of a vehicle's fuel consumption using the following test Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch1 values, rounded to one decimal place: The trip odometer reading (odometer) = 350 The amount to fill the gas tank (amount) = 12

input odometer input amount output odometer/amount What is the final output? a. 27.7 b. 29.2 c. 34.4 d. 32.3 66. Evaluate the given pseudocode to calculate the weighted score for a student: The homework score (homework) = 95 The weight of homework (hwWeight) = 35% The exam score (exams) = 87 The weight of exams(exWeight) = 65%

input homework input hwWeight input exams input exWeight output homework*hwWeight + exams*exWeight What is the final output? a. 89.20 b. 89.80 c. 87.80 d. 92.20 67. Evaluate the given pseudocode to calculate the payment (pmt) with the following test values: The total number of hours worked (working_hours) = 60 The rate paid for hourly work (rate) = 12

input working_hours input rate pmt = working_hours * rate if working_hours > 40 then extra_hours = working_hours - 40 extra_pmt = extra_hours * rate pmt = pmt + extra_pmt output pmt Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch1 What is the final output? a. 960 b. 840 c. 240 d. 720 68. What term is used to refer to an informal description of a sequence of steps for solving a problem? a. assembly language instructions b. pseudocode c. machine instructions for a specific CPU d. Java virtual machine instructions 69. What term is used to refer to a sequence of steps for solving a problem that is unambiguous, executable, and terminating? a. documentation b. pseudoprogram c. algorithm d. comments 70. Which of the following options is true about algorithms? a. Algorithms are described informally and can contain ambiguous steps. b. Algorithms are written in a programming language. c. Algorithms can replace the source code in programs. d. You must create an algorithm for a problem before you can create a program to solve the problem. 71. A sequence of steps is unambiguous when ___________________________ a. it will eventually come to an end. b. it is clearly documented. c. it can be carried out in practice. d. there are precise instructions for what to do at each step and where to go next. 72. A sequence of steps is executable when ___________________________ a. it will eventually come to an end. b. it can be carried out in practice. c. it is documented. d. there are precise instructions for what to do at each step and where to go next. 73. A sequence of steps is terminating when ___________________________ a. there are precise instructions for what to do at each step and where to go next. b. it will eventually come to an end. c. it can be documented. d. it can be carried out in practice. 74. What is the purpose of the following algorithm? Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch1

input num Repeat the following steps for 9 times input var1 if var1 > num then num = var1 print num a. To print out the 10 numbers b. To search for a particular number among 10 numbers c. To find the largest among 10 numbers d. To find the smallest among 10 numbers 75. Evaluate the given pseudocode to calculate the efficiency of a vehicle's fuel consumption using the following test values: The trip odometer reading (odometer) = 300 The amount to fill the gas tank (amount) = 15

input odometer input amount output odometer/amount What is the final output? a. 15 b. 10 c. 30 d. 20 76. Evaluate the given pseudocode to calculate the weighted score for a student: The program score (program) = 92 The weight of programs (pgmWeight) = 40% The exam score (exams) = 85 The weight of exams(exWeight) = 60%

input program input pgmWeight input exams input exWeight output program*pgmWeight + exams*exWeight What is the final output? a. 89.20 b. 87.80 c. 89.80 Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch1 d. 92.20 77. Evaluate the given pseudocode to calculate the payment (pmt) with the following test values: The total number of hours worked (working_hours) = 50 The rate paid for hourly work (rate) = 10

input working_hours input rate pmt = working_hours * rate if working_hours > 40 then extra_hours = working_hours – 40 extra_pmt = extra_hours * rate pmt = pmt + extra_pmt end of if output pmt What is the final output? a. 540 b. 580 c. 500 d. 600 78. What is the correct order of the steps in the program development process: i. Develop and describe the algorithm. ii. Translate the algorithm into Java. iii. Understand the problem. iv. Compile and test the program. v. Test the algorithm with different inputs. a. iii, i, ii, iv, v b. i, ii, iv, v, iii c. iii, i, v, ii, iv d. i, iii, v, ii, iv 79. Pseudocode must be i. Unambiguous. ii. Syntactically correct code. iii. Readable by a human. iv. Indicative of results of an algorithm. a. i, ii b. i, ii, iii c. i, iii, iv d. ii, iii, iv

Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch1 Answer Key 1. c 2. c 3. a 4. c 5. c 6. c 7. d 8. b 9. a 10. b 11. d 12. c 13. a 14. b 15. c 16. a 17. b 18. c 19. b 20. b 21. b 22. a 23. d 24. b 25. c Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch1 26. a 27. b 28. a 29. b 30. d 31. a 32. d 33. a 34. c 35. a 36. c 37. c 38. c 39. c 40. d 41. c 42. c 43. a 44. b 45. d 46. c 47. c 48. b 49. c 50. b 51. b Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch1 52. d 53. b 54. a 55. d 56. a 57. d 58. b 59. c 60. b 61. a 62. c 63. b 64. d 65. b 66. b 67. a 68. b 69. c 70. d 71. d 72. b 73. b 74. c 75. d 76. b Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch1 77. d 78. c 79. c

Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch2

Indicate the answer choice that best completes the statement or answers the question. 1. The “building blocks” that Java programmers use to write computer programs are called _______. a. windows b. objects c. internal data d. entities 2. A method is a sequence of ___ that accesses the data of an object. a. data b. objects c. instructions d. streams 3. In Java, objects within the same class share common _______. a. behavior b. data c. instructions d. comments 4. You can invoke the println and print methods on which object? a. the HelloWorld object b. the String class c. any PrintStream object d. any object in Java 5. What is a storage location in the computer's memory called that has a type, name, and contents? a. identifier b. literal c. label d. variable 6. Which term is used to describe the name of a variable, method, or class? a. type b. literal c. identifier d. label 7. Which statement about identifiers is correct? a. Identifiers are not case sensitive. b. Spaces are permitted inside identifiers. c. Identifiers can use symbols such as ? or %. d. Identifiers can be made up of letters, digits, and the underscore (_) character. Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch2 8. The camel case naming convention uses _________ at intervals in the middle of the variable name. a. uppercase letters b. digits c. dollar signs d. the underscore character 9. By convention among Java programmers, variables begin with a(n) _____________. a. uppercase letter b. digit c. lowercase letter d. dollar sign 10. By convention among Java programmers, class names begin with a(n) _____________. a. lowercase letter b. dollar sign c. digit d. uppercase letter 11. Which of the following is the best choice for a variable identifier that will store a name? a. name b. Name c. n d. nm 12. In Java, a(n) _________ specifies the kind of values that can be stored in a variable. a. literal b. class c. operator d. type 13. What is the name of the type that denotes floating-point numbers that can have fractional parts? a. double b. floatingPoint c. int d. integer 14. What is the name of the type that denotes whole numbers? a. double b. int c. whole d. integer 15. What is the name of the type that denotes a string of characters? a. Characters Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch2 b. char c. charString d. String 16. Which of the following declares a variable that will store a welcome message? a. String welcome; b. double welcome; c. Char welcome; d. int welcome; 17. Which of the following declares a variable that will store a measurement with fractional parts? a. int measure; b. double measure; c. String measure; d. integer measure; 18. Which of the following declares a variable that will store a count with an integer value? a. integer count; b. double count; c. String count; d. int count; 19. In Java, a comment on a line begins with which characters? a. '' b. // c. () d. " " 20. What term is used to refer to text in a program that is an explanation for human readers of the code? a. methods b. comments c. constants d. [* and *] 21. The Java compiler ignores any text between ____. a. (* and *) b. /* and */ c. {* and *} d. // and // 22. What is the name of the = operator in Java? a. inequality b. assignment c. identity Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch2 d. equality 23. What is the purpose of the assignment operator? a. to check for inequality b. to check for identity c. to check for equality d. to change the value of a variable 24. Which statement stores an integer value in a variable? a. count = 5; b. count = 5.0; c. count == 5; d. count != 5; 25. Which statement declares and stores an integer value in a variable? a. count = 5; b. int count = 5; c. integer count = 5; d. String count = 5; 26. Assuming that the variable count has been declared as type int, which statement changes the value of count? a. count = 6; b. count == 6; c. integer count = 6; d. count = 6.0; 27. Assume that the variable count has been declared as type int. Which statement adds 10 to count? a. count = 10; b. count == count + 10; c. count = count + 10; d. count + 10; 28. Which of the following code fragments will cause an error? a. String greeting = "Hello, Dave!"; b. String greeting = "Hello, World!"; int n = greeting.length(); c. int luckyNumber; System.out.println(luckyNumber); d. PrintStream printer = System.out;

29. What is an object? a. A sequence of instructions. b. Any value stored in a variable. c. An entity in your program that is manipulated by calling methods. d. Any input to a method. Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch2 30. The type of an object is given by its ______ ? a. variable b. method c. reference d. class 31. "System.out" is an example of which class? a. String b. Println c. System d. PrintStream 32. Which of the following statements about objects is correct? a. An object defines the methods for a class. b. Every object belongs to a class. c. An object is a sequence of instructions. d. All entities, even numbers, are objects. 33. If greeting is a String object, which method call is incorrect? a. greeting.length() b. greeting.toLowerCase() c. greeting.toUpperCase() d. greeting.println() 34. What is the term used to specify the collection of things you can do with objects that belong to a class? a. private interface b. public interface c. private implementation d. hidden implementation 35. A method name is ____________________ if a class has more than one method with that name (but different parameter types). a. overridden b. overimplemented c. overwhelmed d. overloaded 36. The input to a method is called a(n) _______________. a. overloaded b. argument c. interface d. procedure 37. Which statement about methods is true? Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch2 a. A method must return a value b. The return value of a method must be stored in a variable c. Some methods carry out an action; others return a value d. All methods require multiple arguments 38. Input to a method, enclosed in parentheses after the method name, is known as ______________. a. implicit parameters b. interfaces c. arguments d. return values 39. Which method call represents the invocation of a method that does not have arguments? a. greeting.replace("Hello", "Welcome"); b. greeting.length c. greeting.length() d. System.out.println(greeting); 40. The value calculated by a method is called its _____ value. a. implicit b. explicit c. argument d. return 41. Which of the following statements about methods is correct? a. A method can have only one argument. b. The return value of a method can be used as an argument to another method. c. Every method must have a return value. d. A method can have multiple arguments. 42. Which of the following method calls illustrate using the return value of a method as an argument? a. greeting.length(); b. greeting.println("Hello"); c. System.out.println(length.greeting()); d. System.out.println(greeting.length()); 43. If greeting refers to a String object, which of the following is a syntactically correct Java statement? a. System.out.println(length().greeting); b. System.out.println(greeting()); c. System.out.println(greeting.length()); d. greeting.println("Hello"); 44. What is the declared return type for a method that does not have a return value? a. String b. There is no declared return type when a method does not return a value. Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch2 c. void d. A method must return a value. 45. Which of the following represents a method declaration with a void return type? a. public void setValue(int value) { ... } b. public void int getValue() { ... } c. void public setValue(int value) { ... } d. void int getValue() { ... } 46. Which of the following represents a method call to a method with a void return type? a. greeting.toUpperCase() b. System.out.println() c. greeting.replace("Hello","World") d. greeting.length() 47. Which of the following statements about methods is correct? a. A method is a sequence of instructions that could access the data of an object b. A method name is unique across the entire program. c. A method can be called on any object in any class. d. Methods are stored in variables. 48. Which of the following statements about classes is correct? a. By convention, class names begin with a lowercase letter. b. A class declares the methods that you can apply to its objects. c. All entities, even primitive numbers, are classes. d. A class is a sequence of instructions that accesses the data of an object. 49. Which is not a method of the String class? a. length b. toUpperCase c. toLowerCase d. println 50. Which operator constructs object instances? a. new b. instanceof c. void d. construct 51. Which of the following constructs a Circle of radius 3, assuming the construction parameter is the radius value? a. Circle(3).new b. new Circle(3) c. new.Circle(3) d. Circle(3) Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch2 52. Which statement declares a variable that references a Circle of radius 3, assuming the construction parameter is the radius value? a. Circle c = Circle(3) b. Circle c = new Circle(3); c. Circle c.new.Circle(3); d. c.Circle(3); 53. Which statement calls a constructor with no construction arguments? a. Circle c = new Circle(); b. A call to a constructor must have construction arguments. c. Circle c = new Circle; d. Circle c = Circle() 54. What terminology describes a method that returns information about an object and does not change the object's internal data? a. mutator b. accessor c. void d. public 55. Which term describes a method of an object that modifies that object’s internal data? a. public b. void c. mutator d. accessor 56. Which of the following is a mutator method for the Rectangle class? a. getHeight b. translate c. getWidth d. isEmpty 57. What does API stand for? a. Applet Programming Interface b. Application Programmer Interaction c. Application Programming Instance d. Application Programming Interface 58. A(n) _____________ is a collection of classes with a related purpose. a. package b. import c. method d. collection Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch2 59. To use a class in another package you need to ________ it. a. export b. overload c. rewrite d. import 60. Which package is automatically imported in any Java program? a. java.system b. java.lang c. java.language d. java.util 61. Which class is part of the java.lang package? a. Rectangle b. PrintStream c. String d. Circle 62. Which import statement allows for the use of the Rectangle class? a. import java.geom.Rectangle2D; b. import java.geom.Rectangle; c. import java.geom.RectangularShape; d. import java.awt.Rectangle; 63. Which method could you use to obtain the string "1234567890" from the string "123-456-7890"? a. isEmpty b. replace c. trim d. length 64. Which of the following statements about test programs is true? a. Test programs verify that methods have been implemented correctly. b. A tester class does not contain the main method. c. You do not have to display the expected results. d. Writing test programs is not an important skill. 65. What is the purpose of a test program? a. The test program confirms that the Java compiler is correct. b. The test program verifies that methods have been implemented correctly. c. The test program checks the syntax of each object's methods. d. The test program enforces that the types between arguments match correctly. 66. Which of the following terms denotes the memory location of an object? a. implicit parameter Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch2 b. mutator method c. encapsulation d. object reference 67. What do object variables store? a. objects b. classes c. object references d. numbers 68. Assuming the following Java statement:

Circle c1 = new Circle(3); What does the variable c1 store? a. The constructed Circle object itself. b. A reference to the Circle class. c. A reference to the constructed Circle object. d. The numeric value 3. 69. Assuming the following Java statement:

int num = 10; What does the variable num store? a. The memory location where the value 10 is stored. b. A reference to the int primitive type. c. An object representing the number 10. d. The numeric value 10. 70. Assume the class Circle has an accessor called getRadius and a mutator called setRadius. What is the output of the following code?

Circle c1 = new Circle(3); Circle c2 = c1; c1.setRadius(4); System.out.println(c2.getRadius()); a. 4 b. 3 c. 6 d. 8 71. What is the output of the following code:

Circle c1 = new Circle(3); Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch2

Circle c2 = new Circle(3); c1.setRadius(4); System.out.println(c2.getRadius()); a. 3 b. 8 c. 6 d. 4 72. What is the output of the following code:

int num1 = 6; int num2 = num1; num2 = num2 + 10; System.out.println(num1); a. 6 b. 10 c. 4 d. 16 73. What is the output of the following code:

int num1 = 6; int num2 = 10; num1 = num2; num2 = num1; System.out.println(num1 + ", " + num2); a. 6, 10 b. 10, 6 c. 6, 6 d. 10, 10 74. What is the output of the following code:

int num1 = 6; int num2 = 10; num1 = num1 + num2; num2 = num1 + num2; System.out.println(num1 + ", " + num2); a. 6, 10 b. 16, 16 c. 16, 22 d. 16, 26 Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch2 75. Complete this code fragment to ensure that the frame is shown:

JFrame frame = new JFrame(); a. frame.setVisible(true); b. frame.visible = true; c. JFrame.setVisible(); d. frame.setVisible(); 76. The setVisible method of the JFrame class returns what kind of argument? a. The setVisible method does not return a result. b. The setVisible method returns an integer value. c. The setVisible method returns a String object. d. The setVisible method returns a JFrame object. 77. Based on the following code, which of the following statements sets the frame to a width of 400 and a height of 200:

final int FRAME_WIDTH = 400; final int FRAME_HEIGHT = 200; JFrame frame = new JFrame(); a. frame.size = (FRAME_WIDTH, FRAME_HEIGHT); b. frame.addSize(FRAME_WIDTH, FRAME_HEIGHT); c. frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); d. frame.setSize(FRAME_HEIGHT, FRAME_WIDTH); 78. Based on the following statement, which of the following statements sets the title of the frame:

JFrame frame = new JFrame(); a. frame.title = "An Empty Frame"; b. frame.setTitle(JFrame.EMPTY); c. frame.addTitle("An Empty Frame"); d. frame.setTitle("An Empty Frame"); 79. What is the nickname for the graphical user interface library in Java? a. Applet b. GUI c. JComponent d. Swing 80. Drawing instructions should be placed inside the ____ method, which is called whenever the component needs to be repainted. a. paintComponent b. draw c. paint Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch2 d. drawComponent 81. Complete the following statement, which constructs an ellipse.

Ellipse2D.Double ellipse = new ____________________ (x, y, width, height); a. Double.Ellipse2D b. Ellipse2D.Double c. Ellipse2D d. Double 82. In the code below, write a statement that sets the graphic to green.

public class ItalianFlagComponent extends JComponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; . . . ____ . . . } } a. g2.setColor(GREEN); b. g2.SetColor(0, 255, 0); c. g2.setColor(Color.GREEN); d. g2.setColor("GREEN");

Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch2 Answer Key 1. b 2. c 3. a 4. c 5. d 6. c 7. d 8. a 9. c 10. d 11. a 12. d 13. a 14. b 15. d 16. a 17. b 18. d 19. b 20. b 21. b 22. b 23. d 24. a 25. b Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch2 26. a 27. c 28. c 29. c 30. d 31. d 32. b 33. d 34. b 35. d 36. b 37. c 38. c 39. c 40. d 41. b 42. d 43. c 44. c 45. a 46. b 47. a 48. b 49. d 50. a 51. b Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch2 52. b 53. a 54. b 55. c 56. b 57. d 58. a 59. d 60. b 61. c 62. d 63. b 64. a 65. b 66. d 67. c 68. c 69. d 70. a 71. a 72. a 73. d 74. d 75. a 76. a Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch2 77. c 78. d 79. d 80. a 81. b 82. c

Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch3

Indicate the answer choice that best completes the statement or answers the question. 1. What mechanism does an object use to store its data? a. files b. methods c. instance variables d. access specifiers 2. Each object of a class has its own set of ___. a. methods b. instance variables c. constructors d. classes 3. An instance variable declaration consists of which of the following parts? a. the return type, the name of the method, and a list of the parameters (if any). b. an access specifier, the type of the instance variable, and the name of the instance variable. c. an access specifier, a list of the parameters (if any), and the body of the method. d. the type of the instance variable, an access specifier, a list of the parameters (if any), and the body of the method. 4. The access specifier in the declaration of instance variables should be ___. a. protected b. class c. public d. private 5. What statement is used to specify the value that a method gives back to its caller? a. new b. public c. private d. return 6. Which statement about private instance variables is true? a. They can only be accessed by methods of a different class b. They can only be accessed by methods of the same class c. They cannot be accessed by methods of the same class d. They can only be accessed by the constructor of the class 7. What is the name of the instance variable for a Counter object? a. getValue b. click c. concertCounter d. value Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch3 8. Encapsulation allows a programmer to use a class without having to know its ____. a. interface b. name c. methods d. implementation 9. The black boxes from which a program is manufactured are called ___. a. objects b. access specifiers c. methods d. instance variables 10. Which term means the process of hiding object data and providing methods for data access? a. documentation b. encapsulation c. instantiation d. abstraction 11. Which statement describes a central benefit of information hiding? a. Easier to change the private implementation b. Easier to change the method headers c. Easier to change the name of the class d. Easier to change the public interface 12. Which of the following declares a sideLength instance variable for a Square class that stores an integer value? a. private integer sideLength; b. private int sideLength; c. public integer sideLength; d. public static int sideLength; 13. A method header consists of which of the following parts? a. the return type, the name of the method, and a list of the parameters (if any) b. an access specifier, the type of the instance variable, and the name of the instance variable c. the type of the instance variable, an access specifier, and a list of the parameters (if any) d. an access specifier, a return type, a method name, and a list of the parameters (if any) 14. Which part of a class implementation contains the instructions to initialize an object's instance variables? a. constructor b. access specifier c. initializer d. type name 15. What is the return type of the println method of the PrintStream class? a. void Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch3 b. public c. String d. double 16. What is the return type of a constructor? a. void b. A constructor does not have a return type. c. private d. public 17. A class declaration consists of which of the following parts? a. an access specifier, the keyword class, the name of the class, declarations for instance variables, constructors, and methods b. an access specifier, a return type, a method name, a list of the parameters (if any), and the body of the method c. the name of the class, declarations for instance variables, constructors, and methods d. an access specifier, the name of the class, a list of the parameters (if any), and the body of the constructor 18. The class constructor always has the same name as __. a. access specifier b. class c. instance variable d. parameter variable 19. Which of the following corresponds to a valid constructor header for the Player class? a. public Player() b. public int Player c. public void Player() d. private void Player() 20. Which of the following statements is true about constructors? a. Providing a constructor for a class is optional. b. You can only provide one constructor for a class. c. The body of the constructor must initialize all instance variables or the constructor will not successfully compile. d. A constructor has a void return type. 21. Which of the following is a valid constructor header for the Player class that accepts the player name as a parameter? a. public void Player(String playerName) b. private Player(playerName) c. private void Player(playerName) d. public Player(String playerName) 22. Consider the following code to declare a constructor for the Player class: Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch3

public void Player(String playerName) { name = playerName; } Which statement is true? a. The code compiles successfully and results in the instantiation of a Player object when called. b. The code compiles successfully but results in a logic error in the code that calls the method. c. The code does not compile. d. The code compiles successfully but results in a run-time error in the code that calls the constructor. 23. The public constructors and methods of a class form the public _____ of the class. a. interface b. initialization c. implementation d. encapsulation 24. What are the operations that any programmer can use to create and manipulate objects of the class called? a. public implementation b. public interface c. private implementation d. private interface 25. We want to change the BankAccount class so that all accounts will have a monthly fee. Which of the following will properly define the instance variable monthlyFee that holds the monthly fee? a. monthlyFee: double; b. instance var monthlyFee; c. private double monthlyFee; d. private field monthlyFee; 26. Which of the following corresponds to the getArea method header for a Square class assuming an integer value for a side length? a. public int getArea b. public integer getArea c. public int getArea() d. public integer getArea() 27. What is the purpose of a clean and concise design for an object's public interface? a. Allows the compiler to function more efficiently. b. Supports cross-platform independence. c. Allows programmers to design solutions using the object without needing to know the details of the class implementation. d. Eliminates the need to provide any documentation in the code. Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch3 28. The javadoc utility is used to a. assist the compiler in checking the syntax of the Java program. b. ensure that comments are appropriately descriptive. c. automatically generate HTML pages that describe classes. d. convert the Java program into machine-executable code. 29. Which special delimeter is used with the javadoc utility to document method arguments? a. /** b. @param c. @return d. @javadoc 30. Why is it a good idea for a programmer to write comments about a method first, before implementing it? a. It is a good idea for complex methods, but not simple ones. b. It can help to assign good variable names. c. Without comments it is not possible to compile the code. d. It is an excellent test to ensure that the programmer firmly understands what is needed. 31. Consider the following method comment and method header:

/** Converts from a source measurement to a target measurement. @param _______________ the measurement @return the input value converted to the target unit */ public double convertTo(double fromMeasurement) { . . . } Fill in the blank. a. return b. fromMeasurement c. double d. convertTo 32. . Consider the following method comment and method header:

/** Converts from a source measurement to a target measurement. __________ fromMeasurement the measurement @return the input value converted to the target unit */ public double convertTo(double fromMeasurement) { . . . } Fill in the blank. a. @param b. param c. @parameter Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch3 d. parameter 33. Consider the following method comment and method header:

/** Converts from a source measurement to a target measurement. @param fromMeasurement the measurement __________ the input value converted to the target unit */ public double convertTo(double fromMeasurement) { . . . } Fill in the blank. a. return double b. return c. @return double d. @return 34. What is the name of the utility that formats comments into a set of documents that you can view in a Web browser? a. javadoc b. javac c. javad d. java 35. What is the name of the constructor for the BankAccount class? a. BankAccount b. deposit c. balance d. withdraw 36. We want to change the BankAccount class so that all accounts will have a monthly fee. The instance variable monthlyFee will hold the monthly fee. Which of the following constructors properly sets the monthly fee to a default value of 20? a. public BankAccount (double initialBalance) {

balance = initialBalance; monthlyFee = 20; } b. public BankAccount (double initialBalance) { balance = initialBalance; double monthlyFee = 20; } c. public BankAccount (double initialBalance) { balance = initialBalance; monthlyFee = initialBalance - 20; } Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch3 d. public BankAccount (double initialBalance) {

balance = initialBalance - 20; }

37. We want to change the BankAccount class so that all accounts will have a monthly fee. The instance variable monthlyFee will hold the monthly fee. Which of the following is the correct public interface for a constructor that sets both the initial balance and monthly fee? a. public BankAccount (double initialBalance, monthlyFee) b. public BankAccount (double initialBalance, double monthlyFee) public BankAccount (double initialBalance) has c. monthlyFee d. public BankAccount (double initialBalance) { double monthlyFee; // The rest of the constructor code follows }

38. We want to change the BankAccount class so that all accounts will have a monthly fee. The instance variable monthlyFee will hold the monthly fee. Which of the following methods deducts the value of the monthly fee from the account? a. public void chargeFee() {

balance = balance – monthlyFee; } b. public void chargeFee() { initialBalance = initialBalance - monthlyFee; } c. public void chargeFee() { balance = monthlyFee; } d. public void chargeFee() { balance - monthlyFee; }

39. We want to create a class that represents a geometric sequence. A geometric sequence is a sequence of numbers that begin at some value and then multiplies each value by some constant to get the next value. For example, the geometric sequence 1, 2, 4, 8, 16 starts at 1 and multiplies each term by 2 to get the next. The geometric sequence 10.8, 5.4, 2.7, 1.35 starts at 10.8 and multiplies each term by 0.5 to get the next. The basic framework of a geometric sequence class is below:

public class GeometricSequence { private double currentValue; private double multiplier; } We want to create a geometric sequence using code like: Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch3

GeometricSequence first = new GeometricSequence (1, 2); // Creates 1, 2, 4, 8, 16… GeometricSequence second = new GeometricSequence (10.8, 0.5); // Creates 10.8, 5.4, 2.7, 1.35 … Which of the constructor specifications below will allow this code to behave as desired? a. public void GeometricSequence(double initial, double mult) b. public GeometricSequence init(double initial, double mult) c. public GeometricSequence GeometricSequence(double initial, double mult) d. public GeometricSequence(double initial, double mult) 40. We want to create a class that represents a geometric sequence. A geometric sequence is a sequence of numbers that begin at some value and then multiplies each value by some constant to get the next value. For example, the geometric sequence 1, 2, 4, 8, 16 starts at 1 and multiplies each term by 2 to get the next. The geometric sequence 10.8, 5.4, 2.7, 1.35 starts at 10.8 and multiplies each term by 0.5 to get the next. The basic framework of a geometric sequence class is below:

public class GeometricSequence { private double currentValue; private double multiplier; } Assume that the parameters to the constructor are initial and mult. What should the body of the constructor be? a. currentValue = initial; multiplier = mult; b. initial = currentValue; mult = multiplier; c. double currentValue = initial; double multiplier = mult; d. double initial = currentValue; double mult = multiplier;

41. We want to create a class that represents a geometric sequence. A geometric sequence is a sequence of numbers that begin at some value and then multiplies each value by some constant to get the next value. For example, the geometric sequence 1, 2, 4, 8, 16 starts at 1 and multiplies each term by 2 to get the next. The geometric sequence 10.8, 5.4, 2.7, 1.35 starts at 10.8 and multiplies each term by 0.5 to get the next. The basic framework of a geometric sequence class is below:

public class GeometricSequence { private double currentValue; private double multiplier; } We want to create a geometric sequence using code like:

GeometricSequence first = new GeometricSequence (1, 2); // Creates 1, 2, 4, 8, 16… Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch3

GeometricSequence second = new GeometricSequence (10.8, 0.5); // Creates 10.8, 5.4, 2.7, 1.35 … We want to produce elements of the geometric sequence using code like:

System.out.println (first.next()); // System.out.println (first.next()); // System.out.println (first.next()); // System.out.println (first.next()); // System.out.println (second.next()); System.out.println (second.next()); System.out.println (second.next());

Prints 1 and advances Prints 2 and advances Prints 4 and advances Prints 8 and advances

//Prints 10.8 and advances //Prints 5.4 and advances //Prints 2.7 and advances

Which of the method specifications below will allow this code to behave as desired? a. public next() : double b. public int next() c. public void next(double result) d. public double next() 42. We want to create a class that represents a geometric sequence. A geometric sequence is a sequence of numbers that begin at some value and then multiplies each value by some constant to get the next value. For example, the geometric sequence 1, 2, 4, 8, 16 starts at 1 and multiplies each term by 2 to get the next. The geometric sequence 10.8, 5.4, 2.7, 1.35 starts at 10.8 and multiplies each term by 0.5 to get the next. The basic framework of a geometric sequence class is below:

public class GeometricSequence { private double currentValue; private double multiplier; } We want to create a geometric sequence using code like:

GeometricSequence first = new GeometricSequence (1, 2); // Creates 1, 2, 4, 8, 16… GeometricSequence second = new GeometricSequence (10.8, 0.5); // Creates 10.8, 5.4, 2.7, 1.35 … We want to produce elements of the geometric sequence using code code like:

System.out.println (first.next()); // Prints 1 and advances System.out.println (first.next()); // Prints 2 and advances System.out.println (first.next()); // Prints 4 and advances System.out.println (first.next()); // Prints 8 and advances System.out.println (second.next()); System.out.println (second.next()); Powered by Cognero

//Prints 10.8 and advances //Prints 5.4 and advances Page 9


Name:

Class:

Date:

testbank-bj-7-ch3

System.out.println (second.next());

//Prints 2.7 and advances

What should the body of the next method be? a. double result = currentValue;

currentValue = currentValue * multiplier; return result; b. return currentValue; currentValue = currentValue * multiplier; c. double result = currentValue; multiplier = currentValue * multiplier; return result; d. currentValue = currentValue * multiplier; return currentValue;

43. Descriptive text used to communicate design and implementation issues about the classes and public methods of programs is called _______? a. components b. comments c. constants d. commands 44. If a method has two parameters, one explicit and one implicit, and a return type of void, then the documentation comments should include: a. One @param statement, and one @return statement b. Two @param statements, and one @return statement c. One @param statement, and no @return statement d. Two @param statements, and no @return statement 45. You should provide documentation comments for ___. a. only classes b. only methods with parameters c. every class, every method, every parameter, and every return value d. only methods with return values 46. When you declare a method, you also need to provide the method ____, which consists of statements that are executed when the method is called. a. body b. header c. return type d. access specifier 47. The private implementation of a class consists of ___. a. instance variables and the method headers b. local variables and the method headers c. parameter variables and the method bodies d. instance variables and the implementation of the constructors and methods Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch3 48. Which line of code is part of the private implementation of the BankAccount class? a. public BankAccount() b. balance = balance - amount; c. public void deposit(double amount) d. public void withdraw(double amount) 49. Which line of code is part of the public implementation of the BankAccount class? a. balance = balance + amount; b. balance = balance - amount; c. public BankAccount(double initialBalance) d. return balance; 50. Fill in the blank in the following method comment.

/** Deposits money into the bank account @param _________ the amount to deposit */ public void deposit(double amount) { balance = balance + amount; } a. amount b. balance c. double amount d. money 51. Given this method comment, fill in the blank in the method implementation.

/** Deposits money into the bank account @param amount the amount to deposit */ public _____ deposit(double amount) { balance = balance + amount; } a. double b. void c. return d. null 52. Given this method implementation, fill in the blank in the method comment. Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch3

/** Withdraws money from the bank account _________ amount the amount to withdraw */ public void withdraw(double amount) { balance = balance - amount; } a. parameter b. @param c. param d. @parameter 53. Given this method comment, fill in the blank in the method implementation.

/** Constructs a bank account with a given balance @param initialBalance the initial balance */ public BankAccount(double _________) { balance = initialBalance; } a. amount b. parameter c. initialBalance d. balance 54. Given this method implementation, fill in the blank in the method comment.

/** Gets the current balance of the bank account _________ the current balance */ public double getBalance() { return balance; } a. return b. double c. @return d. balance Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch3 55. Given this method comment, fill in the blank in the method implementation.

/** Gets the current balance of the bank account @return the current balance */ public double getBalance() { __________ balance; } a. balance b. @return c. double d. return 56. Choose the method header that goes with this method comment.

/** Raises the salary of the employee @param percentRaise salary percentage raise */ a. public void raiseSalary(double percent) b. public double raiseSalary(double percent) c. public double raiseSalary(double percentRaise) d. public void raiseSalary(double percentRaise) 57. Consider the following method header for an Employee class:

public void raiseSalary(double percentRaise) { ______________________________________ } Fill in the blank in the method body with the implementation that will change the instance variable salary to reflect the employee's new salary after applying the raise: a. salary = salary * (1 + percentRaise); b. salary = salary * percentRaise; c. salary = salary * raise; d. salary = salary * (1 + raise); 58. Choose the method header that goes with this method comment.

/** Gets the salary of the employee @return the salary of the employee Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch3

*/ a. public void getSalary() b. public void getSalary c. public double getSalary() d. public double getSalary 59. Consider the following method header:

/** Adds interest to the bank account _________________________________ */ public void addInterest(double rate) . . . Fill in the blank in the javadoc comment: a. @param rate the rate of interest b. @parameter rate the rate of interest c. @param interestRate the rate of interest d. @parameter interestRate the rate of interest 60. Consider the following method header for the BankAccount class:

public void addInterest(double rate) { ______________________________________ } Fill in the blank in the method body. a. balance = balance * (1 + rate); b. balance = balance * rate; c. balance = balance * (1 + interestRate); d. balance = balance * interestRate; 61. Fill in the blank in the comment for this method header.

/** Gets the interest for the bank account _________________________________ */ public double getInterest() . . . a. @return double the interest b. return the interest c. @return the interest Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch3 d. return double the interest 62. Fill in the blank in the comment for this method header.

/** Constructs a player with the given name _________________________________ */ public Player(String playerName) . . . a. @return the player b. @parameter playerName the name of the player c. @param playerName the name of the player d. return the player 63. Which of the following corresponds to the constructor body for a Square class that accepts an initial side length value called initialLength where the instance variable is named sideLength? a. sideLength = initialLength; b. initialLength = sideLength; c. initialLength = 0; d. sideLength = 0; 64. Which of the following corresponds to the getArea method body for a Square class where the instance variable is named sideLength? a. return sideLength; b. return area; c. return width * height; d. return sideLength * sideLength; 65. The code below for the mutator method public void setLength(double length) of the Square class is intended to set the value of the sideLength instance variable to the parameter variable of the method. Which line of code avoids the common error of ignoring the parameter variables of a method? a. sideLength = 54; b. return sideLength; c. sideLength = length; d. double thisLength = length; 66. What verifies that a class works correctly in isolation, outside a complete program? a. unit test b. encapsulation c. abstraction d. enumeration 67. What is a tester class? Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch3 a. A class that constructs objects. b. A class that invokes one or more methods. c. A class that is named Tester. d. A class with a main method that contains statements to run methods of another class. 68. Complete the following tester program by choosing the line that prints the expected outcome.

public class BankAccountTester { public static void main(String[] args) { BankAccount account = new BankAccount(1000); account.deposit(account.getBalance()); System.out.println(account.getBalance()); ___________________ } } a. System.out.println("Expected: 1000"); b. System.out.println("Expected: 2000"); c. System.out.println("Expected: 2000") d. println("Expected: 2000"); 69. Fill in the first line of this SquareTester program so that it declares and initializes a variable mySquare as an instance of a Square class with a side length of 6.

public class SquareTester { public static void main(String[] args) { /* Step 1: declare and initialize a variable mySquare as an instance of a Square class with a side length of 6 */ _____________________________________ /* Step 2: print out the area of the object referenced by the variable mySquare using the getArea method */ /* Step 3: print the expected outcome */ } } a. Square mySquare = new Square(6); b. mySquare = new Square(6); Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch3 c. mySquare = Square(6); d. Square mySquare = Square(6); 70. Fill in the third line of this SquareTester program so that it prints out the expected outcome.

public class SquareTester { public static void main(String[] args) { /* Step 1: declare and initialize a variable mySquare as an instance of a Square class with a side length of 6 */ /* Step 2: print out the area of the object referenced by the variable mySquare using the getArea method */ /* Step 3: print the expected outcome */ _____________________________________ } } a. System.out.println("Expected: 12"); b. System.out.println("Expected: 6"); c. System.out.println("Expected: 36"); d. System.out.println("Expected: 18"); 71. When tracing the execution of an object by hand, what is one way to indicate the change of an instance variable when a mutator method is executed? a. Add a new index card for each change. b. Cross out the old value and write down the new value. c. Turn the card over and check the "mutator" box. d. Put a check mark in the upper left corner of the index card. 72. When using index cards to help with the tracing of the execution of an object by hand, what is written on the front of the card? a. The names of all known tester classes for the object. b. The key equations implemented by the constructor. c. A table with the values of all of the instance variables. d. The methods that the object can execute. 73. When using index cards to help with the tracing of the execution of an object by hand, what is written on the back of the card? a. The names of all known tester classes for the object. Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch3 b. The key equations implemented by the constructor. c. A table with the values of all of the instance variables. d. The methods that the object can execute. 74. What is a local variable? a. A variable that is declared in the header of a class. b. A variable that is declared in the body of the class. c. A variable that is declared in the header of a method. d. A variable that is declared in the body of a method. 75. What is a parameter variable? a. A variable that is declared in the header of a method. b. A variable that is declared in the body of the class. c. A variable that is declared in the body of a method. d. A variable that is declared in the header of a class. 76. When a method exits, its ____ are removed. a. local variables b. classes c. comments d. instance variables 77. Where do parameters and local variables belong? a. in an object b. in a class c. in a method d. in a package 78. Where are instance variables properly declared? a. the body of an object b. the constructor of a class c. the body of any method d. in a package 79. What is the name of the parameter variable of the recordPurchase method of the CashRegister class? a. amount b. payment c. purchase d. change 80. What is the name of the local variable of the giveChange method of the CashRegister class? a. amount b. change c. payment Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch3 d. purchase 81. Which of the following is an instance variable of the CashRegister class? a. amount b. balance c. change d. purchase 82. When are instance variables initialized? a. Instance variables are initialized when the method is called. b. Instance variables are initialized with a default value before a constructor is invoked. c. You must initialize instance variables in the constructor. d. You must initialize instance variables in a method body. 83. Given the following constructor for the BankAccount class, which references the instance variable balance declared to be of type double, what output is generated by a call to new BankAccount()?

public BankAccount() { System.out.println(balance); } a. The code fragment has a syntax error and does not compile. b. 1000.0 c. 0.0 d. You cannot print out the value of an uninitialized instance variable. 84. When are local variables initialized? a. Local variables are initialized with a default value before a constructor is invoked. b. Local variables are initialized when the method is called. c. You must initialize local variables in a method body. d. You must initialize local variables in the constructor. 85. Assuming the following code is the body of the main method, what output is generated?

BankAccount myAccount; System.out.println(myAccount.getBalance()); a. The code fragment does not compile because the local variable is not initialized. b. 0.0 c. The code fragment has a syntax error and does not compile. d. 1000.0 86. Assuming the following code is the body of the deposit method, what output is generated by the valid call myAccount.deposit(1000) for an account with an initial balance of 500? Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch3

public void deposit(double amount) { System.out.println(amount); double newBalance = balance + amount; balance = newBalance; } a. 1500.0 b. The code fragment has a syntax error and does not compile. c. The code fragment does not compile because the parameter variable is not initialized. d. 1000.0 87. Instance variables that are object references are initialized to what default value? a. empty b. Instance variables are not initialized to a default value. c. null d. nil 88. Instance variables that are numbers are initialized to what default value? a. Instance variables are not initialized to a default value. b. nil c. 0 d. null 89. Which of the following denotes the implicit parameter? a. void b. this c. extends d. public 90. A method is invoked on what type of parameter? a. public parameter b. explicit parameter c. private parameter d. implicit parameter 91. The use of an instance variable name inside a method denotes the instance variable of what? a. the parameter variable b. the access specifier c. the explicit parameter d. the implicit parameter 92. Identify the explicit parameter of the withdraw method of the BankAccount class. a. public Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch3 b. double c. balance d. amount 93. In the statement below, amount is referred to as the ____ parameter.

public void deposit(double amount) a. private b. public c. explicit d. implicit 94. Consider the following invocation of the deposit method:

mySavings.deposit(250); What is the implicit parameter? a. deposit b. mySavings c. 250 d. There is no implicit parameter. 95. Consider the following invocation of the deposit method:

mySavings.deposit(250); What is the explicit parameter? a. There is no explicit parameter. b. deposit c. 250 d. mySavings 96. Consider the constructor of the BankAccount class that has a parameter for the initial balance. Which line of code is equivalent to this constructor body?

balance = initialBalance; a. this.balance = initialBalance; b. this.initialBalance = balance c. balance = this.initialBalance; d. this.balance = this.initialBalance; 97. Which statement is true about the following constructor of the BankAccount class?

public BankAccount(double balance) { Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch3

this.balance = balance; } a. The code has a syntax error. b. The code has a logic error. c. You can't have an instance variable and a parameter variable with the same name. d. The code sets the instance variable balance to the parameter variable balance. 98. When drawing complex shapes, what is used to initialize the position of the shape? a. constructor b. viewer c. component d. frame 99. Consider the following code fragment from the Italian Flag program in How To 3.2:

public class ItalianFlagComponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2d) g; ItalianFlag flag = new ItalianFlag(100, 100, 90); flag.draw(g2); } } Which of the following statements is true? a. It is impossible to construct an ItalianFlagComponent because no constructor is implemented. b. It is impossible to add an ItalianFlagComponent object to a frame because the class does not extend JComponent. c. The code will not compile because it should have called g2.draw(flag); d. The code has a syntax error and will not compile. 100. If the CarComponent class had the call below added to it, where will car3 be placed?

int y3 = (getHeight() - 30)/2; Car car3 = new Car(0, y3); car3.draw(g2); a. At the middle of the right side of the window b. At the middle of the left side of the window c. At the middle of the top of the window d. At the middle of the bottom of the window 101. Which lines would need to be added to CarComponent to put car3 at the middle of the left side of the window? a. int y3 = (getHeight() - 30)/2; Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch3 Car car3 = new Car(0, y3); car3.draw(g2); b. int x3 = (getHeight() - 30)/2; Car car3 = new Car(x3, 0); car3.draw(g2); c. int y3 = (getWidth() - 30)/2; Car car3 = new Car(0, y3); car3.draw(g2); d. int x3 = (getWidth() - 30)/2; Car car3 = new Car(x3, 0); car3.draw(g2);

102. What will be output from the following statements that use BankAccount class?

BankAccount first = new BankAccount (100); BankAccount second = new BankAccount (100); BankAccount third = first; first.deposit (50.0); second.deposit (50.0); third.deposit (50.0); System.out.println (first.getBalance() + " " + second.getBalance() + third.getBalance()); a. 150.0 200.0 250.0 b. 150.0 150.0 150.0 c. 250.0 250.0 250.0 d. 200.0 150.0 200.0 103. What will be output from the following statements that use BankAccount class?

BankAccount first = new BankAccount (100); first.deposit (50.0); BankAccount second = new BankAccount (first.getBalance()); first.deposit (50.0); BankAccount third = new BankAccount (first.getBalance()); first.deposit (50.0); System.out.println (first.getBalance() + " " + second.getBalance() + third.getBalance()); a. 150.0 200.0 250.0 b. 250.0 250.0 250.0 c. 250.0 150.0 200.0 d. 250.0 200.0 250.0 104. Assume the method below has been added to the BankAccount class.

public void giveBonus () { Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch3

balance = balance + 5.0; } What will be output from the following statements that use the revised BankAccount class?

BankAccount premiumAccount = new BankAccount (100); premiumAccount.giveBonus (); premiumAccount.giveBonus (); premiumAccount.giveBonus (); System.out.println (premiumAccount.getBalance()); a. 110.0 b. 100.0 c. 105.0 d. 115.0 105. Assume the method below has been added to the BankAccount class.

public void transfer (BankAccount source, double amount) { balance = balance + amount; source.balance = source.balance – amount; } What will be output from the following statements that use the revised BankAccount class? BankAccount first = new BankAccount (100.0); BankAccount second = new BankAccount (300.0); first.transfer (second, 50.0); System.out.println (first.getBalance() + " " + second.getBalance()); a. 100.0 300.0 b. 150.0 250.0 c. 150.0 300.0 d. 100.0 250.0 106. We want to create a class that represents a date. A date has a day, month, and year. For example, the date March 16, 2014 has the day 16, month 3, and year 2014. The basic framework of a date class is below:

public class Date { private int day; private int month; private int year; } The default date will be set to January 1, 1990. What should the body of the constructor with zero parameters be? Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch3 a. day = 1;

month = 1; year = 1990; b. int day = 1; int month = 1; int year = 1990; c. int day = 0; int month = 1; int year = 1990; d. int day = 1; int month = 1; int year = 0;

107. We want to create a class that represents a date. A date has a day, month, and year. For example, the date March 16, 2014 has the day 16, month 3, and year 2014. The basic framework of a date class is below:

public class Date { private int day; private int month; private int year; } We want to create a specific date using code like:

Date first = new Date (16, 3, 2014); // Creates March 16, 2014 Date second = new Date (1, 9, 2013); // Creates September 1, 2013 Which of the constructor specifications below will allow this code to behave as desired? a. public void Date (int d, int m, int y) b. public init (int d, int m, int y) c. public Date (int d, int m, int y) d. public Date Date (int d, int m, int y) 108. We want to create a class that represents a date. A date has a day, month, and year. For example, the date March 16, 2014 has the day 16, month 3, and year 2014. The parameter variables in the constructor for month, day, and year should be m, d and y. The basic framework of a date class is below:

public class Date { private int day; private int month; private int year; } What should the body of the constructor be? a. day = d; Powered by Cognero

Page 25


Name:

Class:

Date:

testbank-bj-7-ch3 month = m; year = y; b. d = day; m = month; y = year; c. int day = d; int month = m; int year = y; d. day = 1; month = 1; year = 1990;

109. We want the toString method to return strings like 3/16/2014. Give the body of the toString method. a. return "m/d/y"; b. return month + "/" + day + "/" + year; c. return m + "/" + d + "/" + y; d. return "month/day/year";

Powered by Cognero

Page 26


Name:

Class:

Date:

testbank-bj-7-ch3 Answer Key 1. c 2. b 3. b 4. d 5. d 6. b 7. d 8. d 9. a 10. b 11. a 12. b 13. d 14. a 15. a 16. b 17. a 18. b 19. a 20. a 21. d 22. b 23. a 24. b 25. c Powered by Cognero

Page 27


Name:

Class:

Date:

testbank-bj-7-ch3 26. c 27. c 28. c 29. b 30. d 31. b 32. a 33. d 34. a 35. a 36. a 37. b 38. a 39. d 40. a 41. d 42. a 43. b 44. c 45. c 46. a 47. d 48. b 49. c 50. a 51. b Powered by Cognero

Page 28


Name:

Class:

Date:

testbank-bj-7-ch3 52. b 53. c 54. c 55. d 56. d 57. a 58. c 59. a 60. a 61. c 62. c 63. a 64. d 65. c 66. a 67. d 68. b 69. a 70. c 71. b 72. d 73. c 74. d 75. a 76. a Powered by Cognero

Page 29


Name:

Class:

Date:

testbank-bj-7-ch3 77. c 78. a 79. a 80. b 81. d 82. b 83. c 84. c 85. a 86. d 87. c 88. c 89. b 90. d 91. d 92. d 93. c 94. b 95. c 96. a 97. d 98. a 99. c 100. b 101. a 102. d Powered by Cognero

Page 30


Name:

Class:

Date:

testbank-bj-7-ch3 103. c 104. d 105. b 106. a 107. c 108. a 109. b

Powered by Cognero

Page 31


Name:

Class:

Date:

testbank-bj-7-ch4

Indicate the answer choice that best completes the statement or answers the question. 1. Which of the following options declares a float variable? a. Float age; b. flt age; c. float age; d. age: float; 2. What is the result of the following code snippet?

double circleRadius; double circleVolume = 22 / 7 * circleRadius * circleRadius; System.out.println(circleVolume); a. 0 b. 3.14 c. 6.28 d. compile-time error 3. What is wrong with the following code snippet?

int width = 10; height = 20.00; System.out.println("area = " + (width * height)); a. The code snippet uses an uninitialized variable. b. The code snippet uses an undeclared variable. c. The code snippet attempts to assign a decimal value to an integer variable. d. The code snippet attempts to add a number to a string variable. 4. What is wrong with the following code snippet?

int average; average = 78A; a. The average variable is never initialized. b. The data type for the average variable is not specified. c. The average variable is never assigned a value. d. The average variable is assigned a non-numeric value. 5. Which of the following guidelines will make code more explanatory for others? a. Use shorter statements and shorter variable names in source code. b. Add comments to source code. c. Avoid usage of complex calculations in source code. d. Always enclose the statements in curly braces in source code. Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch4 6. What will be the value stored in the variable x after the execution of the following code snippet?

int a = 10; int b = 20; int c = 2; int x = b / a /*c*/; a. 1 b. 2 c. 4 d. The code has a syntax error 7. Which of the following statements with comments is(are) valid? I. int cnt = 0; /* Set count to 0 II. int cnt = 0; /* Set count to 0 */ III. int cnt = 0; // Set count to 0 a. Only I b. I and II c. II and III d. Only III 8. What is wrong with the following code?

int count = 2000 * 3000 * 4000; a. Wrong data type b. Variable is undefined c. Integer overflow d. Illegal expression 9. Which one of the following variables is assigned with valid literals? a. int salary = 0; salary = 5000.50; b. int salary1 = 0; salary1 = 1.2E6; c. double salary2 = 0; salary2 = 2.96E-2; d. long salary3 = 0; salary3 = 1E-6;

10. Which of the following statements about constants is correct? a. Constants are written using capital letters because the compiler ignores constants declared in small letters. b. The data stored inside a constant can be changed using an assignment statement. c. You can make a variable constant by using the final reserved word when declaring it. d. Constant variables can only be changed through the Math library. 11. Which one of the following refers to a number constant that appears in code without explanation? Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch4 a. Constant b. Variable c. Magic number d. String literal 12. Which one of the following statements defines a constant with the value 123? a. final int MY_CONST = 123; b. const int MY_CONST = 123; c. final int MY_CONST = 0; MY_CONST = 123; d. static int MY_CONST = 123;

13. Which statement is true? a. Variables cannot be assigned and declared in the same statement b. Variable names must contain at least one dollar sign c. Variable names can be no more than 8 characters long d. It is incorrect to initialize a string variable with a number 14. Which statement about number literals in Java is false? a. Numbers in exponential notation always have type double b. Zero is an integer c. Integers must be positive d. An integer with fractional part of .0 has type double. 15. Which option represents the best choice for a variable name to represent the average grade of students on an exam? a. averageGrade b. $averageGrade c. avg d. AveGd 16. The assignment operator a. denotes mathematical equality b. places a new value into a variable c. means the same as the equals sign used in algebra d. makes it illegal to write a statement like sum = sum + 4; 17. Which of the following statements about constants in Java are true? I.Although not required, constants are commonly named using uppercase letters II.Only integer values can appear as constants III.A variable can be defined with an initial value, but the reserved word final prevents it from being changed IV.A named constant makes computations that use it clearer a. I, II, III b. II, III, IV c. I, III, IV Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch4 d. I, II, IV 18. What is the output of this code snippet?

int sum = 22; sum = sum + 2; System.out.print(sum); // sum = sum + 4; System.out.print(sum); a. 2424 b. 2425 c. 2428 d. 2528 19. What is the output of this code snippet?

double average; int grade1 = 87; int grade2 = 94; // System.out.print("The average is " + (grade1 + grade2) / 2.0); System.out.print("The average is " + average); a. Compile-time error b. The average is 91.5 c. The average is 91.5 The average is 91.5 d. The average is 91.5 The average is 0.0

20. What is the output of the following code snippet?

int counter = 0; counter++; System.out.print("The initial value of the counter is "); System.out.println(count); a. The initial value of the counter is 0 b. The initial value of the counter is 1 c. The code will not compile d. The initial value of the counter is 21. Which statements about numeric types in Java are true? I.There is more than one integer type II.The data type float uses twice the storage of double III.The numeric range of the Java integer type is related to powers of two a. I, II Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch4 b. I, III c. II, III d. I, II, III 22. The typical ranges for integers may seem strange but are derived from a. Base 10 floating-point precision b. Field requirements for typical usage and limits c. Overflows d. Powers of two because of base 2 representation within the computer 23. Which of the following options defines an integer variable? a. char age; b. integer age; c. int age; d. age: int; 24. Which statement is true about variable names in Java? a. They can contain the percent sign (%) b. They can contain an underscore symbol (“_”) c. They can contain spaces d. They must make sense as a word 25. Consider the following Java variable names: I. 1stInstance II. basicInt% III. empName_ IV. addressLine1 V. DISCOUNT Which of the following options is correct? a. Only IV is a valid Java variable name. b. Only I and IV are valid Java variable names. c. Only I, IV, and V are valid Java variable names. d. Only III, IV, and V are valid Java variable names. 26. What is the result of the following code snippet?

double bottles; double bottleVolume = bottles * 2; System.out.println(bottleVolume); a. 0 b. 1 c. 2 d. Does not compile

Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch4 27. Which one of the following is a correct method for defining and initializing an integer variable with name value? a. int value = 30; b. Int value = 30; c. int value = .30; d. Int value = .30; 28. What is wrong with the following code snippet?

int size = 42; int cost = 9.99; System.out.println("size = " + size); System.out.println(" cost = " + cost); a. The code snippet uses a variable that has not yet been initialized. b. The code snippet uses a variable that has not been declared. c. The code snippet attempts to assign a decimal value to an integer variable. d. The code snippet attempts to assign an integer value to a decimal variable. 29. Which one of the following reserved words is used in Java to represent a value without a fractional part? a. integer b. int c. Int d. Float 30. In an airline reservation system, the number of available seats in an airplane is required. Which data type should be used to store this value? a. double b. float c. int d. long 31. What is wrong with the following code snippet?

int price; price = 9.42; a. The price variable is never initialized. b. The data type for the price variable is not specified. c. The price variable is never assigned a value. d. The price variable is assigned a decimal value. 32. Which one of the following is an assignment statement? a. int a = 20; b. a = 20; c. assign a = 20; Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch4 d. assign 20 to a; 33. Which one of the following types of statements is an instruction to set the value of a variable? a. Update b. Declaration c. Assignment d. Initialization 34. What is the meaning of x = 0; in Java? a. It checks whether x equals 0. b. It sets the variable x to zero. c. It defines a variable named x and initializes it with 0. d. It is a syntax error because x is not always 0. 35. What is the value of the following expression?

2 + 3 + 5 / 2 a. 5 b. 6 c. 7 d. 7.5 36. Which is a legal number literal of type int in Java? a. 100,000 b. 100.000 c. 100_000 d. 100000L 37. What is the upper limit on the size of an integer represented by the BigInteger object in Java? a. 32,767 b. 2,147,483,647 c. 9,223,372,036,854,775,807 d. Essentially no limit 38. Why is the double type not appropriate for financial calculations? a. Roundoff errors occur when an exact representation of a floating point number is not possible. b. The range is too small. c. The calculations are too slow. d. There are too few significant digits. 39. Which of the following statements is correct about constants? a. Constants are written using uppercase letters because the compiler ignores constants declared in lowercase letters. b. The data stored inside a final variable can be changed using an assignment statement. Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch4 c. You can make a variable constant by using the constant reserved word while declaring the variable. d. Variables defined using final make a code snippet more readable and easier to maintain. 40. What is the value of the following expression?

-18 % 5 a. -2 b. -3 c. 2 d. 3 41. What is the value of the following expression?

1 % 12 a. 1 b. 0 c. -11 d. This is an error because 12 is greater than 1 42. What will be the value of the variables a and b after the given set of assignments?

int a = 20; int b = 10; a = (a + b) / 2; b = a; a++; a. a = 15, b = 16 b. a = 16, b = 16 c. a = 16, b = 15 d. a = 15, b = 15 43. What is the value of the value variable at the end of the given code snippet?

int value = 3; value = value - 2 * value; value++; a. -2 b. 0 c. 2 d. 4 44. What are the values of num1 and num2 after this snippet executes? Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch4

double num1 = 4.20; double num2 = num1 * 10 + 5.0; a. num1 = 4.20 and num2 = 42.0 b. num1 = 4.20 and num2 = 47.0 c. num1 = 42.0 and num2 = 42.0 d. num1 = 42.0 and num2 = 47.0 45. What is the result of the following expression?

double d = 2.5 + 4 * -1.5 - (2.5 + 4) * -1.5; a. 24.375 b. 6.25 c. 12.375 d. 6 46. What is the output of the following code snippet?

int value = 3; value++; System.out.println(value); a. 2 b. 3 c. 4 d. No output due to syntax error 47. What is the output of the following code snippet?

int value = 25; value = value * 2; value--; System.out.println(value); a. 25 b. 50 c. 49 d. 26 48. Which one of the following operators computes the remainder of an integer division? a. / b. % c. \ d. ! Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch4 49. What is the value of Math.pow(3, 2)? a. 6.0 b. 9.0 c. 8.0 d. 5.0 50. What is the output of the following code snippet?

double a; a = Math.sqrt(9.0) + Math.sqrt(16.0); System.out.println(a); a. 25.0 b. 337.0 c. 7.0 d. 19.0 51. Which is the Java equivalent of the following mathematical expression? c = √(a2 + b2) a. c = Math.sqrt(a * 2 + b * 2); b. c = Math.sqrt(a * 2) + Math.sqrt(b * 2); c. c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)); d. c = Math.sqrt(Math.pow(a, 2)) + Math.sqrt(Math.pow(b, 2)); 52. Which is a correct representation of the given mathematical expression in Java?

a + b _____ 2 a. a + b % 2 b. a + b / 2 c. a + (b / 2) d. (a + b) / 2 53. Which is the Java equivalent of the following mathematical expression? c = 2π × radius a. c = 2 * Math.PI * radius * 2; b. c = 2 * Math.PI * Math.pow(2, radius); c. c = 2 * Math.PI * Math.pow(radius, 2); d. c = 2 * Math.PI * radius; 54. What is the output of the following code snippet? Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch4

int s; double f = 365.25; s = f / 10; System.out.println(s); a. 36 b. 36.525 c. 37 d. No output because the code snippet generates compilation errors 55. What happens to the fractional part when a division is performed on two integer variables? a. The fractional part is rounded off to the nearest integer value. b. The fractional part is discarded. c. Two integers cannot be used in division; at least one of the operands should be a floating-point number. d. Instead of using an integer division, you should use the modulus operator to perform floating-point division. 56. Consider the following division statements: I. 22 / 7 II. 22.0 / 7 III. 22 / 7.0 Which of the following is correct? a. All three statements will return an integer value. b. Only I will return an integer value. c. Only I, II will return an integer value. d. Only I and III will return an integer value. 57. What is the output of the following code snippet?

int var1 = 10; int var2 = 2; int var3 = 20; var3 = var3 / (var1 % var2); System.out.println(var3); a. 0 b. 4 c. 20 d. There will be no output due to a run-time error. 58. Which one of the following statements gives the absolute value of the floating-point number x = -25.50? a. abs(x); b. Math.abs(x); c. x.abs(); d. x.absolute(); Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch4 59. What is the value of Math.abs(-2)? a. -2 b. 0 c. 2 d. 4 60. What is the output of the following code snippet?

double x; x = Math.pow(3.0, 2.0) + Math.pow(4.0, 2.0); System.out.println(x); a. 25.0 b. 34 c. 7.0 d. 14 61. Which is the Java equivalent of the following mathematical expression? c = (√a + √b)2 a. c = (Math.sqrt(a) + Math.sqrt(b)) * 2; b. c = Math.sqrt(a * 2) + Math.sqrt(b * 2); c. c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)); d. c = Math.pow((Math.sqrt(a) + Math.sqrt(b)), 2); 62. Which of the following is the Java equivalent of the following mathematical expression? p = 2 × π × radius3 a. p = 2 * Math.PI * (radius * 3); b. p = Math.PI * Math.pow(3,radius); c. p = 2 * Math.PI * Math.pow(radius, 3); d. p = 2 * Math.pow(Math.PI * radius, 3); 63. What will be the value of the variables x and y after the given set of assignments?

int x = 20; int y = 10; x = (x - y) * 2; y = x / 2; a. x = 40, y = 20 b. x = 20, y = 10 c. x = 10, y = 20 d. x = 20, y = 20 64. What is the value of the var variable at the end of the given code snippet?

int var = 30; Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch4

var = var + 2 / var; var++; a. 0 b. 1 c. 30 d. 31 65. What is the output of the following code snippet?

int num1 = 10; int num2 = 5; int num3 = 200; num3 = num3 % (num1 * num2); System.out.println(num3); a. 0 b. 4 c. 10 d. 250 66. One way to avoid round-off errors is to use: a. Math.sqrt() b. Math.pow() c. Math.round() d. Math.truncate() 67. What is the output of the following statement sequence?

int x = 100.0 % 6.0; System.out.println(x); a. 4 b. Compile-time error c. Run-time error d. 16 68. What is result of evaluating the following expression?

(45 / 6) % 5 a. 2 b. 7 c. 2.5 d. 3 Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch4 69. What is the difference between the result of the following two Java statements? I.int cents = (int)(100 * price + 0.5); II.int cents = (100 * price + 0.5); a. Statement I causes truncation, but II does not b. Statement II causes truncation, but I does not c. Statement I compiles, but II does not d. Statement II compiles, but I does not 70. What is the value of the following expression? 3*5/2*5 a. 1.5 b. 30 c. 35 d. 37.5 71. What is the value of Math.pow(2, 3)? a. 5.0 b. 6.0 c. 8.0 d. 9.0 72. Which is a correct representation of the given mathematical expression in Java? a. a - b / 2 % 2 b. a - b / 2 c. a - (b / 2) / 2 d. (a - b / 2) / 2 73. Given the definition final double PI = 3.14159; which of the following is the Java equivalent of the mathematical expression c = π × radius2 a. c = PI * (radius * 2); b. c = PI * Math.pow(2, radius); c. c = PI * Math.pow(radius, 2); d. c = Math.pow(PI * radius, 2); 74. Which is the mathematical equivalent of the following Java expression?

h = (4.0 * a * b - Math.pow(b, 2)) / c; a. h = 4ab - 2b / c b. h = (4ab - 2b) / c c. h = 4ab - b2/ c d. h = (4ab - b2) / c 75. When you purchase donuts, they come in boxes of 12, so 24 donuts take 2 boxes. All donuts need to be in a box, so if you buy 13 donuts, you'll get 2 boxes with 12 in the first box and 1 in the second. If the integer variable Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch4 numberOfDonuts contains the positive number of donuts purchased, which of the following will correctly give the number of boxes needed? a. int numberOfBoxes = (numberOfDonuts + 11) / 12; b. int numberOfBoxes = numberOfDonuts / 12; c. int numberOfBoxes = 1 + numberOfDonuts / 12; d. int numberOfBoxes = numberOfDonuts / 12 + numberOfDonuts % 12; 76. Which of the following statements will assign the largest value of three integer variables a, b, and c to the integer variable maximum? a. maximum = Math.max(a, b, c); b. maximum = Math.max(a, b); maximum = Math.max(b, c); maximum = Math.max(a, c); c. maximum = Math.max(a, b); maximum = Math.max(maximum, c); d. maximum = Math.max(a, b) + Math.max(b, c) +

Math.max(a, c);

77. A student's class average can be computed by dividing the number of marks they have earned by the number of marks possible. Assume the following variables have been declared as shown and given values elsewhere:

int marksEarned, marksPossible; double classPercentage; Which of the following statements will assign the correct percentage average to classPercentage? For example, if marksEarned is 725 and marksPossible is 1000, classPercentage should be assigned the value 72.5. a. classPercentage = marksEarned / marksPossible * 100.0; b. classPercentage = 100 * marksEarned / marksPossible; c. classPercentage = (100.0 * marksEarned) / marksPossible; d. classPercentage = (100.0 + marksEarned) / marksPossible; 78. Assume the following variables have been declared as shown and given values elsewhere: a. double discriminant = Math.sqrt(b * b - 4 * a * c); b. double discriminant = Math.sqrt(b * b) - 4 * a * c; c. double discriminant = Math.sqrt(b * b) - Math.sqrt(4 * a * c); d. double discriminant = Math.sqrt(b2 - 4ac) 79. Assuming that the user inputs a value of 25 for the price and 10 for the discount rate in the following code snippet, what is the output?

Scanner in = new Scanner(System.in); System.out.print("Enter the price: "); double price = in.nextDouble(); System.out.print("Enter the discount rate: "); double discount = in.nextDouble(); System.out.println("The new price is " + price - price * (discount / 100.0)); Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch4 a. The new price is 25.0 b. The new price is 15.0 c. The new price is 22.5 d. The new price is 20.0 80. Assuming that the user inputs a value of 25000 for the pay and 10 for the bonus rate in the following code snippet, what is the output?

Scanner in = new Scanner(System.in); System.out.print("Enter the pay: "); double pay = in.nextDouble(); System.out.print("Enter the bonus rate:"); double bonus = in.nextDouble(); System.out.println("The new pay is " + (pay + pay * (bonus / 100.0))); a. The new pay is 25000.0 b. The new pay is 25100.0 c. The new pay is 27500.0 d. The new pay is 30000.0 81. Which one of the following statements displays the output as 54321.00? a. System.out.printf("%8.2f", 54321.0); b. System.out.printf("%8,2f", 54321.0); c. System.out.printf(",8.2f", 54321.0); d. System.out.printf("%8.00f", 54321.0); 82. Which one of the following statements displays the output as -1.23e+02? a. System.out.printf("%5.2e", -123.0); b. System.out.printf("%5.1e", -123.0); c. System.out.printf("^5.2e", -123.0); d. System.out.printf("%5.2E", -123.0); 83. Which one of the following statements displays the output as +000321.00? a. System.out.printf("+%09.2f", 321.0); b. System.out.printf("%009,2f", 321.0); c. System.out.printf("+9.2f", 321.0); d. System.out.printf("%09.00f", 321.0); 84. What does the following statement sequence print if the user input is 123?

Scanner in = new Scanner(System.in); System.out.print("Enter a number "); int myInt = in.nextInt(); myInt += 456; Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch4

System.out.println(myInt); a. 579 b. Compile-time error c. Run-time error d. 123456 85. What does the following statement sequence print if the user input is 123?

Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); String str = in.next(); str += 456; System.out.println(str); a. 579 b. Compile-time error c. Run-time error d. 123456 86. Which of the following statements places input into the variable value given this line of code?

Scanner in = new Scanner(System.in); a. int value = in(); b. int value = in.nextInt(); c. int value = in.next(); d. int value = in.nextFloat(); 87. Assuming that the user inputs a value of 30 for the price and 10 for the discount rate in the following code snippet, what is the output?

Scanner in = new Scanner(System.in); System.out.print("Enter the price: "); double price = in.nextDouble(); System.out.print("Enter the discount rate: "); double discount = in.nextDouble(); System.out.print("The new price is "); System.out.println(price - price * (discount / 100.0)); a. The new price is 30.0 b. The new price is 20.0 c. The new price is 27.0 d. The new price is 33.0 Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch4 88. Assuming price contains the value 20.0, which of the following statements displays

price =

20.00

a. System.out.print("price = ");

System.out.printf(price); b. System.out.print("price = "); System.out.printf("%f", price); c. System.out.print("price = "); System.out.printf("%10.2f", price); d. System.out.print("price = "); System.out.printf("%2.10f", price);

89. What is the output of the following code snippet?

System.out.printf("%5.3f", 20.0); a. 20 b. 20.0 c. 20.00 d. 20.000 90. Assume the following variables have been declared and given values as shown:

int i = 2345; double m = 67.8; What will be printed by the statement below?

System.out.printf("Values are %10d and %7.2f", i, j); a. Values are 2345 and 67.8 b. Values are 2345 and 67.80 c. Values are %10d and %7.2f 2345 67.8 d. Values are %10d and %7.2f i j 91. Assume the following variables have been declared and given values as shown:

int i = 2345; double m = 67.8; Which statement will give the output below?

Values are 2345 and 67.80 a. System.out.printf("Values are %10d and %7.2f", i, m); b. System.out.printf("Values are %6d and %2.2f", i, m); c. System.out.printf("Values are %i and %m"); d. System.out.println("Values are " + i + " and " + m); Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch4 92. What will be printed by the statement below?

System.out.print("O\"my\t\\\"no!"); a. O"myt\"no! b. O\"my\t\\\"no! c. O\ my\t\\\ no! d. O"my \"no! 93. What will be printed by the statements below?

final int BONUS = 20; int salary = 100; int netSalary = salary + BONUS; System.out.print(netSalary); a. salaryBONUS b. 120 c. 100BONUS d. Nothing will be printed because constants cannot be used in expressions. 94. What will be printed by the statements below?

int x = 20; int y = x; x++; y--; System.out.print("x = " + x + ", y = " + y); a. x = 20, y = 20 b. x = 21, y = 20 c. x = 20, y = 19 d. x = 21, y = 19 95. What will be printed by the statements below?

int x = 20; int y = x; x += 3; y *= 2; System.out.print("x = " + x + ", y = " + y); a. x = 23, y = 46 b. x = 23, y = 40 c. x = 46, y = 46 d. x = 3, y = 2 Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch4 96. The first step in problem solving is a. To write the expression that calculates the answer b. To understand the problem and its inputs and outputs c. To do examples by hand that confirm the solution will work d. To write Java code that can be executed and tested 97. At what point in the problem-solving process should one write pseudocode? a. After writing Java code, as a way to summarize the code’s algorithm b. Before writing Java code, as a guide for a general solution c. After defining Java variables so that the pseudocode and data types make sense d. Before working out examples by hand in order to guide those examples 98. The problem solving process emphasizes a “first, do-it-by-hand” approach because a. pseudocode is not able to capture the subtleties of complex problems. b. it is faster to do computations by hand than to do them by computer. c. this guarantees that programs will be correct. d. if programmers cannot compute a solution by hand, it is unlikely they will be able to write a program that can do it. 99. Assume the following variable has been declared and given values as shown: String name = "Mamey, Jean"; Which statement will print the name as "Jean Mamey"? a. System.out.print(name.substring(7) + " " + name.substring(0, 5)); b. System.out.print(name.substring(8, 4) + " " + name.substring(1, 5)); c. System.out.print(name.substring(8) + " " + name.substring(1, 4)); d. System.out.print(name.substring(2) + " " + name.substring(1)); 100. What is the result of the following statement?

String s = "You" + "had" + "me" + "at" + "hello"; a. The string s has the following value: "You had me at "hello" b. The statement results in an error because the + operator can be used only with numbers c. The statement results in an error because the + operation cannot be performed on string literals d. The string s has the following value: "Youhadmeathello" 101. Which operator is used to concatenate two or more strings? a. + b. % c. & d. ^ 102. What output is produced by these statements? Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch4

String name = "Joanne Hunt"; System.out.println(name.length()); a. 8 b. 10 c. 9 d. 11 103. How do you compute the length of the string str? a. length(str) b. length.str c. str.length d. str.length() 104. What is the output of the following code snippet?

String str1; str1 = "I LOVE MY COUNTRY"; String str2 = str1.substring(4, 11); System.out.println(str2); a. OVE MY b. OVE MY C c. VE MY CO d. VE MY C 105. Assuming that the user inputs “Joe” at the prompt, what is the output of the following code snippet?

System.out.print("Enter your name "); String name; Scanner in = new Scanner(System.in); name = in.next(); name += ", Good morning"; System.out.print(name); a. The code snippet does not compile because the += operator cannot be used in this context. b. Joe, Good morning c. , Good morning d. Joe 106. Assuming that the user enters 45 and 62 as inputs for n1 and n2, respectively, what is the output of the following code snippet?

System.out.print("Enter a number: "); Scanner in = new Scanner(System.in); String n1 = in.next(); Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch4

System.out.print("Enter another number: "); String n2 = in.next(); String result = n1 + n2; System.out.print(result); a. 46 b. 4662 c. 107 d. 4562 107. Which of the methods below are static methods? I. length II. substring III. pow IV. sqrt a. All the methods are static b. Only I, II and III c. Only II and IV d. Only III and IV 108. Which one of the following expressions can be used to extract the last five characters from any string variable str? a. str.substring(str.length() - 5, str.length()) b. str.substring(5, 5) c. str.substring(str.length() - 4, 5) d. str.substring(str.length() - 5, 5) 109. How do you extract the first 5 characters from the string str? a. substring(str, 5) b. substring.str(0,5) c. str.substring(5) d. str.substring(0,5) 110. Which of the given System.out.print statements generates the following output?

ABCDE"\ a. System.out.println("ABCDE\"\\"); b. System.out.println("ABCDE"\"); c. System.out.println("ABCDE"\); d. System.out.println("ABCDE\"\"); 111. Which of the given statements generates the following output? \\\"/// a. System.out.println("\\\"///"); b. System.out.println("\\\\\\\"///"); Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch4 c. System.out.println("\\\\\\""//////"); d. System.out.println("\\\"///"); 112. Assuming that the user enters 23 and 45 as inputs for num1 and num2, respectively, what is the output of the following code snippet?

Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); String num1 = in.next(); System.out.print("Enter another number: "); String num2 = in.next(); System.out.println(num1 + num2); a. 23 b. 4523 c. 68 d. 2345 113. Which one of the following statements can be used to extract the last 10 characters from the string variable str? a. str.substring(str.length() - 10, str.length()) b. str.substring(10, str.length()) c. str.substring(str.length() - 9, 10) d. str.substring(0, 10) 114. Which one of the following statements can be used to get the fifth character from a string str? a. char c = str.charAt(5); b. char c = str.charAt(4); c. char c = str[5]; d. char c = str[4]; 115. What (if any) type of error occurs with the following code if the user input is ABC?

Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); String str = in.next(); int count = Integer.parseInt(str); System.out.println("Input is " + count); a. Compile-time error b. Run-time error c. Overflow error d. Illegal expression 116. What is the output of the following code snippet? Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch4

String str = "Harry"; int n = str.length(); String mystery = str.substring(0, 1) + str.substring(n - 2, n); System.out.println(mystery); a. Ha b. Har c. Hy d. Hry 117. What is the output of the following code snippet?

String str = "Hello"; int n = str.length(); String mystery = str.substring(0, 1) + str.substring(n - 2, n + 1); System.out.println(mystery); a. Run-time error b. He c. Ho d. Hry 118. What is the output of the following code snippet?

String str = "Java Is Good"; int n = str.length(); String mystery = str.substring(n - 4, n) + str.charAt(4) + str.substring(0, 4); System.out.println(mystery); a. Java b. Good Java c. Good d. Is Good 119. What is the output of the following code snippet?

final String str = "Java"; str += " is powerful"; System.out.println(str); a. Java is powerful b. Java + is powerful c. is powerful d. Nothing; compile-time error Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch4 120. What is the output of the following code snippet?

String str = "Java"; str += " is powerful"; System.out.println(str); a. Java is powerful b. Java + is powerful c. is powerful d. Compile-time error 121. What is the output of the following code snippet?

String firstname = "William"; String lastname; System.out.println("First: " + first); System.out.println("Last: " + lastname); a. First: William Last: b. First: William Last: lastname

c. Code will not compile d. Unpredictable output 122. What is the correct way to invoke methods on variables in Java that are strings? a. Methods can only be invoked on string constants, not on variables. b. For each method there is a special operator that must be used. c. There are no methods available in Java for string variables. d. Invoke them using the variable name and the dot (.) notation. 123. Suppose a phone number, stored as a ten-character string (of digits only) called phoneNumber must be converted into a string that has parentheses around the area code. Which statement below will do that? a. String newNumber = "(" + phoneNumber.substring(3, 0) + ")"; b. String newNumber = "(" + ")" + phoneNumber;

c. String newNumber = "(" +

phoneNumber.substring(1, 3) + ")" + phoneNumber.substring(3, 7); d. String newNumber = "(" + phoneNumber.substring(0, 3) + ")" + phoneNumber.substring(3, 10);

124. Assume the following variables have been declared and given values as shown:

String str = "0123456789"; String sub = str.substring(3, 4); Which is the value of sub? a. 3 Powered by Cognero

Page 25


Name:

Class:

Date:

testbank-bj-7-ch4 b. 34 c. 345 d. 3456 125. Assume the following variable has been declared and given a value as shown:

String str = "0123456789"; Which is the value of str.length()? a. 9 b. 10 c. 11 d. 12 126. Assume the variable str has been declared to be a String that has at least one character. Which is the following represents the last character in str? a. str.charAt(str.length()) b. str.lastChar() c. str.charAt(str.length() - 1) d. str.substring(str.length()) 127. What will be printed by the statements below?

int x = 100; int y = -12; System.out.print("Sum is " + x + y); a. Sum is 100-12 b. Sum is 88 c. Sum is xy d. Sum is 100 + -12

Powered by Cognero

Page 26


Name:

Class:

Date:

testbank-bj-7-ch4 Answer Key 1. c 2. d 3. b 4. d 5. b 6. b 7. c 8. c 9. c 10. c 11. c 12. a 13. d 14. c 15. a 16. b 17. c 18. a 19. a 20. c 21. b 22. d 23. c 24. b 25. d Powered by Cognero

Page 27


Name:

Class:

Date:

testbank-bj-7-ch4 26. d 27. a 28. c 29. b 30. c 31. d 32. b 33. c 34. b 35. c 36. c 37. d 38. a 39. d 40. b 41. a 42. c 43. a 44. b 45. b 46. c 47. c 48. b 49. b 50. c 51. c Powered by Cognero

Page 28


Name:

Class:

Date:

testbank-bj-7-ch4 52. d 53. d 54. d 55. b 56. b 57. d 58. b 59. c 60. a 61. d 62. c 63. b 64. d 65. a 66. c 67. b 68. a 69. c 70. c 71. c 72. d 73. c 74. d 75. a 76. c Powered by Cognero

Page 29


Name:

Class:

Date:

testbank-bj-7-ch4 77. c 78. a 79. c 80. c 81. a 82. a 83. a 84. a 85. d 86. b 87. c 88. c 89. d 90. b 91. a 92. d 93. b 94. d 95. b 96. b 97. b 98. d 99. a 100. d 101. a 102. d Powered by Cognero

Page 30


Name:

Class:

Date:

testbank-bj-7-ch4 103. d 104. d 105. b 106. d 107. d 108. a 109. d 110. a 111. b 112. d 113. a 114. b 115. b 116. d 117. a 118. b 119. d 120. a 121. c 122. d 123. d 124. a 125. b 126. c 127. a Powered by Cognero

Page 31


Name:

Class:

Date:

testbank-bj-7-ch4

Powered by Cognero

Page 32


Name:

Class:

Date:

testbank-bj-7-ch5

Indicate the answer choice that best completes the statement or answers the question. 1. What is the best way to improve the following code fragment?

if ((counter % 10) == 0) { System.out.println("Counter is divisible by ten: " + counter); counter++; } else { System.out.println("Counter is not divisible by ten: " + counter); counter++; } a. Move the duplicated code outside of the if statement b. Shorten variable names c. Move the brackets to save several lines of code d. Add semicolons after the if condition and the else reserved word 2. What are the two parts of an if statement? a. A condition and a body b. A check and an increment c. An increment and a body d. An increment and a return value 3. Which of the following statements is true about the if statement? a. The if statement can have only one condition that evaluates to an integer value. b. The if block is optional. c. The else block is optional. d. The if and else blocks should always be included within curly braces. 4. Which of the following statements is correct about an if statement? a. You must use braces if the body of an if statement contains only a single statement. b. You can omit an else statement if there is no task defined in the else branch. c. You cannot use braces if the body of an if statement contains only a single statement. d. The number of opening braces can be different from the number of closing braces. 5. Which of the following is the correct syntax for an if statement? a. if (x < 10) { size = "Small"; } else (x < 20) { size = "Medium"; } b. if (x < 10); { size = "Small"; } else (x < 20) { size = "Medium"; } c. if (x < 10) { size = "Small"; } else { size = "Medium"; } d. if { size = "Small";}

Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch5 else (x < 20) { size = "Medium"; }

6. Assuming that the user provides 303 as input, what is the output of the following code snippet?

int x; int y; Scanner in = new Scanner(System.in); System.out.print("Please enter a number: "); y = in.nextInt(); if (y > 300) { x = y; } else { x = 0; } System.out.println("x: " + x); a. x: 0 b. x: 300 c. x: 303 d. There is no output due to compilation errors. 7. Assuming that the user provides 99 as input, what is the output of the following code snippet?

int a; int b; Scanner in = new Scanner(System.in); System.out.print("Please enter a number: "); b = in.nextInt(); if (b > 300) { a = b; } else { a = 0; } System.out.println("a: " + a); a. a: 0 b. a: 99 c. a: 100 d. a: 300 8. The following code snippet contains an error. What is the error? Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch5

int cost = 100; if (cost > 100); { cost = cost – 10; } System.out.println("Discount cost: " + cost); a. Syntax error (won’t compile) b. Logical error: use of an uninitialized variable c. Logical error: if statement has do-nothing statement after if condition d. Logical error: assignment statement does not show equality 9. A store provides 10 percent discount on all items with a price of at least $100. No discount is otherwise applicable. Which of the following DOES NOT correctly compute the discount? a. double discount = 0; if (price >= 100) { discount = 0.10 * price; } b. double discount = 0.10 * price; if (price <= 100) { discount = 0; } c. double discount; if (price < 100) { discount = 0; } else { discount = 0.10 * price; } d. double discount = 10; if (price >= 100) { discount = 0.1 * price; } else { discount = 0; }

10. Which of the following statements is (are) true about an if statement? I. It guarantees that several statements are always executed in a specified order. II. It repeats a set of statements as long as the condition is true. III. It allows the program to carry out different actions depending on the value of a condition. a. I only b. II only c. III only Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch5 d. I, II, III 11. What is the output of the following code snippet?

double income = 45000; double cutoff = 55000; double minIncome = 30000; if (minIncome > income) { System.out.println("Minimum income requirement is not met."); } if (cutoff < income) { System.out.println("Maximum income limit is exceeded."); } else { System.out.println("Income requirement is met."); } a. Minimum income requirement is not met. b. Maximum income limit is exceeded. c. Income requirement is met. d. There is no output. 12. Suppose one needs an if statement to check whether an integer variable pitch is equal to 440 (which is the frequency of the note “A” to which strings and orchestras tune). Which condition is correct? a. if (pitch – 440 = 0) b. if ((pitch !< 440) && (pitch !> 440)) c. if (pitch = 440) d. if (pitch == 440) 13. What kind of operator is the <= operator? a. Ternary b. Arithmetic c. Inequality d. Relational 14. Which of the following operators is used as a relational operator? a. =< b. <= c. = d. ! 15. The operator !> stands for a. not less than. Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch5 b. not greater than. c. not equal to. d. this is not an operator in Java 16. Assuming that a user enters 15 as input, what is the output of the following code snippet?

Scanner in = new Scanner(System.in); System.out.print("Please enter a number: "); int number = in.nextInt(); if (number > 20) { System.out.println("The number is LARGE!"); } else { System.out.println("The number is SMALL!"); } a. There is no output due to compilation errors. b. The number is LARGE! c. The number is SMALL! d. The number is LARGE! The number is SMALL!

17. What is the output of the following code snippet if the input is 25?

int i; Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); i = in.nextInt(); if (i > 25) { i++; } else { i--; } System.out.print(i); a. 24 b. 25 c. 26 d. 27 18. Which statement about an if statement is true? a. The condition in an if statement using relational operators will evaluate to a Boolean result Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch5 b. The condition in an if statement should make exact comparisons to floating-point numbers c. The condition in an if statement should always evaluate to true d. The condition in an if statement should never include integer variables 19. What is the syntax error in the following if statement?

double count = 15.0; if (count / 3.0) { System.out.println("The value of count is "); } a. There should be an “else” condition b. The condition does not evaluate to a Boolean value c. The variable count should be part of the string d. It is never possible to use the “/” operator in an if statement 20. Consider the following code snippet. What is the potential problem with the if statement?

double average; average = (g1 + g2 + g3 + g4) / 4.0; if (average == 90.0) { System.out.println("You earned an A in the class!"); } a. Using == to test the double variable average for equality is error-prone. b. The conditional will not evaluate to a Boolean value. c. The assignment operator should not be used within an if-statement conditional. d. Literals should never be used in if statement conditionals. 21. Which code snippet will always output “Yes!” when s1 and s2 are two strings the contain the same sequence of characters? a. if (s1 = s2) {

System.out.println("Yes!"); } b. if (s1 == s2) { System.out.println("Yes!"); } c. if (s1.equals(s2)) { System.out.println("Yes!"); } d. if (s1.compareTo(s2) == 1) { System.out.println("Yes!"); Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch5 }

22. Which condition, when supplied in the if statement below in place of (. . .), will correctly protect against division by zero?

if (. . .) { result = grade / num; System.out.println("Just avoided division by zero!"); } a. (grade == 0) b. ((grade / num) == 0) c. (num == 0) d. (num != 0) 23. What is the output of the following code snippet?

int num = 100; if (num != 100) { System.out.println("100"); } else { System.out.println("Not 100"); } a. There is no output due to compilation errors. b. 100 c. Not 100 d. 100 Not 100

24. What is the output of the following code snippet?

String str1 = "her"; String str2 = "cart"; if (str1.compareTo(str2) < 0) { System.out.print(str2); } else { System.out.print(str1); } a. her Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch5 b. hercart c. cart d. carther 25. What is the conditional required to check whether the length of a string s1 is odd? a. if ((s1.length() % 2) == 0) b. if ((s1.length() % 2) != 0) c. if ((s1.length() / 2)) d. if ((s1.length() * 2)) 26. The two strings “Aardvark” and “Aardvandermeer” are exactly the same up to the first six letters. What is their correct lexicographical ordering? a. They cannot be compared lexicographically unless they are the same length b. “Aardvandermeer” is first, then “Aardvark” c. “Aardvark" is first, then “Aardvandermeer” d. The shorter word is always first 27. Which if statement is true when the length of string s1 is greater than 42? a. if (s1.length() > 42) b. if (s1.length() != 42) c. if (42 > s1.length()) d. if (42 != s1.length()) 28. Which of the following operators is NOT a relational operator? a. <= b. += c. != d. == 29. Assuming that the user provides 3 as input, what is the output of the following code snippet?

int x; int y; x = 0; System.out.print("Please enter y: "); Scanner in = new Scanner(System.in); y = in.nextInt(); if ((y % 2) != 0) { x = 2 * y; } else { x = 2 + x; } Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch5

System.out.println("x: " + x); a. x: 2 b. x: 4 c. x: 6 d. There is no output due to compilation errors. 30. Assuming that the user provides 49 as input, what is the output of the following code snippet?

int x = 0; int y = 0; System.out.print("Please enter y: "); Scanner in = new Scanner(System.in); y = in.nextInt(); if (y > 50); { x = y; } System.out.println("x: " + x); a. x: 0 b. x: 49 c. x: 50 d. There is no output due to compilation errors. 31. What is the output of the following code snippet?

final int EXPERIENCE = 5; int age = 25; if ((age + EXPERIENCE) > 30) { System.out.println("You are wise!"); } else { System.out.println("You have much to learn!"); } a. There is no output due to compilation errors. b. You are wise! c. You have much to learn! d. You are wise! You have much to learn! 32. What is the output of the following code snippet? Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch5

int x = 50; if (x > 100) { x++; } else { x--; } System.out.println(x); a. 49 b. 50 c. 51 d. 52 33. A store applies a 15 percent service charge on all items with a price of at least $150. No service charge is otherwise applicable. Which of the following DOES NOT correctly compute the service charge? a. double serviceCharge = 0; if (cost >= 150) { serviceCharge = 0.15 * cost; } b. double serviceCharge = 0.15 * cost; if (cost <= 150) { serviceCharge = 0; } c. double serviceCharge; if (cost < 150) { serviceCharge = 0; } else { serviceCharge = 0.15 * cost; } d. double serviceCharge = 15; if (cost >= 150) { serviceCharge = 0.15 * cost; } else { serviceCharge = 0; }

34. What is the output of the following code snippet? Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch5

double salary = 55000; double cutOff = 65000; double minSalary = 40000; if (minSalary > salary) { System.out.println("Minimum salary requirement is not met."); } if (cutOff < salary) { System.out.println("Maximum salary limit is exceeded."); } else { System.out.println("Salary requirement is met."); } a. Minimum salary requirement is not met. b. Maximum salary limit is exceeded. c. Salary requirement is met. d. There is no output. 35. What is the output of the following code snippet?

final int COST = 583; int digit = COST % 10; if (digit != 500) { System.out.println("500"); } else { System.out.println("Not 500"); } a. There is no output due to compilation errors. b. 500 c. Not 500 d. 500 Not 500 36. What is the output of the following code snippet?

String someString1 = "his"; String someString2 = "cycle"; if (someString1.compareTo(someString2) < 0) { System.out.println(someString2); Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch5

} else { System.out.println(someString1); } a. his b. hiscycle c. cycle d. There is no output due to compilation errors. 37. What is the output of the statements below?

int a = 10; if (a > 5) { System.out.print ("One"); } else { System.out.print ("Two"); } System.out.print ("Three"); a. One b. OneThree c. TwoThree d. OneTwoThree 38. What is the output of the statements below?

int a = 10; int b = 20; int count = 0; if (a > 5) { count ++; } if (b > 5) { count ++; } if (a > 10) { count ++; } if (b > 10) Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch5

{ count ++; } System.out.print (count); a. 1 b. 2 c. 3 d. 4 39. What is the output of the statements below?

int a = 10; int b = 20; int count = 0; if (a > 5) { count ++; } else if (b > 5) { count ++; } else if (a > 10) { count ++; } else if (b > 10) { count ++; } System.out.print (count); a. 1 b. 2 c. 3 d. 4 40. What is the output of the statements below?

int a = 10; int b = 20; int count = 0; if (a > 5) { count ++; Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch5

if (b > 5) { count ++; } } if (a > 10) { count ++; if (b > 10) { count ++; } } System.out.print (count); a. 1 b. 2 c. 3 d. 4 41. What is the output of the statements below?

int a = 10; int b = 20; int count = 0; if (a > 5) if (b > 5) { count ++; } else count = 7; System.out.print (count); a. 0 b. 1 c. 2 d. 7 42. What is the output of the statements below?

int a = 10; int b = 20; int count = 0; if (a > 10) { count ++; Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch5

if (b > 5) { count ++; } if (a > 10) { count ++; } } if (b > 10) { count ++; } System.out.print (count); a. 1 b. 2 c. 3 d. 4 43. Which of the following conditions can be added to the code below so it will assign the larger value of two integer variables a and b to the integer variable maximum?

if (/* put condition here */) { maximum = a; } else { maximum = b; } a. a == b b. b > a c. a > b d. a.compareTo (b) > 0 44. Which of the following conditions is true exactly when the integer variable number is even? a. number / 2 == 0 b. number > 2 c. number / 2 > 1 d. number % 2 == 0 45. Which of the following conditions is true exactly when the integer variable middle is between the values 0 and 10? a. (0 <= middle) && (middle <= 10) b. 0 <= middle <= 10 Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch5 c. (0 <= middle) || (middle <= 10) d. (0 <= 10) && (middle <= 10) 46. Which of the following conditions is true exactly when the integer variables a, b, and c contain three different values? a. (a != b) && (a != c) && (b != c) b. (a != b) || (a != c) || (b != c) c. !((a == b) && (b == c) && (a == c)) d. a != b != c 47. Which of the following conditions will correctly check if the String variable greeting is "bonjour"? a. if (greeting == "bonjour") b. if (greeting.compareTo("bonjour") < 0) c. if (greeting.equals("bonjour")) d. if (greeting.compareTo("bonjour") > 0) 48. Which of the following conditions will correctly check if the String variable early comes before "middle" alphabetically? a. if (greeting <= "middle") b. if (greeting.compareTo("middle") > 0) c. if (greeting.compareTo("middle") == 0) d. if (early.compareTo("middle") < 0) 49. What is the output of the following code snippet?

int x = 25; if (x < 100) { x = x + 5; } if (x < 500) { x = x - 2; } if (x > 10) { x++; } else { x--; } System.out.println(x); a. 27 b. 28 c. 29 Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch5 d. 30 50. Suppose you want to write an if statement with multiple alternatives to print out someone's tax bracket based on their income. Assume the integer variable income holds the annual income. What is wrong with the following if statement?

if (income < 10000) { System.out.println("Lowest tax bracket"); } if (income < 20000) { System.out.println("Low-Middle tax bracket"); } if (income < 30000) { System.out.println("Middle tax bracket"); } System.out.println("High tax bracket"); a. The conditions are in the wrong order; the check for the highest bracket should be first b. The conditions should use an if/ else if/else sequence, not just independent if statements c. The conditions should be a switch statement instead d. Nothing is wrong – the if statement will correctly print out the correct tax brackets 51. Which observation about the switch statement in Java is true? a. The switch statement is like a sequence of if statements that compares a single value against several constant alternatives. b. The switch statement is a compound statement that tests all branches against different variables. c. The switch statement requires compound Boolean expressions as alternatives. d. The switch statement is no longer valid in the most recent version of Java. 52. In a switch statement, if a break statement is missing a. the break happens at the end of each branch by default b. the statement will not compile c. execution falls through the next branch until a break statement is reached d. the default case is automatically executed 53. What is the output of the following code snippet?

int s1 = 20; if (s1 <= 20) { System.out.print("1"); } if (s1 <= 40) { Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch5

System.out.print("2"); } if (s1 <= 20) { System.out.print("3"); } a. 1 b. 2 c. 3 d. 123 54. Consider a situation where multiple if statements are combined into a chain to evaluate a complex condition. Which of the following reserved words is used to define the branch to be executed when none of the conditions are true? a. if b. else if c. else d. All of the above items 55. Consider the following code snippet:

int number = 0; Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); number = in.nextInt(); if (number > 30) { . . . } else if (number > 20) { . . .. } else if (number > 10) { . . . } else { . . . } Assuming that the user input is 40, which block of statements is executed? a. if (number > 30) { . . .} b. else if (number > 20) { . . .} c. else if (number > 10) { . . .} d. else { . . .} 56. Assuming that the user enters 60 as the input, what is the output after running the following code snippet?

int num = 0; Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); num = in.nextInt(); if (num < 10) { System.out.println("Too small!"); } else if (num < 50) Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch5

{ System.out.println("Intermediate!"); } else if (num < 100) { System.out.println("High!"); } else { System.out.println("Too high!"); } a. Too small! b. Intermediate! c. High! d. Too high! 57. Assuming that a user enters 5 as the value for num, what is the output of the following code snippet?

int num = 0; Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); num = in.nextInt(); if (num < 50) { num = num + 5; } if (num < 10) { num = num - 2; } if (num > 5) { num++; } else { num--; } System.out.println(num); a. 0 b. 9 c. 5 d. 11 58. Consider the following code snippet. Assuming that the user enters first 20 and then 12 as the two input values, what Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch5 is the output of the code snippet?

int num1 = 0; int num2 = 0; int num3 = 0; int num4 = 0; int num5 = 0; Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); num1 = in.nextInt(); System.out.print("Enter a number: "); num2 = in.nextInt(); if (num1 < num2) { num3 = num1; } else { num3 = num2; } if (num1 < num2 + 10) { num4 = num1; } else if (num1 < num2 + 20) { num5 = num1; } System.out.println("num1 = " + num1 + " num2 = " + num2 + " num3 = " + num3 + " num4 = " + num4 + " num5 = " + num5); a. num1 = 20 num2 = 12 num3 = 20 num4 = 20 num5 = 0 b. num1 = 20 num2 = 12 num3 = 12 num4 = 0 num5 = 20 c. num1 = 20 num2 = 12 num3 = 12 num4 = 20 num5 = 0 d. num1 = 20 num2 = 12 num3 = 20 num4 = 0 num5 = 20 59. What is the value of the price variable after the following code snippet is executed?

int price = 42; if (price < 40) { price = price + 10; } if (price > 30) { price = price * 2; } Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch5

if (price < 100) { price = price - 20; } a. 42 b. 52 c. 84 d. 64 60. Consider the following code snippet. Assuming that the user inputs 75 as the age, what is the output?

int age = 0; Scanner in = new Scanner(System.in); System.out.print("Please enter your age: "); age = in.nextInt(); if (age < 10) { System.out.print("Child "); } if (age < 30) { System.out.print("Young adult "); } if (age < 70) { System.out.print("Old "); } if (age < 100) { System.out.print("Impressively old "); } a. Impressively old b. Child Young adult Old c. Young adult Old d. Child Young adult Old Impressively old 61. What is the value of the magicPowers variable after executing the following code snippet?

String magicPowers = ""; int experienceLevel = 9; if (experienceLevel > 10) { magicPowers = magicPowers + "Golden sword "; } if (experienceLevel > 8) Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch5

{ magicPowers = magicPowers + "Shining lantern "; } if (experienceLevel > 2) { magicPowers = magicPowers + "Magic beans "; } a. Golden sword Shining lantern Magic beans b. Shining lantern Magic beans c. Magic beans d. An empty string 62. Assuming that a user enters 5 as the age, what is the output of the following code snippet?

int age = 0; Scanner in = new Scanner(System.in); System.out.print("Please enter your age: "); age = in.nextInt(); if (age < 10) { System.out.println("Kid"); } if (age < 30) { System.out.print("Young"); } if (age < 70) { System.out.print("Aged"); } if (age < 100) { System.out.print("Old"); } a. Kid b. Kid

Young c. Kid YoungAged d. Kid YoungAgedOld

63. What is the value of num after you run the following code snippet?

int num = 100; if (num <= 100) Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch5

{ num++; } if (num <= 200) { num--; } if (num <= 300) { num++; } if (num <= 400) { num--; } if (num <= 500) { num++; } a. 99 b. 100 c. 101 d. 102 64. What is the output of the following code snippet?

int num1 = 40; if (num1 <= 40) { System.out.print("F"); } if (num1 <= 75) { System.out.print("C"); } if (num1 <= 90) { System.out.print("B"); } a. F b. C c. B d. FCB 65. What is the output after running the following code snippet? Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch5

int number = 600; if (number < 200) { System.out.println("Low spender"); } else if (number < 500) { System.out.println("Spending in moderation"); } else if (number < 1000) { System.out.println("Above average!"); } else { System.out.println("High Roller!"); } a. Low spender b. Spending in moderation c. Above average! d. High Roller! 66. What is the output of the following code snippet?

int x = 25; if (x < 100) { x = x + 5; } if (x < 500) { x = x - 2; } if (x > 10) { x++; } else { x--; } System.out.println(x); a. 27 b. 28 Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch5 c. 29 d. 30 67. What is the value of the cost variable after the following code snippet is executed?

int cost = 82; if (cost < 100) { cost = cost + 10; } if (cost > 50) { cost = cost * 2; } if (cost < 100) { cost = cost - 20; } a. 82 b. 92 c. 184 d. 164 68. Consider the following code snippet. What is the output?

int score = 68; if (score < 50) { System.out.print("You need to practice!"); } if (score < 100) { System.out.print("Almost respectable!"); } if (score < 150) { System.out.print("You hit triple digits!"); } if (score < 250) { System.out.print("Impressive!"); } a. You need to practice! b. Almost respectable!You hit triple digits! c. You hit triple digits!Impressive! Powered by Cognero

Page 25


Name:

Class:

Date:

testbank-bj-7-ch5 d. Almost respectable!You hit triple digits!Impressive! 69. What is the output of the following code snippet?

int shoeSize = 8; if (shoeSize < 6) { System.out.println("Petite"); } if (shoeSize < 8) { System.out.println("Small"); } if (shoeSize < 10) { System.out.println("Medium"); } if (shoeSize < 14) { System.out.println("Large"); } a. Petite b. Petite Small c. Small Medium d. Medium Large

70. What is the output of the following code snippet?

int golfScore = 64; if (golfScore < 60) { System.out.println("Astounding!"); } if (golfScore >= 60 && golfScore < 70) { System.out.println("Professional!"); } if (golfScore >= 70 && golfScore < 80) { System.out.println("Pretty good!"); } if (golfScore >= 80 && golfScore < 90) { System.out.println("Not so hot!"); } Powered by Cognero

Page 26


Name:

Class:

Date:

testbank-bj-7-ch5

if (golfScore >= 90) { System.out.println("Keep your day job!"); } a. Astounding! b. Professional! c. Pretty good! d. Keep your day job! 71. A company applies a discount based on the size of the order. If the order is over $50, the discount is 5%. If the order is over $100, the discount is 10%. Otherwise, there is no discount. If the integer variable order contains the size of the order, which of the following will assign the double variable discount the correct value? a. if (order > 100) discount = 0.10; else if (order > 50) discount = 0.05; else discount = 0; if (order > 100) b. discount = 0.10; if (order > 50) discount = 0.05; else discount = 0; if (order > 100) c. discount = 0.10; if (order > 50) discount = 0.05; if (order <= 50) discount = 0; d. if (order > 50) discount = 0.05; else if (order > 100) discount = 0.10; else discount = 0;

72. An if statement inside another if statement is called a a. switch statement b. nested if statement c. break statement d. syntax error, since that is not permitted in Java 73. When an if statement is nested inside another if statement, it creates the possibility of a. an infinite loop b. the misuse of the break statement c. type mismatch Powered by Cognero

Page 27


Name:

Class:

Date:

testbank-bj-7-ch5 d. the dangling else 74. Which of the following options correctly represents a “nested if” structure? a. if (cost < 70) {

if (tax_rate < 0.10) { . . . } } b. if (cost < 70) { . . . } if (tax_rate < 0.10) { . . . } c. if (cost < 70) { . . . } else { . . . } if (tax_rate < 0.10) { . . . } d. if (cost < 70) { . . . } { else { if (tax_rate < 0.10) { . . . } } }

75. Which of the following statements is true about the “nested if” structure? a. It cannot have any else branches at all. b. It allows multiple else branches in a single if statement. c. It allows one if statement within another if statement. d. It does not allow more than one if statement nested within another if statement. 76. Assuming that a user enters 10, 20, and 30 as input values one after another, separated by spaces, what is the output of the following code snippet?

int num1 = 0; int num2 = 0; int num3 = 0; Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); num1 = in.nextInt(); System.out.print("Enter a number: "); num2 = in.nextInt(); System.out.print("Enter a number: "); num3 = in.nextInt(); if (num1 > num2) { if (num1 > num3) { System.out.println(num1); } else { System.out.println(num3); } Powered by Cognero

Page 28


Name:

Class:

Date:

testbank-bj-7-ch5

} else { if (num2 > num3) { System.out.println(num2); } else { System.out.println(num3); } } a. 0 b. 10 c. 20 d. 30 77. What is the output of the following code snippet?

int num = 100; if (num < 100) { if (num < 50) { num = num - 5; } else { num = num – 10; } } else { if (num > 150) { num = num + 5; } else { num = num + 10; } } System.out.println(num); a. 95 b. 100 Powered by Cognero

Page 29


Name:

Class:

Date:

testbank-bj-7-ch5 c. 105 d. 110 78. Which of the following options refers to the technique of simulating program execution on a sheet of paper? a. Compiling b. Prototyping c. Hand-Tracing d. Debugging 79. To which of the following coding techniques can hand-tracing be applied? a. Pseudocode b. Java code c. Both pseudocode and Java code d. Neither pseudocode nor Java code 80. If the user enters 22 as the price of an object, which of the following hand-trace tables is valid for this code snippet?

int price = 0; String status = ""; Scanner in = new Scanner(System.in); System.out.print("Please enter object’s price: "); price = in.nextInt(); if (price >= 50) { status = "reasonable"; if (price >= 75) { status = "costly"; } } else { status = "inexpensive"; if (price <= 25) { status = "reasonable"; } } a. price

status

0

""

22

"inexpensive" "reasonable"

b. price Powered by Cognero

status Page 30


Name:

Class:

Date:

testbank-bj-7-ch5

0

"inexpensive"

22

"reasonable"

c. price

status

0 22

"reasonable" "costly"

d. price

status

0

"reasonable"

22

"costly"

81. Consider the following code snippet:

boolean married = true; boolean engaged = false; Which of the following if statements includes a condition that evaluates to true? a. if (married == "true") { . . . } b. if (married == true) { . . . } c. if (engaged == "false") { . . . } d. if (married == engaged) { . . . } 82. What is the output of the following code snippet?

boolean passed = false; String someStr = "Unknown"; passed = !(passed); if (!passed) { someStr = "False"; } if (passed) { passed = false; } if (!passed) { someStr = "True"; } else { someStr = "Maybe"; } System.out.println(someStr); Powered by Cognero

Page 31


Name:

Class:

Date:

testbank-bj-7-ch5 a. False b. True c. Unknown d. Maybe 83. Assuming that a user enters 50, 70, and 60 as input values one after another, separated by spaces, what is the output of the following code snippet?

int number1 = 0; int number2 = 0; int number3 = 0; Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); number1 = in.nextInt(); System.out.print("Enter a number: "); number2 = in.nextInt(); System.out.print("Enter a number: "); number3 = in.nextInt(); if (number1 > number2) { if (number1 > number3) { System.out.println(number1); } else { System.out.println(number3); } } else { if (number2 > number3) { System.out.println(number2); } else { System.out.println(number3); } } a. 0 b. 50 c. 60 d. 70 84. When drawing flowcharts, unconstrained branching and merging can lead to Powered by Cognero

Page 32


Name:

Class:

Date:

testbank-bj-7-ch5 a. So-called “spaghetti code” b. A better design c. Intuitive understanding of the flow of control d. Clear visualization of the problem solution 85. The flow chart shows the order in which steps should be executed, and the diamond-shaped boxes indicate a. input b. algorithms c. tasks d. conditional tests 86. How does a flow chart help with the understanding of the flow of control? a. Prevents errors in boolean expressions b. Enumerates the objects involved in the computation c. Helps to visualize the flow of control d. Delimits the scope of all program variables 87. What is the simple flow chart rule for avoiding unconstrained branching? a. Never point an arrow inside another branch b. Never use nested branching c. Never develop a flow chart with more than one outcome d. Write complicated flow chart diagrams on separate sheets of paper 88. When testing code for correctness, it always makes sense to a. Test all cases b. Identify boundary cases and test them c. Check all cases by hand d. Assume invalid input will never occur 89. How can flow charting help in developing test cases? a. Can use the chart to trace the code b. Can more easily reference objects that need to be tested c. The chart helps visually identify which branches are covered by test cases d. The chart makes the computation more simple 90. Which of the following operators compare using short-circuit evaluation? a. ++ b. -c. & & d. == 91. Which of the following options is a legally correct expression for inverting a condition? a. if (!(a == 10)) b. if (!a == 10) Powered by Cognero

Page 33


Name:

Class:

Date:

testbank-bj-7-ch5 c. if (a !== 10) d. if (a ! 10) 92. Which of the following variables is used to store a condition that can be either true or false? a. Algebraic b. Logical c. Boolean d. Conditional 93. Consider the following code snippet:

boolean attendance = true; boolean failed = false; Which of the following if statements includes a condition that evaluates to true? a. if (attendance == "true") { . . . } b. if (attendance) { . . . } c. if (failed) { . . . } d. if (attendance == failed) { . . . } 94. What is the output of the following code snippet?

boolean attendance = false; String str = "Unknown"; attendance = !(attendance); if (!attendance) { str = "False"; } if (attendance) { attendance = false; } if (attendance) { str = "True"; } else { str = "Maybe"; } System.out.println(str); a. False b. True c. Unknown d. Maybe Powered by Cognero

Page 34


Name:

Class:

Date:

testbank-bj-7-ch5 95. Which of the following operators is used to combine two Boolean conditions? a. ## b. $$ c. %% d. & & 96. Assuming that a user enters 56 for age, what is the output of the following code snippet?

int age = 0; Scanner in = new Scanner(System.in); System.out.print("Please enter your age: "); age = in.nextInt(); if (age < 13) { System.out.println("Kid!"); } if (age >= 13 && age < 19) { System.out.println("Teen!"); } if (age >= 19 && age < 30) { System.out.println("Young!"); } if (age >= 30 && age < 50) { System.out.println("Adult!"); } if (age >= 50) { System.out.println("Old!"); } a. Teen! b. Young! c. Adult! d. Old! 97. Which of the following expressions represents a legal way of checking whether a value assigned to the num variable falls in the range 100 to 200 (inclusive)? a. if (num >= 200 && num <= 100) b. if (num >= 100 && num <= 200) c. if (num >= 100 || num <= 200) d. if (num >= 200 || num <= 100) 98. Which of the following expressions represents a legal way of checking whether a value for the num variable is either Powered by Cognero

Page 35


Name:

Class:

Date:

testbank-bj-7-ch5 less than 100 or more than 200? a. if (num <= 100 && num >= 200) b. if (num < 100 && num > 200) c. if (num < 100 || num> 200) d. if (num <= 100 || num >= 200) 99. Assuming that a user enters 64 as the score, what is the output of the following code snippet?

int score = 0; Scanner in = new Scanner(System.in); System.out.print("Enter your score: "); score = in.nextInt(); if (score < 40) { System.out.println("F"); } else if (score >= 40 || score < 50) { System.out.println("D"); } else if (score >= 50 || score < 60) { System.out.println("C"); } else if (score >= 60 || score < 70) { System.out.println("B"); } else if (score >= 70 || score < 80) { System.out.println("B+"); } else { System.out.println("A"); } a. D b. C c. B d. A 100. Which of the following operators is used to invert a conditional statement? a. ! b. != c. || d. ? Powered by Cognero

Page 36


Name:

Class:

Date:

testbank-bj-7-ch5 101. What is the output of the following code snippet?

final int MIN_SPEED = 45; final int MAX_SPEED = 65; int speed = 55; if (!(speed < MAX_SPEED)) { speed = speed - 10; } if (!(speed > MIN_SPEED)) { speed = speed + 10; } System.out.println(speed); a. 45 b. 55 c. 65 d. 50 102. Consider the following code snippet:

int score = 0; double price = 100; if (score > 0 && price < 200 && price / score > 10) { System.out.println("buy"); } Which of the following statements is true on the basis of this code snippet? a. The output is buy. b. The code snippet compiles and runs, but there is no output. c. The code snippet doesn't compile. d. The code snippet causes a divide-by-zero error. 103. Which of the following options checks that city is neither Chicago nor Dallas? a. if (!city.equals("Chicago") || !city.equals("Dallas")) b. if (!(city.equals("Chicago") || city.equals("Dallas"))) c. if (!(city.equals("Chicago") && city.equals("Dallas"))) d. if (!city.equals("Chicago") || city.equals("Dallas")) 104. Assuming that a user enters 45, 78, and then 12, what is the output of the following code snippet?

int num1 = 0; int num2 = 0; int num3 = 0; Powered by Cognero

Page 37


Name:

Class:

Date:

testbank-bj-7-ch5

Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); num1 = in.nextInt(); System.out.print("Enter a number: "); num2 = in.nextInt(); System.out.print("Enter a number: "); num3 = in.nextInt(); if (!(num1 > num2 && num1 > num3)) { System.out.println(num1); } else if (!(num2 > num1 && num2 > num3)) { System.out.println(num2); } else if (!(num3 > num1 && num3 > num2)) { System.out.println(num3); } a. 12 b. 45 c. 78 d. There is no output due to compilation errors. 105. Which of the following expressions represents a legal way of checking whether a value assigned to the number variable falls between 50 and 100 inclusive? a. if (number >= 100 && number <= 50) b. if (number >= 50 && number <= 100) c. if (number >= 50 || number <= 100) d. if (number >= 100 || number <= 50) 106. Assuming that a user enters 68 as the score, what is the output of the following code snippet?

int score = 68; if (score < 50) { System.out.println("F"); } else if (score >= 50 || score < 55) { System.out.println("D"); } else if (score >= 55 || score < 65) { System.out.println("C"); } else if (score >= 65 || score < 75) { System.out.println("B"); } else if (score >= 75 || score < 80) { System.out.println("B+"); } else { System.out.println("A"); } a. D b. C Powered by Cognero

Page 38


Name:

Class:

Date:

testbank-bj-7-ch5 c. B d. A 107. Which of the following options checks that the string country is neither China nor Denmark? a. if (!country.equals("China") || !country.equals("Denmark") b. if (!(country.equals("China") || country.equals("Denmark"))) c. if (!(country.equals("China") && country.equals("Denmark"))) d. if (country.equals("China") || country.equals("Denmark")) 108. Which of the following conditions tests for the user to enter the string "Hello"? a. if (s == "Hello") b. if (s.substring(0,5) == "Hello") c. if (s.equals("Hello")) d. if (s = "Hello") 109. Which of the following options checks that character ch is neither a letter nor a white space? a. if (!Character.isLetter(ch) || !Character.isWhiteSpace(ch)) b. if (!(Character.isLetter(ch) || Character.isWhiteSpace(ch))) c. if (!(Character.isLetter(ch) && Character.isWhiteSpace(ch))) d. if (!Character.isLetter(ch) || Character.isWhiteSpace(ch)) 110. Assume the following variables have been declared and given values elsewhere:

boolean isFelon; int age; A person may vote if they are 18 or older and not a felon. Which of the following statements assigns the Boolean variable mayVote correctly? a. mayVote = (age >= 18) || !isFelon; b. mayVote = !((age >= 18) && isFelon); c. mayVote = (age >= 18) && !isFelon; d. mayVote = !((age >= 18) || isFelon); 111. Assume the following variables have been declared and given values elsewhere:

boolean completedProject; int programsDone; double classPercentage; A student will pass programming class if and only if they have a percentage of 70.0% or higher and have either completed the project or they have done 5 or more programs. Which of the following statements assigns the Boolean variable passProgramming correctly? a. passProgramming = (classPercentage >= 0.7) && (programsDone >= 5 || completedProject); b. passProgramming = (classPercentage >= 0.7) && (programsDone >= 5) && (completedProject); Powered by Cognero

Page 39


Name:

Class:

Date:

testbank-bj-7-ch5 c. passProgramming = (classPercentage >= 0.7) || (programsDone >= 5) || (completedProject); d. passProgramming = ((classPercentage >= 0.7) && (programsDone >= 5 )) || completedProject; 112. Assume isBusy and isHappy have been defined to be Boolean variables. Which of the following conditions has the same value as !isBusy || isHappy? a. !(isBusy || !isHappy) b. isBusy && !isHappy c. !(isBusy && !isHappy) d. isBusy || !isHappy 113. Assume isBusy has been defined to be a Boolean variables. Which of the following has the same value as (isBusy || true) && !isBusy? a. isBusy b. !isBusy c. true d. false 114. Assume isBusy has been defined to be a Boolean variables. Which of the following has the same value as (isBusy || true) && false? a. isBusy b. !isBusy c. true d. false 115. Which of the following performs the same way as the switch statement below?

switch (value) { case 1: System.out.print ("Small"); break; case 10: System.out.print ("Large"); break; default: System.out.print ("Other"); break; } a. if (value == 1) System.out.print("Small");

else if (value == 10) System.out.print("Large"); else System.out.print("Other"); b. if (value == 1) System.out.print("Small"); if (value == 10) System.out.print("Large"); else System.out.print("Other"); c. if (value >= 10) System.out.print("Large"); else System.out.print("Other"); d. if (value >= 10) System.out.print("Large"); Powered by Cognero

Page 40


Name:

Class:

Date:

testbank-bj-7-ch5 else System.out.print("Other");

116. Assume a, b, and c have been defined to be integer variables. Which of the following values make the expression !(a == b) && (c > a) true? a. a = 10, b = 10, c = 15 b. a = 10, b = 20, c = 15 c. a = 10, b = 2, c = 5 d. a = 10, b = 20, c = 10 117. Which of the following statements can be used to validate that the user input for the floor variable is between 0 and 20 inclusive? a. if (floor >= 0 && floor <= 20) b. if (floor >= 0 || floor <= 20) c. if (floor <= 0 && floor >= 20) d. if (floor <= 0 || floor >= 20) 118. Assuming that a valid price should be between 30 and 50, what does the following code snippet do?

final int MIN_PRICE = 30; final int MAX_PRICE = 50; int price = 0; Scanner in = new Scanner(System.in); System.out.print("Please enter the price: "); price = in.nextInt(); if (price < MIN_PRICE) { System.out.println("Error: The price is too low."); } else if (price > MAX_PRICE) { System.out.println("Error: The price is too high."); } else { System.out.println("The price entered is in the valid price range."); } a. This code snippet ensures that the price value is between 30 and 50. b. This code snippet only ensures that the price value is greater than 30. c. This code snippet only ensures that the price value is less than 50. d. This code snippet ensures that the price value is either less than 30 or greater than 50. 119. Which of the following conditions tests whether the user enters an integer value that will then be assigned to the floor variable?

int floor = 0; Scanner in = new Scanner(System.in); Powered by Cognero

Page 41


Name:

Class:

Date:

testbank-bj-7-ch5

System.out.print("Floor: "); if (...) { floor = in.nextInt(); } a. in.nextInt(floor) b. in.hasNextInt() c. in.fail d. in.nextInt()

Powered by Cognero

Page 42


Name:

Class:

Date:

testbank-bj-7-ch5 Answer Key 1. a 2. a 3. c 4. b 5. c 6. c 7. a 8. c 9. b 10. c 11. c 12. d 13. d 14. b 15. d 16. c 17. a 18. a 19. b 20. a 21. c 22. d 23. c 24. a 25. b Powered by Cognero

Page 43


Name:

Class:

Date:

testbank-bj-7-ch5 26. b 27. a 28. b 29. c 30. b 31. c 32. a 33. b 34. c 35. c 36. a 37. b 38. c 39. a 40. b 41. b 42. a 43. c 44. d 45. a 46. a 47. c 48. d 49. c 50. b 51. a Powered by Cognero

Page 44


Name:

Class:

Date:

testbank-bj-7-ch5 52. c 53. d 54. c 55. a 56. c 57. d 58. c 59. d 60. a 61. b 62. d 63. c 64. d 65. c 66. c 67. c 68. d 69. d 70. b 71. a 72. b 73. d 74. a 75. c 76. d Powered by Cognero

Page 45


Name:

Class:

Date:

testbank-bj-7-ch5 77. d 78. c 79. c 80. a 81. b 82. b 83. d 84. a 85. d 86. c 87. a 88. b 89. c 90. c 91. a 92. c 93. b 94. d 95. d 96. d 97. b 98. c 99. a 100. a 101. b 102. b Powered by Cognero

Page 46


Name:

Class:

Date:

testbank-bj-7-ch5 103. b 104. b 105. b 106. a 107. b 108. c 109. b 110. c 111. a 112. c 113. b 114. d 115. a 116. b 117. a 118. a 119. b

Powered by Cognero

Page 47


Name:

Class:

Date:

testbank-bj-7-ch6

Indicate the answer choice that best completes the statement or answers the question. 1. How many times will the following loop run?

int i = 0; while (i < 10) { System.out.println(i); i++; } a. 0 b. 8 c. 9 d. 10 2. What is the output of the code snippet given below?

int i = 0; while (i != 9) { System.out.print(i + " "); i = i + 2; } a. no output b. 0 2 4 6 8 c. 10 12 14 16 18 …. (infinite loop) d. 0 2 4 6 8 10 12 14 …. (infinite loop) 3. How many times does the code snippet given below display "Loop Execution"?

int i = 1; while (i != 10) { System.out.println("Loop Execution"); i++; } a. infinite times b. 8 times c. 9 times d. 10 times 4. What is the output of the code fragment given below?

int i = 0; Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch6

int j = 0; while (i < 27) { i = i + 2; j++; } System.out.println("j=" + j); a. j=27 b. j=12 c. j=13 d. j=14 5. What is the output of the following code snippet?

int i = 1; while (i < 10) { System.out.print(i + " "); i = i + 2; if (i == 5) { i = 9; } } a. 1 3 5 b. 1 3 9 c. 1 3 5 7 9 d. 1 3 5 9 6. The code snippet below checks whether a given number is a prime number. What will be the result of executing it?

public static void main(String[] args) { int j = 2; int result = 0; int number = 0; Scanner reader = new Scanner(System.in); System.out.println("Please enter a number greater than 1: "); number = reader.nextInt(); while (j <= number / 2) { if (number % j == 0) { result = 1; } Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch6

j++; } if (result == 1) { System.out.println("Number: " + number + " is not prime."); } else { System.out.println("Number: " + number + " is prime."); } } a. The code snippet will not compile. b. The code snippet will display the desired result. c. The code snippet will display an incorrect result if the number is 1. d. The code snippet will loop forever. 7. What are the values of i and j after the following code fragment runs?

int i = 60; int j = 50; int count = 0; while (count < 5) { i = i + i; i = i + 1; j = j - 1; j = j - j; count++; } System.out.println("i=" + i + ", j=" + j); a. i = 1951, j = 0 b. i = 1951, j = 45 c. i = 65, j = 1 d. i = 65, j = 45 8. Which error type does the "off-by-one" error belong to? a. syntax error b. compile-time error c. run-time error d. infinite loop 9. How many times does the following code fragment display "Hi"?

int i = 10; while (i >= 0) Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch6

{ System.out.println("Hi"); i--; } a. 9 times b. 10 times c. 11 times d. 12 times 10. What is the output of the following code fragment?

int i = 1; int sum = 0; while (i <= 11) { sum = sum + i; i++; } System.out.println("The value of sum is " + sum); a. The value of sum is 65. b. The value of sum is 66. c. The value of sum is 55. d. The value of sum is 56. 11. What is the output of the following code snippet?

int i = 1; while (i <= 10) { System.out.println("Inside the while loop"); i = i + 10; } a. No output because of compilation error. b. “Inside the while loop” will be displayed 10 times. c. No output after successful compilation. d. “Inside the while loop” will be displayed only once. 12. How many times does the code snippet below display "Hello"?

int i = 0; while (i != 15) { System.out.println("Hello"); i++; Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch6

} a. infinite times b. 14 times c. 15 times d. 16 times 13. What is the output of the code snippet given below?

String s = "abcde"; int i = 1; while (i < 5) { System.out.print(s.substring(i, i + 1)); i++; } a. no output b. abcd c. abcde d. bcde 14. What is the output of the code snippet given below?

String s = "12345"; int i = 1; while (i < 5) { System.out.print(s.substring(i, i + 1)); i+=2; } a. no output b. 13 c. 24 d. 2345 15. What is the output of the code fragment given below?

int i = 0; int j = 0; while (i < 125) { i = i + 2; j++; } Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch6

System.out.println(j); a. 0 b. 62 c. 63 d. The code fragment displays no output because it does not compile. 16. What is the output of the following code snippet?

int i = 1; while (i < 20) { System.out.print(i + " "); i = i + 2; if (i == 15) { i = 19; } } a. 1 3 5 7 9 11 13 15 17 19 b. 1 3 5 7 9 11 13 19 c. 1 3 5 7 9 11 13 15 17 d. 1 3 5 7 9 11 13 17 19 17. What are the values of i and j after the following code snippet is run?

int i = 10; int j = 20; int count = 0; while (count < 5) { i = 2*i; i = i + 1; j = j - 1; count++; } System.out.println("i = " + i + ", j = " + j); a. i = 10, j = 20 b. i = 351, j = 15 c. i = 351, j = 20 d. i = 1311, j = 35 18. What is the output of the following code fragment?

int i = 1; Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch6

int sum = 0; while (i <= 6) { sum = sum + i; i+=2; } System.out.println("The value of sum is " + sum); a. The value of sum is 0. b. The value of sum is 9. c. The value of sum is 12. d. The value of sum is 21. 19. What is the output of the following code snippet?

double r = 1; double b = 2; int i = 16; while (i > 0) { if (i % 2 == 0) // i is even { b = b * b; i = i / 2; } else { r = r * b; i = i - 1; } } System.out.println("r = " + r); a. r = 16.0 b. r = 128.0 c. r = 4096.0 d. r = 65536.0 20. What output does this while loop generate?

j = 6; while (j > 0) { System.out.print(j + ", "); j--; } Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch6 a. No output is generated. b. 6, 5, 4, 3, 2, 1 c. 6, 5, 4, 3, 2, 1, d. The output is infinite. 21. What is the output of this code snippet?

String str = "ABCabc"; char ch; int i = 0; while (i < str.length()) { ch = str.charAt(i); if (Character.isLowerCase(ch)) { System.out.print(i + " "); } else { i++; } } a. 3 4 5 b. 3 c. 3 3 3 3 3 ... (infinite loop) d. 0 1 2 22. What will be the result of running the following code fragment?

int year = 0; double rate = 5; double principal = 10000; double interest = 0; while (year < 10) { interest = (principal * year * rate) / 100; System.out.println("Interest " + interest); } a. The code fragment will display the interest calculated for nine years. b. The code fragment will continue to display the calculated interest forever because the loop will never end. c. The code fragment will not display the calculated interest and halt abruptly. d. The code fragment will not display any output because it will not compile. 23. Which of the following code snippets displays the output exactly 10 times? a. int i = 0; Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch6 while (i < 10); { System.out.println("This is example 1."); i++; } b. int i = 0; while (i < 10) { System.out.println("This is example 2."); i++; } c. int i = 0; while (i < 10) { System.out.println("This is example 3."); } d. int i = 1; while (i < 10) { System.out.println("This is example 4."); i++; }

24. What is the output of the following code snippet?

int i = 1; while (i != 9) { System.out.print(i + " "); i++; if (i == 9) { System.out.println("End"); } } a. 1 End b. 1 End (but the loop is an infinite loop) c. 1 2 3 4 5 6 7 8 End d. 1 2 3 4 5 6 7 8 End (but the loop is an infinite loop) 25. What changes do you need to make in the following code snippet to display “Let us learn Java” exactly 10 times?

int i = 0; while (i <= 10) { System.out.println("Let us learn Java"); i++; } a. while (i < 9) Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch6 b. while (i < 11) c. while (i < 12) d. int i = 1; 26. Which of the following statements is true about the variable sum in the code snippet below?

int i = 0; while (i != 11) { System.out.print(" " + i); int sum = i; i++; sum++; } a. It contains the value 10 after the loop is finished executing. b. It contains the value 11 after the loop is finished executing. c. It is the cause of an infinite loop. d. It disappears after the loop is done executing. 27. What is the output of the code snippet given below?

int i = 0; while (i != 11) { System.out.print(i + " "); i = i + 3; } a. No output b. 0 3 6 9 12 15 18 c. 0 1 3 5 7 9 d. 0 3 6 9 …. (infinite loop) 28. This code snippet is intended to calculate the balance of an account after twenty years of gaining interest. Select the statement that correctly completes the loop.

int years = 20; double balance = 10000; while (years > 0) { __________ double interest = balance * rate / 100; balance = balance + interest; } a. years++; Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch6 b. years--; c. balance++; d. balance--; 29. What is the best strategy for avoiding off-by-one errors? a. Randomly insert +1 or -1 until the program seems to work. b. Think through a couple of test cases and use the results to come up with a rationale for decisions. c. Always start a loop at 0. d. Never use the < operator by itself in a comparison test. 30. When hand-tracing the loop in the code snippet below, which variables are important to evaluate?

int i = 10; int j = 5; int k = -10; int sum = 0; while (i > 0) { sum = sum + i + j; i--; System.out.println("Iteration: " + i); } a. the variables i and j only b. the variables i and sum c. the variables i, j, and k d. Tthe variables j and k only 31. When hand tracing, drawing a line through the value stored in a variable means that the a. value stored there has changed to something new. b. variable is the wrong data type for the code being executed. c. expression being evaluated uses that variable. d. variable must be inside a loop. 32. When hand-tracing a portion of code, which statement about Boolean conditions is true? a. They typically are too complex to be evaluated. b. They do not need to be monitored because their result usually is not stored in a variable. c. It is rare to encounter a Boolean condition. d. They are crucial to evaluate since they determine if-statement conditions and looping control. 33. The process of hand-tracing code is valuable because a. it is usually faster than just running the code. b. it is the best way to design an algorithm. c. you must already have a working program in order to do it. d. it gives valuable insight that you do not get by running the code. Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch6 34. Which of the statements about hand-tracing is true? a. You need a working program in order to do hand-tracing. b. Hand-tracing can be done with pseudocode. c. Hand-tracing will clearly show how long a program will take to execute. d. The goal of hand-tracing is to double check the answers of the running code. 35. What for loop can be used in the indicated area so the code will print:

**** *** ** * for (int val = 0; val < 4; val ++) { // Put for loop here { System.out.print("*"); } System.out.println(); } a. for (int num = 0; num < 4 – val; num++) b. for (int num = 0; num < val; num++) c. for (int num = 4; num < val; num++) d. for (int num = 4; num > 0; num--) 36. How many times does the loop execute in the following code fragment?

int i; for (i = 0; i < 50; i = i + 4) { System.out.println(i); } a. 11 b. 12 c. 13 d. 14 37. How many times does the following code snippet display "Loop Execution"?

for (int i = 0; i < 10; i++); { System.out.println("Loop Execution"); Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch6

} a. ten times b. The code snippet does not run because of a compile error. c. infinite loop d. only one time 38. Assuming the variable n is an integer that stores a positive value, which of the following is a loop with a bound that could be problematic? a. for (i = 1; i != n; i++) b. for (years = n; years < 0; years--) c. for (i = 1; i <= n; i++) d. for (int i = 1; i <= 10; i++) 39. What values does counter variable i take on when this loop executes?

for (int i = 20; i >= 2; i = i - 6) { System.out.print(i + ","); } a. 20, 14, 8, 2 b. 20, 14, 8, 2, –4 c. 20, 14, 8 d. 14, 8, 2 40. What is the output of the following code snippet?

int f1 = 0; int f2 = 1; int fRes; System.out.print(f1 + " "); System.out.print(f2 + " "); for (int i = 1; i < 10; i++) { fRes = f1 + f2; System.out.print(fRes + " "); f1 = f2; f2 = fRes; } System.out.println(); a. 0 1 5 7 9 11 13 15 17 19 b. 0 1 1 2 3 5 8 13 21 34 55 c. 0 1 4 6 8 10 12 14 16 18 d. 0 1 6 7 9 12 14 17 19 21 Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch6 41. What is the output of the following code snippet?

int counter = 1; for (double i = 0.01; i <= 1.0; i = i + 0.01) { counter++; } System.out.println(counter); a. 100 b. 49.50 c. 60.5 d. 10 42. What does the following code snippet print?

int n1 = 120; int n2 = 90; int result = 1; for (int k = 1; k <= n1 && k <= n2; k++) { if (n1 % k == 0 && n2 % k == 0) { result = k; } } System.out.println(result); a. 10 b. 20 c. 30 d. 40 43. Which of the following for loops is illegal? ; ) { } a. for (int i = 0; b. for (int i = 0) { } c. for (int i = 0, k = 1; ; i++) { } d. for ( ; ; ) 44. How many times does the following loop execute?

for (double d = 1; d != 10; d++) { d = d / 3; System.out.print(d + " "); Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch6

} a. 10 b. 9 c. 8 d. an infinite number of times 45. Which of the following statements expresses why the following code is considered bad form?

for (rate = 5; years-- > 0; System.out.println(balance)) . . . I. unrelated expressions in loop header II. doesn't match expected for loop idiom III. loop iteration is not clear a. II and III only b. I and II only c. I and III only d. I, II, and III 46. Which of the following loops executes 8 times? a. for (years = 8; years >= 0; years--) b. for(i = 0; i <= 7; i++) c. for(i = 1; i <= 10; i++) d. for (int i = 19; i >= 11; i--) 47. Is the code snippet written below legal? (lines are numbered for reference)

1) String s = "1234"; 2) for (int i = 0; i <= 5; i++) 3) { 4) System.out.print(s.substring(i, i + 1)); 5) } a. Yes. b. No; there should be a semicolon at the end of line 2. c. No; for i = 4, s.substring(i, i + 1) will result in an StringIndexOutOfBounds error. d. No; line 4 should have no semicolon at the end. 48. Which statement about this code snippet is accurate?

int years = 50; double balance = 10000; double targetBalance = 20000; double rate = 3; for (int i = 1; i <= years; i++) { Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch6

if (balance >= targetBalance) { i = years + 1; } else { double interest = balance * rate / 100; balance = balance + interest; } } a. The loop will run 50 times. b. The loop will never stop. c. The loop will run at most 50 times, but may stop earlier when balance exceeds or equals targetBalance. d. There is a compilation error. 49. The for loop header can contain multiple variables of the same type and multiple update expressions, separated by commas:

for (int i = 0; j = 3; i <= 5; i++, j--) Which loop below correctly implements the same loop using a single counter in the loop control? a. int i = 0; for (int j = 3; j <= 5; j++) { . . . i++; } b. int i = 3; for (int j = 0; j <= 5; j++) { . . . i++; } c. int j = 3; for (int i = 0; i <= 5; j--) { . . . i++; } d. int j = 3; for (int i = 0; i <= 5; i++) { . . . j--; }

50. In the __________ loop header, you can include multiple update expressions, separated by commas, but it is not recommended. a. do Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch6 b. while c. for d. if 51. Which of the following loops executes the statements inside the loop before checking the condition? a. for b. while c. do d. do-for 52. Which loop does not check a condition at the beginning of the loop? I. the do loop II. the while loop III. the for loop a. I and II b. I and III c. I only d. III only 53. How many times does the following loop run?

int i = 0; int j = 1; do { System.out.println("" + i + ";" + j); i++; if (i % 2 == 0) { j--; } } while (j >= 1); a. 0 times b. 1 times c. 2 times d. 4 times 54. What is the output of the following code?

double x = 1; double y = 1; int i = 0; do { Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch6

y = x / 2; x = x + y; i = i + 1; } while (x < 2.5); System.out.print(i + " "); a. 1 b. 2 c. 3 d. 4 55. Given the following code snippet, what should we change to have 26 alphabet characters in the string str?

String str = ""; for (char c = 'A'; c < 'Z'; c++) { str = str + c; } a. int c = 'A' b. str = c + str; c. c <= 'Z' d. must change to use a do loop 56. What is the output of the code snippet given below?

String s = "abcde"; int i = 1; do { if (i > 1) { System.out.print(s.substring(i, i + 1)); } } while (i < 5); a. no output b. no output (infinite loop) c. abcde d. bcde 57. What is the output of the code snippet given below?

String s = "12345"; int i = 1; Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch6

do { if (i > 1) { System.out.print(s.substring(i, i + 1)); } } while (i < 2); a. no output b. no output (infinite loop) c. 12345 d. 2345 58. What is the output of the code snippet given below?

String s = "abcdefghijkl"; int i = 1; do { if (i > 2) { System.out.print(s.substring (1, i)); } i++; } while (i < 5); a. abcd b. bcde c. bcbcd d. cdef 59. Consider the following loop:

int n = 1; double x = 0; double s; do { s = 1.0 / (n * n); x = x + s; n++; } while (s > 0.01); System.out.println(x); Which loop below is an equivalent loop? Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch6 a. double x = 0;

double s = 1; for (int k = 1; s > 0.01; k++) { s = 1.0 / (k * k); x = x + s; } System.out.println(x); b. double x = 0; double s = 1; for (int k = 1; k < 100; k++) { s = 1.0 / (k * k); x = x + s; } System.out.println(x); c. double x = 0; double s = 1; int k = 10; while (s > 0.01) { s = 1.0 / (k * k); x = x + s; k++; } System.out.println(x); d. double x = 0; double s = 10; int k = 1; while (s > 0.01) { s = 1.0 / (k * k); x = x + s; k++; } System.out.println(x);

60. What is the output of the following loop?

int s = 1; int n = 1; do { s = s + n; n++; } while (s < 4 * n); System.out.println(s); a. 37 b. 36 c. 25 d. 24 Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch6 61. Which of the following loop(s) could possibly not enter the loop body at all? I. the for loop II. the while loop III. the do loop a. I only b. I and II only c. II and III only d. I and III only 62. Which of the loop(s) test the condition after the loop body executes? I. the for loop II. the while loop III. the do loop a. I only b. II only c. III only d. II and III 63. How many times is the text “Let's have fun with Java.” printed when this code snippet is run?

int i = 0; do { System.out.println("Let's have fun with Java."); i++; if (i % 2 == 0) { i = 10; } } while (i <= 10); a. 1 b. 2 c. 3 d. 10 64. Is the following code snippet legal?

boolean b = false; do { System.out.println("Do you think in Java?"); } while (b != b); Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch6 a. Yes, it is legal but does not print anything. b. Yes, it is legal and prints "Do you think in Java?" once. c. Yes, it is legal and prints "Do you think in Java?" twice. d. No, it is not legal and gives a compilation error. 65. How many times does the following loop execute?

int i = 0; int j = 1; do { System.out.println("" + i + ";" + j); i++; if (i % 3 == 0) { j--; } } while (j >= 1); a. 1 time b. 2 times c. 3 times d. 4 times 66. What is the output of the code snippet given below?

String s = "aeiou"; int i = 0; do { System.out.print(s.substring(i, i + 1)); i++; if (i >= 3) { i = 5; } } while (i < 5); a. a b. ae c. aeiou d. aei 67. What is the output of this code snippet? Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch6

int s = 1; int n = 1; do { s = s + n; System.out.print(s + " "); n++; } while (s < 3 * n); a. 2 4 7 11 16 22 b. 1 3 5 7 9 c. 2 3 5 6 7 d. 2 4 6 8 68. What is the sentinel value in the following code snippet?

public static void main(String[] args) { int age = 0; int sumOfAges = 0; int stop = 1; Scanner reader = new Scanner(System.in); System.out.println("Enter an age (-1 to stop): "); age = reader.nextInt(); while (age != -1) { sumOfAges = sumOfAges + age; System.out.println("Enter an age (-1 to stop): "); age = reader.nextInt(); } System.out.println("Sum of ages " + sumOfAges); return 0; } a. 0 b. 1 c. 2 d. -1 69. What will be the final output of the following code snippet when a user enters input values in the order 10, 20, 30, 40, 50, and -1?

public static void main(String[] args) { double sum = 0; int count = 0; Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch6

double salary = 0; double average = 0; Scanner reader = new Scanner(System.in); System.out.println("Enter salaries (-1 to stop): "); while (salary != -1) { salary = reader.nextInt(); if (salary != -1) { sum = sum + salary; count++; } } if (count > 0) { average = sum / count; System.out.println("The Average Salary: " + average); } else { System.out.println("No data!"); } return 0; } a. The Average Salary: 0.0 b. The Average Salary: 30.0 c. No data! d. There will be no output as the code snippet will not compile. 70. What will be the output of the following code snippet?

boolean token = false; while (token) { System.out.println("Hello"); } a. Hello will be displayed infinitely many times. b. There will be no output as the code snippet will not compile. c. There will be no output after successful compilation. d. Hello will be displayed only once. 71. What will be the output of the following code snippet?

boolean token = false; Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch6

do { System.out.println("Hello"); } while (token); a. Hello will be displayed infinitely many times. b. There will be no output as the code snippet will not compile. c. There will be no output after successful compilation. d. Hello will be displayed only once. 72. What is the outcome of the following code snippet?

boolean val1 = true; boolean val2 = false; while (val1) { if (val1) { System.out.println("Hello"); } val1 = val2; } a. No output will be displayed because of a compilation error. b. Hello will be displayed only once. c. Hello will be displayed infinite times. d. No output will be displayed even after successful compilation of the code snippet. 73. Which statement, inserted at the indicated blank line, will correctly terminate this loop when the end of input is reached (detected when the user enters the letter Q)?

ArrayList<Double> data = new ArrayList<Double>(); boolean done = false; while (!done) { String input = in.next(); if (input.equalsIgnoreCase("Q")) { __________ } else { double x = Double.parseDouble(input); data.add(x); } Powered by Cognero

Page 25


Name:

Class:

Date:

testbank-bj-7-ch6

} a. stop; b. done = 1; c. exit; d. done = true; 74. What does the following code snippet display?

char ch1 = '\u0000'; char ch2 = '\uffff'; for (int i = 0; i < 1000; i++) { if (i % 50 == 0) { System.out.println(); } System.out.print((char)(ch1 + Math.random() * (ch2 - ch1 + 1))); } a. It displays random Unicode characters. b. It displays random ASCII characters. c. Nothing because it has compilation error. d. It displays the hexadecimal characters between '0' and 'F.' 75. Which of the following loops executes exactly 10 times? a. for (int i = 0; i <= 10; i++) { } b. int i = 0; boolean found = false; do { i++; if (i % 10 == 0) { found = true; } } while (i < 10 && !found); c. int i = 0; while (i <= 10) { i++; } d. for (int i = 1; i <= 10; i++)

76. Suppose that a program asks a user to enter multiple integers, either positive or negative, to do some calculation. The data entry will stop when the user enters a certain value to indicate the end of the data. What value should the program use as the sentinel? Powered by Cognero

Page 26


Name:

Class:

Date:

testbank-bj-7-ch6 a. 0 b. -1 c. 999 d. an alphabetic character 77. How do you fix this code snippet to make it print out the sum when the user enters a letter rather than a double? The user must enter at least one double when the program begins.

System.out.print("Enter a value: "); double sum = 0; Scanner in = new Scanner(System.in); boolean hasData = true; do { double value = in.nextDouble(); sum = sum + value; System.out.print("Enter a value to add, or a letter to quit: "); } while (in.hasNext()); System.out.println("sum " + sum); a. while (in.hasData()); b. while (!in.hasEnded()); c. while (in.hasNextDouble()); d. while (hasData); 78. Which of the following should be used when you need to ask a user to enter one data item and repeat the prompt if the data is invalid? I. the for loop II. the while loop III. the do loop a. I only b. I and II c. III only d. II only 79. Which of the following statements is correct about a sentinel? a. A sentinel is a value that creates a bridge between a data set and unrelated input. b. A sentinel is a value that is part of the data to be processed by the program. c. A sentinel is a value that terminates a program. d. A sentinel is a value that indicates the end of an input sequence. 80. Which statement is correct about the execution of the loop in the following code fragment?

double num; int incr = 0; Powered by Cognero

Page 27


Name:

Class:

Date:

testbank-bj-7-ch6

Scanner reader = new Scanner(System.in); do { incr = incr + 1; System.out.println("Please enter a number (0 when done): "); num = reader.nextDouble(); } while (num != 0); System.out.println("" + incr); a. The loop will execute only when 0 is entered. b. The execution of the loop is independent of user input. c. The program prints the count of positive inputs. d. The loop will execute at least once even if the user has entered the sentinel value. 81. What will be the output of the following code snippet?

boolean token1 = true; while (token1) { for (int i = 0; i < 10; i++) { System.out.println("Hello"); } token1 = false; } a. There will be no output. b. Hello will be displayed 10 times. c. Hello will be displayed 9 times. d. Hello will be displayed infinite times. 82. When will the loop in the following code snippet stop?

Scanner in = new Scanner(System.in); double sum = 0; int count = 0; System.out.print("Enter values: "); do { double value = in.nextDouble(); sum = sum + value; count++; System.out.print("Enter values, Q to quit: "); } while (in.hasNextDouble() && count < 100); Powered by Cognero

Page 28


Name:

Class:

Date:

testbank-bj-7-ch6 I. when the user enters an integer II. when the user enters an alphabetic character III. after the user enters 100 numbers a. I or II b. II only c. III only d. II or III 83. The command line interface of your operating system provides a way to link a file to the input of a program. What is this process called? a. debugging b. redirection c. profiling d. compiling 84. Storyboards are a helpful part of the design process because the storyboard develops a. a pseudocode description of the algorithm being designed. b. the mathematical formulas required for computing a correct answer. c. the information needed to solve the problem, and how to present that information. d. the amount of time and space needed to find a solution. 85. When designing storyboards, it is a good idea to use different colors to a. make it easy to distinguish between user input and program output. b. match the colors your program will use when it is finally designed. c. emphasize the difference between numbers and words. d. draw lines to divide up panels into different regions. 86. Suppose you must design a program to calculate the roll-out (number of inches travelled in one revolution of the pedals of a bicycle based on its gear combinations). The user will provide the gear sizes, which must be converted into roll-out for all different gear combinations. How can the flow of user interaction for this problem be designed? a. Hand-tracing can confirm code that implements gear selection. b. Pseudocode can guide algorithm design through divide-and-conquer strategy. c. A storyboard can be used. d. The physical gears can lead to ideas for the correct algorithm to use. 87. Which statement about storyboards is true? a. A storyboard can help prevent potential user confusion early in the design process. b. Storyboards are used primarily to understand how implemented programs work. c. The storyboard helps to train users about how to use software. d. Storyboards have no relationship to the structure of an actual working program. 88. What is the purpose of the following loop?

int upperCaseLetters = 0; int position; String str = "abcdEfghI"; Powered by Cognero

Page 29


Name:

Class:

Date:

testbank-bj-7-ch6

boolean found = false; for (position = 0; position < str.length() && !found; position++) { char ch = str.charAt(position); if (Character.isUpperCase(ch)) { found = true; } } a. finds the position of the first digit (0 through 9) in a string, starting from the left b. finds the position of the first digit (0 through 9) in a string, starting from the right c. finds the position of the first uppercase character in a string, starting from the left d. finds the position of the first uppercase character in a string, starting from the right 89. What is the output of this code snippet if the user enters the numbers 1 2 3 4 -1 5?

double total = 0; boolean hasValidNumber = true; Scanner in = new Scanner(System.in); while (in.hasNextDouble() && hasValidNumber) { double input = in.nextDouble(); if (input < 0) { hasValidNumber = false; } else { total = total + input; } } System.out.println(total); a. 15.0 b. 14.0 c. 12.0 d. 10.0 90. What is the output of this loop?

int i = 0; boolean found; while (i < 20 && !found) { int sum = i * 2 + i * 3; System.out.print(sum + " "); Powered by Cognero

Page 30


Name:

Class:

Date:

testbank-bj-7-ch6

if (sum > 50) { found = true; } i++; } a. 0 5 10 15 20 25 30 35 40 45 50 55 b. 0 c. no output, compilation error d. 0 5 10 91. How many times does the following loop execute?

int i = 0; boolean found = false; while (i < 10 && !found) { i++; System.out.print(i + " "); int j = i * i; if ((i * i * i) % j == j) { found = true; } } a. 0 times b. 1 time c. 10 times d. an infinite number of times 92. Which code snippet produces the sum of the first n even numbers? a. int sum = 0; for (int i = 1; i <= n; i++) { if (i % 2 == 0) { sum = sum + i; } } b. int sum = 0; for (int i = 1; i <= n; i++) { sum = sum + i * 2; } c. int sum = 0; for (int i = 0; i < n; i++) {

Powered by Cognero

Page 31


Name:

Class:

Date:

testbank-bj-7-ch6 if (i % 2 == 0) { sum = sum + i; } } d. int sum = 0; for (int i = 1; i < 2*n; i++) { sum = sum + i; }

93. Which of the following loops will print the odd numbers between 0 and 20? a. for (int num = 1; num < 20; num++) {

System.out.print(num % 2 + " "); } b. for (int num = 0; num < 20; num+= 2) { System.out.print(num + " "); } c. for (int num = 1; num < 20; num+= 2) { System.out.print(num + " "); } d. for (int num = 0; num < 20; num+= 2) { if (num % 2 == 1) System.out.print(num + " "); }

94. Which of the following conditions can be added to the code below so it will loop until the user enters "no" or "NO"?

Scanner in = new Scanner (System.in); System.out.print("Continue? "); String response = in.next(); while (/* put condition here */) { System.out.println("Hello beautiful!"); System.out.print("Continue? "); response = in.next(); } a. response.equals("no") != response.equals("NO") b. !(response.equals("no") || response.equals("NO")) c. !response.equals("no") || !response.equals("NO") d. !(response.equals("no") && response.equals("NO")) 95. For which input values will the following loop not correctly compute the maximum of the values?

Scanner in = new Scanner (System.in); int max = 0; Powered by Cognero

Page 32


Name:

Class:

Date:

testbank-bj-7-ch6

while (in.hasNextInt()) { int value = in.nextInt(); if (value > max) { max = value; } } a. 3 3 3 3 b. 0 1 2 9 107 c. 107 2 9 -3 d. -4 -2 -10 -7 96. What will be printed by the statements below?

for (int ctr = 10; ctr > 5; ctr--) { System.out.print(ctr + " "); } a. 10 9 8 7 6 5 b. 10 9 8 7 6 c. 5 6 7 8 9 10 d. 6 7 8 9 10 97. Which of the following loops will print the odd numbers between 0 and 20? a. int num = 1; while (num < 20) { System.out.print(num + " "); num += 2; } b. int num = 1; while (num < 20) { System.out.print(num + " "); num ++; } c. int num = 0; while (num < 20) { System.out.print(num + " "); num += 2; } d. int num = 1; while (num < 20) { num += 2; System.out.print(num + " ");

Powered by Cognero

Page 33


Name:

Class:

Date:

testbank-bj-7-ch6 }

98. Which of the following conditions can be added to the code below so it will loop until the value of sum is greater than 100?

Scanner in = new Scanner (System.in); int sum = 0; do { sum += in.nextInt(); } while (/* put condition here */); a. sum != 0 b. sum <= 100 c. sum > 100 d. sum == 100 99. What does the following loop compute?

Scanner in = new Scanner(System.in); int sum = 0; int count = 0; while (in.hasNextInt()) { int value = in.nextInt(); if (value > 0) { sum += value; count++; } } double result = (sum * 1.0)/count; a. the average of all the integers in the input b. the sum of all the positive integers in the input divided by the number of integers in the input c. the average of all the positive integers in the input d. the second smallest value in the input 100. What does the method below return?

public static int findSomething(String str) { int position = 0; while (position < str.length() && (str.charAt(position) != 'e')) { position++; } Powered by Cognero

Page 34


Name:

Class:

Date:

testbank-bj-7-ch6

return position; } a. the position of the first 'e' in the string or the length of the string if there is no 'e' b. the position of the last 'e' in the string or the length of the string if there is no 'e' c. the position of the first character that is not an 'e' in the string or the length of the string if there is no character that is not an 'e' d. the position of the last character that is not an 'e' in the string or the length of the string if there is no character that is not an 'e' 101. What is the output of the code below?

for (int val = 0; val < 4; val ++) { System.out.print("+"); for (int num = 0; num < val; num++) { System.out.print("0"); } } a. +0+00+000+0000 b. +000+000+000+000 c. ++0+00+000 d. ++++000000 102. What is the output of the code below?

for (int val = 0; val < 4; val ++) { int sum = val; for (int num = 0; num < val; num++) { sum = sum + num; } System.out.print(sum + " "); } a. 0 1 3 6 b. 0 1 4 10 c. 0 2 5 9 d. 0 2 7 16 103. What is the last output line of the code snippet given below?

int i = 5; Powered by Cognero

Page 35


Name:

Class:

Date:

testbank-bj-7-ch6

while (i >= 1) { int num = 1; for (int j = 1; j <= i; j++) { System.out.print(num + "**"); num = num * 2; } System.out.println(); i = i - 1; } a. no output b. 1**2 c. 1**2**3 d. 1** 104. A loop inside another loop is called a a. sentinel loop. b. nested loop. c. parallel loop. d. do/while loop. 105. What is the first and last value of i to be displayed by the following code snippet?

int n = 20; for (int i = 0; i <= n; i++) { for (int j = 0; j <= i; j++) { System.out.println("" + i); } } a. 0 and 20 b. 1 and 20 c. 0 and 19 d. 1 and 19 106. How many times will the output line be printed in the following code snippet?

for (int num2 = 1; num2 <= 3; num2++) { for (int num1 = 0; num1 <= 2; num1++) { System.out.println("" + num2 + " " + num1); } Powered by Cognero

Page 36


Name:

Class:

Date:

testbank-bj-7-ch6

} a. 3 times b. 6 times c. 9 times d. 12 times 107. In the following code snippet, when does the execution of the program switch from the inner loop to the outer loop?

int i; int j; for (i = 0; i <= 9; i++) { for (j = 1; j < 5; j++) { System.out.println("Hello"); if (j == 2) { j = 6; } } } a. when the value of j becomes 6 b. when the program executes completely c. when the condition for the outer loop is met d. when the value of i is incremented 108. What is the last output line of the code snippet given below?

int i = 0; while (i < 10) { for (int j = i; j > 1; j--) { System.out.print(j + " "); } System.out.println("***"); i++; } a. 3 2 *** b. 9 8 7 6 5 4 3 2 *** c. 8 7 6 5 4 3 2 *** d. 2 *** 109. Which for loop prints data across each row in the following code snippet? Powered by Cognero

Page 37


Name:

Class:

Date:

testbank-bj-7-ch6

int i; int j; for (i = 1; i <= 3; i++) { for (j = 1; j <= 3; j++) { System.out.print("X"); } System.out.println(""); } a. the inner for loop b. the outer for loop c. both for loops d. another missing for loop 110. What will be the output of the following code snippet?

int i; int j; for (i = 0; i <7; i++) { for (j = 7; j > i; j--) { System.out.print("*"); } System.out.println(""); } a. The output will be a rectangle with six rows and seven columns of asterisks. The numberof rows increments by one on completion of one iteration of the inner loop. b. The output will be a right triangle with six rows and seven columns of asterisks. Thenumber of columns increments by one on completion of one iteration of the inner loop. c. The output will be a rectangle with seven rows and six columns of asterisks. The numberof rows increments by one on completion of one iteration of the inner loop. d. The output will be a right triangle with six rows and seven columns of asterisks. The number of columns decrements by one on completion of one iteration of the inner loop. 111. In the following code snippet, when does the execution of the program switch from the inner loop to the outer loop?

int i; int j; for (i = 0; i <= 9; i++) { for (j = 1; j < 5; j++) { System.out.println("Hello"); Powered by Cognero

Page 38


Name:

Class:

Date:

testbank-bj-7-ch6

} } a. when the value of j becomes 5 b. when the program executes completely c. when the condition for the outer loop is met d. when the value of i is incremented 112. Which of the following activities can be simulated using a computer? I. waiting time in a line at a restaurant II. tossing a coin III. shuffling cards for a card game a. I only b. II only c. I and II only d. I, II, and III 113. What will be the range of the random numbers generated by the following code snippet?

Random generator = new Random(); int r1 = generator.nextInt(50) + 1; a. between 1 and 49 b. between 0 and 50 c. between 0 and 49 d. between 1 and 50 114. Which of the following is the correct code snippet for throwing a pair of dice to get a sum of the numbers on two dice between 2 and 12 with different probabilities? (Assume Random generator = new Random();) a. int sum = generator.nextInt(6) + generator.nextInt(6) + 2 b. int sum = generator.nextInt(12) + 1 c. int sum = generator.nextInt(6 + 1) + generator.nextInt(6 + 1) d. int sum = generator.nextInt(11) + 2 115. What is the data type of the number generated by the Random.nextDouble() method? a. double b. float c. int d. string 116. What does the following code do?

int sum = 0; final double count = 1000; Random generator = new Random(); Powered by Cognero

Page 39


Name:

Class:

Date:

testbank-bj-7-ch6

for (int i = 1; i <= count; i++) { sum = sum + generator.nextInt(101); } System.out.println(sum / count); a. It simulates the outcome of throwing a coin. b. It calculates the average of 1000 random numbers between 0 and 100. c. It performs a Monte Carlo simulation to estimate the value of pi. d. It calculates the average of 1000 random numbers between 1 and 101. 117. How many times does the following loop execute?

double d; Random generator = new Random(); double x = generator.nextDouble() * 100; do { d = Math.sqrt(x) * Math.sqrt(x) - x; System.out.println(d); x = generator.nextDouble() * 10001; } while (d != 0); a. exactly once b. exactly twice c. can't be determined d. always infinite loop 118. Which of the following is correct for simulating the toss of a pair of coins to get 0 (head) or 1 (tail) with different probabilities? (Assume Random generator = new Random();.) a. System.out.println(generator.nextInt(1) + " " + generator.nextInt(2)); b. System.out.println((generator.nextDouble() + 2) * 2); c. System.out.println(generator.nextInt(1) + " " + generator.nextInt(1)); d. System.out.println(generator.nextInt(2)+ " " + generator.nextInt(2)); 119. Suppose that the chance to hit the jackpot in a lottery is one in one million. Which of the expressions simulates that random number? (Assume Random generator = new Random();.) a. generator.nextDouble() * 1000000 b. generator.nextDouble() * 100000 c. generator.nextDouble() * 9999990 + 1 d. generator.nextDouble() * 1000000 + 1 120. Which of the following code snippets will generate a random number between 0 (inclusive) and 79 (inclusive)? (Assume Random generator = new Random();.) a. int val = generator.nextInt(79) + 1; Powered by Cognero

Page 40


Name:

Class:

Date:

testbank-bj-7-ch6 b. int val = generator.nextInt(80) - 1; c. int val = generator.nextInt(79); d. int val = generator.nextInt(80); 121. Assume the following variable has been declared and given a value as shown:

Random rand = new Random(); Which of the following will generate a random integer in the range – 20 to 20, inclusive, where each value has an equal chance of being generated? a. rand.nextInt (-20, 20) b. rand.nextInt(20) - 41 c. rand.nextInt (-20) + 40 d. rand.nextInt(41) - 20 122. Assume the following variable has been declared and given a value as shown:

Random rand = new Random(); int number = rand.nextInt (27) * 2

+ 3;

What are the smallest and largest values number may be assigned? a. 3, 57 b. 0, 27 c. 3, 55 d. 0, 26 123. Assume the following variable has been declared and given a value as shown:

Random rand = new Random(); double number = rand.nextDouble () * 2

+ 3;

What are the smallest and largest values number may be assigned? a. 3.0, 5.0 b. 0.0, 6.0 c. -3.0, 3.0 d. 0.0, 3.0 124. What is the name of the special program that lets you find bugs in your code by following its execution? a. compiler b. assembler c. interpreter d. debugger 125. What debugger command allows you to make the program execution stop at a specific line of code? a. inspect variable b. set breakpoint Powered by Cognero

Page 41


Name:

Class:

Date:

testbank-bj-7-ch6 c. single step d. halt 126. Which statement about using a debugger is correct? a. You can only set a single breakpoint in a program. b. Most values of variables are hidden and cannot be inspected using a debugger. c. When the program terminates, the debugger stops as well. d. It is not possible to step through a program's execution one line at a time. 127. To check whether a specific method is doing is job correctly, you can use the debugger tool called a. "step over." b. "step into." c. "inspect variable." d. "reproduce error." 128. The "divide-and-conquer" strategy for using a debugger helps to a. pinpoint the location of an error in the code. b. reproduce an error. c. simplify an error. d. know what the program should be doing.

Powered by Cognero

Page 42


Name:

Class:

Date:

testbank-bj-7-ch6 Answer Key 1. d 2. d 3. c 4. d 5. b 6. b 7. a 8. c 9. c 10. b 11. d 12. c 13. d 14. c 15. c 16. b 17. b 18. b 19. d 20. c 21. c 22. b 23. b 24. c 25. d Powered by Cognero

Page 43


Name:

Class:

Date:

testbank-bj-7-ch6 26. d 27. d 28. b 29. b 30. b 31. a 32. d 33. d 34. b 35. a 36. c 37. d 38. a 39. b 40. b 41. a 42. c 43. b 44. d 45. d 46. b 47. c 48. c 49. d 50. c 51. c Powered by Cognero

Page 44


Name:

Class:

Date:

testbank-bj-7-ch6 52. c 53. c 54. c 55. c 56. b 57. b 58. c 59. a 60. a 61. b 62. c 63. c 64. b 65. c 66. d 67. a 68. d 69. b 70. c 71. d 72. b 73. d 74. a 75. d 76. d Powered by Cognero

Page 45


Name:

Class:

Date:

testbank-bj-7-ch6 77. c 78. c 79. d 80. d 81. b 82. d 83. b 84. c 85. a 86. c 87. a 88. c 89. d 90. c 91. c 92. b 93. c 94. b 95. d 96. b 97. a 98. b 99. c 100. a 101. c 102. a Powered by Cognero

Page 46


Name:

Class:

Date:

testbank-bj-7-ch6 103. d 104. b 105. a 106. c 107. a 108. b 109. a 110. d 111. a 112. d 113. d 114. a 115. a 116. b 117. c 118. d 119. a 120. d 121. d 122. c 123. a 124. d 125. b 126. c 127. b Powered by Cognero

Page 47


Name:

Class:

Date:

testbank-bj-7-ch6 128. a

Powered by Cognero

Page 48


Name:

Class:

Date:

testbank-bj-7-ch7

Indicate the answer choice that best completes the statement or answers the question. 1. Which one of the following statements is true about using arrays with methods? a. Arrays can be method arguments, and return values, just like any other values. b. A method can only accept arguments that are elements of an array, but not the whole array. c. A method may accept an argument that is an array, but it cannot return a result that is an array. d. If a method is defined to have an array as a method argument, it must also define the size of the array as another method argument. 2. Consider the following line of code:

int[] somearray = new int[30]; Which one of the following options is a valid line of code for displaying the twenty-eighth element of somearray? a. System.out.println(somearray[28]); b. System.out.println(somearray(28)); c. System.out.println(somearray(27)); d. System.out.println(somearray[27]); 3. Identify the correct statement for defining an integer array named numarray of ten elements. a. int[] numarray = new int[9]; b. int[] numarray = new int[10]; c. int[10] numarray; d. int numarray[10]; 4. Which one of the following statements is a valid initialization of an array named somearray of ten elements? a. int[] somearray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; b. int somearray[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; c. int[10] somearray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; d. int somearray[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 5. What is the output of the following code snippet?

int[] myarray = { 10, 20, 30, 40, 50 }; System.out.print(myarray[2]); System.out.print(myarray[3]); a. 1050 b. 2030 c. 3040 d. 4050 6. What is the result of executing this code snippet?

int[] marks = { 90, 45, 67 }; for (int i = 0; i <= 3; i++) Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch7

{ System.out.println(marks[i]); } a. The code snippet does not give any output. b. The code snippet displays all the marks stored in the array without any redundancy. c. The code snippet causes a bounds error. d. The code snippet executes an infinite loop. 7. What is the valid range of index values for an array of size 10? a. 0 to 9 b. 0 to 10 c. 1 to 9 d. 1 to 10 8. Which one of the following statements is correct about the given code snippet?

int[] somearray = new int[6]; for (int i = 1; i < 6; i++) { somearray[i] = i + 1; } a. The for loop initializes all the elements of the array. b. The for loop initializes all the elements except the first element. c. The for loop initializes all the elements except the last element. d. The for loop initializes all the elements except the first and last elements. 9. What is the output of the given code snippet?

int[] mynum = new int[5]; for (int i = 1; i < 5; i++) { mynum[i] = i + 1; System.out.print(mynum[i]); } a. 2345 b. 1234 c. 1345 d. 1111 10. Which one of the following statements is correct for the given code snippet?

int[] number = new int[3]; number[3] = 5; Powered by Cognero

// Line 1 // Line 2 Page 2


Name:

Class:

Date:

testbank-bj-7-ch7 a. Line 2 declares and initializes an array of three elements with value 5. b. Line 2 causes a bounds error because 3 is an invalid index number. c. Line 2 initializes the third element of the array with value 5. d. Line 2 initializes all the elements of the array with value 5. 11. What is displayed after executing the given code snippet?

int[] mymarks = new int[10]; int total = 0; Scanner in = new Scanner(System.in); for (int cnt = 1; cnt <= 10; cnt++) { System.out.print("Enter the marks: "); mymarks[cnt] = in.nextInt(); total = total + mymarks[cnt]; } System.out.println(total); a. The code snippet displays the total marks of all ten subjects. b. The for loop causes a run-time time error on the first iteration. c. The code snippet causes a bounds error. d. The code snippet displays zero. 12. When an array myArray is only partially filled, how can the programmer keep track of the current number of elements? a. access myArray.length() b. maintain a companion variable that stores the current number of elements c. access myArray.currentElements() d. access myArray.length() - 1 13. If currLength is an integer variable that gives the number of elements currently in the array myArray, which code snippet prints out the elements in the partially filled array of integers? a. for (int i = 0; i < myArray.length(); i++) {

System.out.print(myArray[i]); } b. for (int i = 0; i < myArray.currLength(); i++) { System.out.print(myArray[i]); } c. for (int i = 0; i < currLength; i++) { System.out.print(myArray[i]); } d. for (int i = 0; i < myArray.length(); i++) { System.out.print(myArray[currLength]); } Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch7 14. In a partially filled array, the number of slots in the array that are not currently used is the a. length of the array minus the number of elements currently in the array. b. number of elements currently in the array minus the length of the array. c. length of the array plus the number of elements currently in the array. d. number of elements currently in the array. 15. When a Java program terminates and reports an exception, the error message contains which pieces of useful information? I. the compile and revision control history of the source code changes that caused the error II. the name of the exception that occurred III. the stack trace a. I, II only b. I, III only c. II, III only d. I, II, III 16. Which statement correctly describes the enhanced for loop? a. In the enhanced for loop, the element variable is assigned. In the basic for loop, the index variable is assigned. b. In the enhanced for loop, the index variable is assigned. In the basic for loop, the element variable is assigned. c. The enhanced for loop has a very specific purpose: modifying the contents of the array. d. The enhanced for loop has a very specific purpose: initializing the contents of the array. 17. Complete the following code snippet with the correct enhanced for loop so it iterates over the array without using an index variable.

String[] arr = { "abc", "def", "ghi", "jkl" }; ___________________ { System.out.print(str); } a. for (String str : arr) b. for (str : String arr) c. for (str[] : arr) d. for (arr[] : str) 18. What is the result of the following code?

for (double element : values) { element = 0; } a. The elements of the array values are initialized to zero. Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch7 b. The elements of the array element are initialized to zero. c. The first element of the array values is initialized to zero. d. The array values is not modified. 19. Which statements about the enhanced for loop are true for arrays of primitive data? I. It is suitable for all array algorithms. II. It does not allow the contents of the array to be modified. III. It does not require the use of an index variable. a. I, II only b. I, III only c. II, III only d. I, II, III 20. The enhanced for loop is a. convenient for traversing all elements in an array. b. convenient for traversing elements in a partially filled array. c. only used for arrays of integers. d. used to initialize all array elements to a common value. 21. Assume the array of integers values has been created and process is a method that has a single integer parameter. Which of the following is equivalent to the loop below?

for (int val: values) { process(val); } a. for (int i: values) {

process (i); i++; } b. for (int i = 1; i <= values.length; i++) { int val = values[i]; process (val); } c. for (int i = 0; i < values.length; i++) { int val = values[i]; process (val); } d. for (int i = 0; i < values.length; i++) { process (i); }

22. Assume the array of integers values has been created. Which condition must be used in the indicated area so the loop below will assign max the largest value in values? Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch7

int max = values[0]; for (int val: values) { if (/* Put condition here */) max = val; } a. max > val b. val > max c. values[val] > max d. max > values[val] 23. Assume the array of integers values has been created. Which condition must be used in the indicated area so the loop below will assign max the largest value in values?

int max = values[0]; for (int current = 1; current < values.length; current++) { if (/* Put condition here */) max = values[current]; } a. current > max b. max > current c. max > values[current] d. values[current] > max 24. Suppose you wish to write a method that returns the sum of the elements in partially filled array. Which is the best choice for a method header? a. public int sum(int[] values) b. public int sum() c. public int sum(int[] values, int currSize) d. public int sum(int[] values, int size, int currSize) 25. When the order of the elements is unimportant, what is the most efficient way to remove an element from an array? a. Delete the element and move each element after that one to a lower index. b. Replace the element to be deleted with the last element in the array. c. Replace the element to be deleted with the first element in the array. d. Replace the element with the next element. 26. When an array reading and storing input runs out of space a. the program could be recompiled with a bigger size for the array. b. the array could be "grown" using the growArray method. c. it automatically resizes to accommodate new elements. d. the array could be "grown" using the new command and the copyOf method. Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch7 27. It may be necessary to "grow" an array when reading inputs because a. the number of inputs may not be known in advance. b. arrays in Java must be resized after every 100 elements. c. arrays are based on powers of two. d. the only alternative is a bounds exception. 28. Which code snippet calculates the sum of all the even elements in an array values? a. int sum = 0; for (int i = 0; i < values.length; i++) { if ((values[i] % 2) == 0) { sum += values[i]; } } b. int sum = 0; for (int i = 0; i < values.length; i++) { if ((values[i] % 2) == 0) { sum++; } } c. int sum = 0; for (int i = 0; i < values.length; i++) { if ((values[i] / 2) == 0) { sum += values[i]; } } d. int sum = 0; for (int i = 0; i < values.length; i++) { if ((values[i] / 2) == 0) { sum++; } }

29. Which code snippet calculates the sum of all the elements in even positions in an array? a. int sum = 0; for (int i = 1; i < values.length; i+=2) { sum++; } b. int sum = 0; for (int i = 0; i < values.length; i++) { sum++; } c. int sum = 0;

Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch7 for (int i = 0; i < values.length; i++) { sum += values[i]; } d. int sum = 0; for (int i = 0; i < values.length; i = i + 2) { sum += values[i]; }

30. What (if anything) is wrong with the following code snippet, which searches for the searchedValue variable in the array data?

String[] data = { "abc", "def", "ghi", "jkl" }; String searchedValue = "ghi"; int pos = 0; boolean found = false; while (pos < data.length) { if (data[pos].equals(searchedValue)) { found = true; } else { found = false; } pos++; } if (found) { System.out.println("Found at position: " + pos); } else { System.out.println("Not found"); } a. There is nothing wrong. b. There is a compile-time error. c. There is a bounds error. d. There is a logic error. 31. Consider the following code snippet:

String[] data = { "abc", "def", "ghi", "jkl" }; String [] data2; In Java 6 and later, which statement copies the data array to the data2 array? Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch7 a. data2 = Arrays.copyOf(data, data2.length); b. data2 = Arrays.copyOf(data, data.length); c. data2 = Arrays.copyOf(data, data.size()); d. data2 = Arrays.copyOf(data); 32. Consider the following code snippet in Java 6 or later:

String[] data = { "abc", "def", "ghi", "jkl" }; String[] data2 = Arrays.copyOf(data, data.length - 1); What does the last element of data2 contain? a. "abc" b. "def" c. "ghi" d. "jkl" 33. Consider the following code snippet:

String[] data = { "abc", "def", "ghi", "jkl" }; Using Java 6 or later, which statement grows the data array to twice its size? a. data = Arrays.copyOf(data, 2 * data.length); b. data = Arrays.copyOf(data, 2); c. data = Arrays.copyOf(data, 2 * data); d. data = Arrays.copyOf(data, 2 * data.size()); 34. Consider the following code snippet:

String[] data = { "123", "ghi", "jkl", "def", "%&*" }; Which statement sorts the data array in ascending order? a. data = Arrays.sort(); b. Arrays.sort(data); c. data = Arrays.sort(data.length); d. data = Arrays.sort(data); 35. Consider the following code snippet. Which statement should be used to fill in the empty line so that the output will be [32, 54, 67.5, 29, 35]?

public static void main(String[] args) { double data[] = {32, 54, 67.5, 29, 35}; ______________ System.out.println(str); } a. String str = Arrays.format(data); Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch7 b. String str = data.toString(); c. String str = Arrays.toString(data); d. String str = str + ", " + data[i]; 36. Select the statement that reveals the logic error in the following method.

public static double minimum(double[] data) { double smallest = 0.0; for (int i = 0; i < data.length; i++) { if (data[i] < smallest) { smallest = data[i]; } } return smallest; } a. double m = minimum(new double[] { 1.2, -3.5, 6.6, 2.4 }); b. double m = minimum(new double[] { 1.2, 23.5, 16.6, -23.4 }); c. double m = minimum(new double[] { -10.2, 3.5, 62.6, 21.4 }); d. double m = minimum(new double[] { 12.2, 31.5, 6.6, 2.4 }); 37. Assume the following variable has been declared and given a value as shown:

int[] numbers = {9, 17, -4, 21 }; Which is the value of numbers.length? a. 3 b. 4 c. 9 d. 21 38. Assume the variable numbers has been declared to be an array that has at least one element. Which is the following represents the last element in numbers? a. numbers[numbers.length] b. numbers.length c. numbers[–1] d. numbers[numbers.length – 1] 39. What is the output of the following code snippet?

int[] values = { 1, 2, 3, 4}; values[2] = 24; values[values[0]] = 86; for (int i = 0; i < values.length; i++) Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch7

{ System.out.print (values[i] + " "); } a. 86 2 24 4 b. 86 24 3 4 c. 1 86 24 4 d. 1 2 24 86 40. What is the output of the following code snippet?

int[] values = { 10, 20, 30, 7}; int[] numbers = values; numbers[2] = 24; values[3] = numbers[0] + 6; System.out.println (numbers[2] + " " + numbers[3] + " " + values[2] + " " + values[3]); a. 24 0 30 16 b. 24 0 30 6 c. 24 7 30 16 d. 24 16 24 16 41. The integer array numbers will be filled with values from the Scanner object in. If there are more input values than there are spaces in the array, only enough values to fill the array should be read. The integer variable currentSize should be set to the number of values read. Partial code to do this is given below:

int[] numbers = new int[100]; Scanner in = new Scanner (System.in); int currentSize = 0; while (/* Put condition here */) { int value = in.nextInt(); numbers[currentSize] = value; currentSize++; } What condition will complete this code? a. currentSize < numbers.length && in.hasNextInt() b. currentSize < numbers.length || in.hasNextInt() c. currentSize <= numbers.length && in.hasNextInt() d. currentSize <= numbers.length || in.hasNextInt() 42. The method findLargest should return the largest of any number of double values. For example, the call findLargest (3.4, -2.6, 2.9) should return 3.4 and the call findLargest (9.2, 17.6, 3.4, 2.6, 2.9) should return 17.6. Partial code to do this is given below: Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch7

double findLargest (double... values) { double max = values[0]; // New code goes here return max; } What code will complete this method? a. for (double val: values) {

if (val > max) { max = val; } } b. for (int i = 1; i < values.length; i++) { if (i > max) { max = i; } } c. for (double val:values) { if (values[val] > max) { max = values[val]; } } d. for (int i = 1; i < values.length; i++) { if (values[i] > max) { max = i; } }

43. What will be printed by the statements below?

int[] values = { 4, 5, 6, 7}; for (int i = 1; i < values.length; i++) { values[i] = values[i – 1] + values[i]; } for (int i = 0; i < values.length; i++) { System.out.print (values[i] + " "); } a. 4 9 11 13 b. 4 9 15 22 Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch7 c. 9 11 13 7 d. 4 5 6 7 44. What will be printed by the statements below?

int[] values = { 4, 5, 6, 7}; values[0] = values[3]; values[3] = values[0]; for (int i = 0; i < values.length; i++) { System.out.print (values[i] + " "); } a. 7 5 6 4 b. 7 6 5 4 c. 7 5 6 7 d. 4 5 6 4 45. What will be printed by the statements below?

int[] values = { 10, 24, 3, 64}; int position = 0; for (int i = 1; i < values.length; i++) { if (values[i] > values[position]) { position = i; } } System.out.print (position); a. 0 b. 1 c. 2 d. 3 46. Assume the method createSomething has been defined as follows:

public static int [] createSomething (int start, int size) { int [] result = new int[size]; for (int i = 0; i < result.length; i++) { result[i] = start; start++; } return result; Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch7

} What is printed by the statement below?

System.out.print(Arrays.toString(createSomething(4, 3))); a. [3, 4, 5, 6] b. [4, 4, 4] c. [3, 3, 3, 3] d. [4, 5, 6] 47. Assume the method doSomething has been defined as follows:

public static int [] doSomething (int[] values) { int [] result = new int[values.length - 1]; for (int i = 0; i < result.length; i++) { result[i] = values[i] + values[i + 1]; } return result; } What is printed by the statements below?

int [] nums = {3, 18, 29, -2} ; System.out.print(Arrays.toString(doSomething(nums))); a. [4, 19, 30, -1] b. [21, 47, 27] c. [21, 50, 48] d. [3, 21, 47, 27] 48. Assume the method doSomething has been defined as follows:

public static void doSomething (int[] values, int p1, int p2) { int temp = values[p1]; values[p1] = values[p2]; values[p2] = temp; } What does the method do? a. It copies the integer array values to a new array. b. It swaps the integer values stored in positions p1 and p2 of the array values. c. It moves each element of the array values to a higher index position. Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch7 d. It inserts a new value into the array values. 49. Assume the method doSomething has been defined as follows:

public static void doSomething (int[] values, int p1, int p2) { int temp = values[p1]; values[p1] = values[p2]; values[p2] = values[p1]; } What does the method do? a. It copies the integer array values to a new array. b. It swaps the integer values stored in positions p1 and p2 of the array values. c. It moves each element of the array values to a higher index position. d. It overwrites the value stored in the integer array values at position p1 with the value stored in position p2. 50. Assume the method doSomething has been defined as follows:

public static void doSomething (int[] values) { for (int i = 1; i < values.length; i++) { values[i - 1] = values[i]; } } What does the method do? a. It copies the integer array values to a new array. b. It swaps the integer values stored in positions i and i - 1 of the array values. c. It moves each element of the array values to a lower index position and overwrites the first element. d. It overwrites all the values stored in the integer array values with the value stored in position 0. 51. Assume the method doSomething has been defined as follows:

public static int[] doSomething (int[] values) { int [] result = new int[values.length - 1]; for (int i = 0; i < result.length; i++) { result[i] = values[i + 1]; } return result; } What does the method do? a. It copies the integer array values to a new array. Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch7 b. It copies all but the first element in the integer array values to a new array. c. It moves each element of the array values to a lower index position and overwrites the first element. d. It overwrites all the values stored in the integer array values with the value stored in position 0. 52. The binary search is more efficient than the linear search, providing a. the size of the array is a power of two. b. the elements of the array are ordered. c. the elements of the array are unordered. d. the element being searched for is actually in the array. 53. This code snippet is an implementation of what algorithm?

int searchedValue = 42; int pos = 0; boolean found = false; while (pos < values.length && !found) { if (values[pos] == searchedValue) { found = true; } else { pos++; } } a. removing an array element b. finding the maximum value in an array c. calculating the mean of values in an array d. sequential search 54. Consider the code snippet below:

int searchedValue = 42; int pos = 0; boolean found = false; while (pos < values.length && !found) { if (values[pos] == searchedValue) { found = true; } else { pos++; } Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch7

} When the loop finishes what does the value of the boolean variable found indicate? a. the size of the array values b. whether or not the value 42 was found in the array c. whether or not the value 0 was found in the array d. the position where the value 42 is located in the array 55. The code snippet below is intended to perform a linear search on the array values to find the location of the value 42. What is the error in the code snippet?

int searchedValue = 42; int pos = 0; boolean found = true; while (pos < values.length && !found) { if (values[pos] == searchedValue) { found = true; } else { pos++; } } a. The boolean variable found should be initialized to false. b. The condition in the while loop should be (pos <= values.length && !found). c. The variable pos should be initialized to 1. d. The condition in the if statement should be (values[pos] <= searchedValue). 56. Which statements about array algorithms are true? I. The array algorithms are building blocks for many programs that process arrays. II. Java contains ready-made array algorithms for every problem situation. III. It is inefficient to make multiple passes through an array if you can do everything in one pass. a. I, II only b. I, III only c. II, III only d. I, II, III 57. Suppose you wish to use an array to solve a new problem. What is the first step to take in finding a solution? a. structure a program using methods b. adapt a built-in array algorithm c. decompose the problem into steps d. assemble a test program and run it Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch7 58. Suppose you wish to process an array of values and eliminate any potential duplicate values stored in the array. Which array algorithms might be adapted for this? a. find the minimum b. remove an element c. add an element d. calculate the sum of the elements 59. Which code snippet finds the largest value in an array that is only partially full? a. double largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } } b. double largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] < largest) { largest = values[i]; } } c. double largest = values[0]; for (int i = 1; i < currSize; i++) { if (values[i] > largest) { largest = values[i]; } } d. double largest = values[0]; for (int i = 1; i < currSize; i++) { if (values[i] < largest) { largest = values[i]; } }

60. Consider using a deck of cards as a way to visualize a shuffle algorithm. When two cards shuffle their position, what has to happen to the size of the array holding them? a. It increases by one. b. It decreases by one. c. It stays the same. d. It increases by two. 61. Consider the telephone book as a physical object that can help understand algorithms. What kind of algorithm might be visualized using it? a. sorting Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch7 b. searching c. finding the maximum d. Monte Carlo methods 62. Why is the use of physical objects helpful in algorithm design? a. It simulates the way the computer actually implements the algorithm. b. It is more abstract than using a pencil and paper. c. Because the constraints on physical things are the same as the constraints on bits and bytes. d. Many people feel it is less intimidating than drawing diagrams. 63. Consider the following code snippet:

int count = 0; int[][] numarray = new int[2][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { numarray[j][i] = count; count++; } } What is the value of numarray[1][2] after the code snippet is executed? a. 2 b. 5 c. 3 d. 4 64. How many elements can be stored in an array of dimension 2 by 3? a. 2 b. 3 c. 5 d. 6 65. Which one of the following statements is the correct declaration for a two-dimensional array of 20 rows and 2 columns of type int? a. int[][] num = new int[20][2]; b. int[][] num = new int[2][20]; c. int[][] num = new int[20,2]; d. int[][] num = new int[2,20]; 66. Consider the following code snippet:

int[][] numarray = { Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch7

{ 3, 2, 3 }, { 0, 0, 0 } }; System.out.print(numarray[0][0]); System.out.print(numarray[1][0]); What is the output of the given code snippet? a. 00 b. 31 c. 30 d. 03 67. Which one of the following is the correct definition for initializing data in a two-dimensional array with three rows and two columns? a. int[][] arr = {

{ 1, 1, 1 }, { 2, 2, 2 }, }; b. int[][] arr = { { 1, 1 }, { 2, 2 }, { 3, 3 } }; c. int[][] arr = { { 1, 1 } { 2, 2 } { 3, 3 } }; d. int[][] arr = { { 1, 1, 1 } { 2, 2, 2 } { 3, 3, 3 } };

68. Which one of the following statements is correct for displaying the value in the second row and the third column of a two-dimensional, size 3 by 4 array? a. System.out.println(arr[1][2]); b. System.out.println(arr[2][3]); c. System.out.println(arr[2][1]); d. System.out.println(arr[3][2]); 69. Consider the following code snippet:

int[][] arr = { { 13, 23, 33 }, Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch7

{ 14, 24, 34 } }; Identify the appropriate statement to display the value 24 from the given array? a. System.out.println(arr[1][2]); b. System.out.println(arr[2][2]); c. System.out.println(arr[1][1]); d. System.out.println(arr[2][1]); 70. Consider the following code snippet:

int val = arr[0][2]; Which value of arr is stored in the val variable? a. the value in the first row and the second column b. the value in the first row and the first column c. the value in the first row and the third column d. the value in the third row and the second column 71. Consider the following code snippet:

int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 } }; int val = arr[0][2] + arr[1][2]; System.out.println(val); What is the output of the given code snippet on execution? a. 5 b. 7 c. 9 d. 10 72. Which one of the following is a valid signature of a method with an integer two-dimensional array parameter of size 10 x 10? a. public void func(int[][] arr) b. public void func(int[10][] arr) c. public void func(int[][10] arr) d. public void func(int[10][10] arr) 73. Consider the following 2-dimensional array. Which expression gives the number of elements in the third row?

int[][] counts = { { 0, 0, 1 }, Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch7

{ 0, 1, 1, 2 }, { 0, 0, 1, 4, 5 }, { 0, 2 } }; a. counts[2].size() b. counts.length[2] c. counts.length d. counts[2].length 74. Consider the following code snippet:

int[][] arr = { { 1, 2, 3, 0 }, { 4, 5, 6, 0 }, { 0, 0, 0, 0 } }; int[][] arr2 = arr; System.out.println(arr2[2][1] + arr2[1][2]); What is the output of the given code snippet on execution? a. 5 b. 6 c. 7 d. 9 75. What is the output of the following code?

int[][] counts = { { 0, 0, 1 }, { 0, 1, 1, 2 }, { 0, 0, 1, 4, 5 }, { 0, 2 } }; System.out.println(counts[3].length); a. 2 b. 3 c. 4 d. 5 76. Assume the following variable has been declared and given a value as shown:

int[][] data = { Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch7

{9, 17, -4, 21 }, {15, 24, 0, 9}, {6, 2, -56, 8}, }; Which is the value of data.length? a. 4 b. 3 c. 12 d. 6 77. Assume the following variable has been declared and given a value as shown:

int[][] data = { {9, 17, -4, 21 }, {15, 24, 0, 9}, {6, 2, -56, 8}, }; Which is the value of data[0].length? a. 21 b. 12 c. 4 d. 3 78. Assume the following variable has been declared and given a value as shown:

int[][] data = { {9, 17, -4, 21 }, {15, 24, 0, 9}, {6, 2, -56, 8}, }; Which is the value of data[1][2]? a. 0 b. 17 c. 15 d. 2 79. Which statement(s) about the size of a Java array, array list, and string are true? I. The syntax for determining the size of an array, an array list, and a string in Java is consistent among the three. II. The string uses s.size(), while the array list uses a.length(). III. The array uses a.length, which is not a method call. a. I only b. II only Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch7 c. III only d. II, III only 80. If a programmer confuses the method required for checking the length of a string and uses size() instead of length(), what will happen? a. The program will crash. b. The program will not compile. c. The program will run but will produce an uncertain result. d. The compiler will automatically correct the error. 81. Java 7 introduced enhanced syntax for declaring array lists, which is termed a. angle brackets. b. method lists. c. diamond syntax. d. symmetric slants. 82. The following statement gets an element from position 4 in an array:

x = a[4]; What is the equivalent operation using an array list? a. x = a.get(4); b. x = a.get(); c. x = a.get[4]; d. x = a[4]; 83. Which statements are true regarding the differences between arrays and array lists? I. Arrays are better if the size of a collection will not change. II. Array lists are more efficient than arrays. III. Array lists are easier to use than arrays. a. I, II only b. I, III only c. II, III only d. I, II, III 84. What is the value of the count variable after the execution of the given code snippet?

ArrayList<Integer> num = new ArrayList<Integer>(); num.add(1); num.add(2); num.add(1); int count = 0; for (int i = 0; i < num.size(); i++) { if (num.get(i) % 2 == 0) { Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch7

count++; } } a. 1 b. 2 c. 0 d. 3 85. Which one of the following code snippets accepts the integer input in an array list named num1 and stores the odd integers of num1 in another array list named oddnum? a. ArrayList<Integer> num1 = new ArrayList<Integer>(); ArrayList<Integer> oddnum = new ArrayList<Integer>(); int data; Scanner in = new Scanner(System.in); for (int i = 0; i < 10; i++) { data = in.nextInt(); num1.add(data); if (num1.get(i) % 2 == 0) { oddnum.add(num1.get(i)); } } b. ArrayList<Integer> num1 = new ArrayList<Integer>(); ArrayList<Integer> oddnum = new ArrayList<Integer>(); int data; Scanner in = new Scanner(System.in); for (int i = 0; i < 10; i++) { data = in.nextInt(); num1.add(data); if (num1.get(i) % 2 != 0) { oddnum.add(num1.get(i)); } } c. ArrayList<Integer> num1 = new ArrayList<Integer>(); ArrayList<Integer> oddnum = new ArrayList<Integer>(); int data; Scanner in = new Scanner(System.in); for (int i = 0; i < 10; i++) { data = in.nextInt(); num1.add(data); if (num1.get(i) % 2 == 0) { oddnum.add(num1[i]); } } d. ArrayList<Integer> num1 = new ArrayList<Integer>(); ArrayList<Integer> oddnum = new ArrayList<Integer>(); int data; Scanner in = new Scanner(System.in);

Powered by Cognero

Page 25


Name:

Class:

Date:

testbank-bj-7-ch7 for (int i = 0; i < 10; i++) { data = in.nextInt(); num1.add(data); if (num1[i] % 2 != 0) { oddnum.add(num1[i]); } }

86. Consider the following code snippet:

ArrayList<Integer> num1 = new ArrayList<Integer>(); int data; Scanner in = new Scanner(System.in); for (int i = 0; i < 5; i++) { data = in.nextInt(); num1.add(data); if (data == 0 && num1.size() > 3) { num1.remove(num1.size() - 1); } } System.out.println("size is : " + num1.size()); What is the output of the given code snippet if the user enters 1,2,0,0,1 as the input? a. size is : 1 b. size is : 2 c. size is : 4 d. size is : 0 87. Which one of the following statements about declaring an array list as a method parameter is true? a. An array list declared as a method parameter should be accompanied with its size. b. An array list declared as a method parameter is a constant value by default. c. An array list value cannot be modified in a method when the array list is declared as a parameter. d. An array list value can be modified inside the method. 88. Which one of the following is a correct declaration for a method named passAList with the array list num of size 5 as a parameter? a. public static void passAList(ArrayList<Integer> num[5]) b. public static void passAList(ArrayList<Integer> num, 5) c. public static void passAList(ArrayList<Integer> num) d. public static void passAList(num) 89. Consider the following code snippet:

public static void check(ArrayList<Integer> chknum1) Powered by Cognero

Page 26


Name:

Class:

Date:

testbank-bj-7-ch7

{ int cnt = 0; for(int i = 0; i < chknum1.size(); i++) { if(chknum1.get(i) == 0) { cnt++; } } System.out.println("The total 0 values in the list are: " + cnt); } Which one of the following is true about the check method in the given code snippet? a. The check method counts all the elements with value 0 in an array list passed as a parameter to the method. b. The check method removes all the elements with value 0 from an array list passed as a parameter to the method. c. The check method counts all the elements with value 0 in an array list passed as a parameter to a method and also returns the count. d. The check method adds 0 to the elements of an array list as a parameter to a method and also returns the array list. 90. Consider the following line of code for calling a method named func1:

func1(listData, varData); Which one of the following method headers is valid for func1, where listData is an integer array list and varData is an integer variable? a. public void func1(int[] listData, int varData) b. public void func1(ArrayList<Integer> listData, varData) c. public void func1(ArrayList<Integer> ldata, int vdata) d. public void func1(int vdata, ArrayList<Integer> ldata) 91. What is the output of the following code snippet?

public static int check(ArrayList<Integer> listData) { int sum = 0; for (int i = 0; i < listData.size(); i++) { sum = sum + listData.get(i); } return sum; } public static void main(String[] args) { ArrayList<Integer> vdata = new ArrayList<Integer>(); int rsum; Powered by Cognero

Page 27


Name:

Class:

Date:

testbank-bj-7-ch7

for (int cnt = 0; cnt < 3; cnt++) { vdata.add(cnt + 1); } rsum = check(vdata); System.out.println(rsum); } a. 4 b. 2 c. 3 d. 6 92. What is the result of the following definition of an array list?

ArrayList<Double> points; a. The statement causes a compile time error as the size of the array list is not defined. b. The statement creates an array list of size 0. c. The statement creates an array list with unlimited size. d. The statement defines an array list reference but does not create an array list. 93. Consider the following code snippet:

ArrayList<Double> somedata = new ArrayList<Double>(); somedata.add(10.5); What is the size of the array list somedata after the given code snippet is executed? a. 0 b. 1 c. 10 d. 2 94. What is the output of the following code snippet?

ArrayList<Integer> num; num.add(4); System.out.println(num.size()); a. 1 b. 0 c. 4 d. Error because num is not initialized 95. Your program needs to store an integer sequence of unknown length. Which of the following is most suitable to use? a. An array declared as int[] marks; Powered by Cognero

Page 28


Name:

Class:

Date:

testbank-bj-7-ch7 b. A array list declared as ArrayList<Integer> marks = new ArrayList<Integer>(); c. An array declared as int marks[10000]; d. An array declared as int marks[10]; 96. Consider the following code snippet:

ArrayList<Integer> arrList = new ArrayList<Integer>(); for (int i = 0; i < arrList.size(); i++) { arrList.add(i + 3); } What value is stored in the element of the array list at index 0? a. 0 b. 3 c. 6 d. None 97. What should you check for when calculating the largest value in an array list? a. The array list contains at least one element. b. The array list contains at least two elements. c. The array list contains the minimum value in the first element. d. The array list contains the maximum value in the first element. 98. Which one of the following is the correct code snippet for calculating the largest value in an integer array list arrList of size 10? a. int maximum = 0; for (int counter = 1; counter < arrList.size(); counter++) { if (arrList.get(counter) > maximum) { maximum = arrList.get(counter); } } b. int maximum = arrList.get(0); for (int counter = 1; counter < arrList.size(); counter++) { if (arrList.get(counter) > maximum) { maximum = arrList.get(counter); } } c. int maximum = arrList.get(1); for (int counter = 1; counter < arrList.size(); counter++) { if (arrList.get(counter) > maximum) { maximum = arrList.get(counter); } }

Powered by Cognero

Page 29


Name:

Class:

Date:

testbank-bj-7-ch7 d. int maximum = arrList.get(0);

for (int counter = 1; counter > arrList.size(); counter++) { if (arrList.get(counter) < maximum) { maximum = arrList.get(counter); } }

99. What is the value of the count variable after the execution of the code snippet below?

ArrayList<Integer> somenum = new ArrayList<Integer>(); somenum.add(1); somenum.add(2); somenum.add(1); int count = 0; for (int index = 0; index < somenum.size(); index++) { if (somenum.get(index) % 2 == 0) { count++; } } a. 1 b. 2 c. 3 d. 0 100. Which one of the following code snippets accepts the integer input in an array list named num1 and stores the even integers of num1 in another array list named evennum? a. ArrayList<Integer> num1 = new ArrayList<Integer>(); ArrayList<Integer> evennum = new ArrayList<Integer>(); Scanner in = new Scanner(System.in); int data; for (int i = 0; i < 10; i++) { data = in.nextInt(); num1.add(data); if (num1.get(i) % 2 == 0) { evennum.add(num1.get(i)); } } b. ArrayList<Integer> num1 = new ArrayList<Integer>(); ArrayList<Integer> evennum = new ArrayList<Integer>(); Scanner in = new Scanner(System.in); int data; for (int i = 0; i < 10; i++) { data = in.nextInt(); num1.add(data);

Powered by Cognero

Page 30


Name:

Class:

Date:

testbank-bj-7-ch7 if (num1.get(i) % 2 != 0) { evennum.add(num1.get(i)); } } c. ArrayList<Integer> num1 = new ArrayList<Integer>(); ArrayList<Integer> evennum = new ArrayList<Integer>(); Scanner in = new Scanner(System.in); int data; for int i = 0; i < 10; i++) { data = in.nextInt(); num1.add(data); if (num1.get(i) % 2 != 0) { evennum[i] = num1[i]; } } d. ArrayList<Integer> num1 = new ArrayList<Integer>(); ArrayList<Integer> evennum = new ArrayList<Integer>(); Scanner in = new Scanner(System.in); int data; for (int i = 0; i < 10; i++) { data = in.nextInt(); num1.add(data); if (num1.get(i) % 2 == 0) { evennum[i] = num1[i]; } }

101. Which one of the following is a correct declaration for a method named passAList that has as arguments an array list myList of size 10 and an integer array intArr of size 20, and that modifies the contents of myList and intArr? a. public void passAList(ArrayList<Integer> myList(10), int[] intArr) b. public void passAList(ArrayList<Integer> myList, int[20] intArr) c. public void passAList(ArrayList<Integer> myList, int[] intArr) d. public void passAList(ArryaList<Integer> myList, int intArr) 102. Which statement is true about the code snippet below?

ArrayList<String> names = new ArrayList<String>(); names.add("John"); names.add("Jerry"); ArrayList<String> friends = names; friends.add("Harry"); a. The final size of names is 2; the final size of friends is 3. b. The final size of names is 3; the final size of friends is 2. c. The final size of names is 3; the final size of friends is 3. d. compilation error Powered by Cognero

Page 31


Name:

Class:

Date:

testbank-bj-7-ch7 103. Which statement is true about the code snippet below?

ArrayList<String> names = new ArrayList<String>(); names.add("John"); names.add("Jerry"); ArrayList<String> friends = new ArrayList<String>(names); friends.add("Harry"); a. The final size of names is 2; the final size of friends is 3. b. The final size of names is 3; the final size of friends is 2. c. The final size of names is 3; the final size of friends is 3. d. compilation error 104. Consider the following code snippet:

public static void main(String[] args) { ArrayList<String> names = new ArrayList<String>(); names.add("John"); names.add("Jerry"); names.add("Janet"); ArrayList<String> names2 = reverse(names); } public static ArrayList<String> reverse(ArrayList<String> names) { ArrayList<String> result = new ArrayList<String>(); for (int i = names.size() - 1; i >= 0; i--) { result.add(names.get(i)); } return <String>result; } Which statement is true after the main method is executed? a. names contains "Janet", "Jerry", "John" in this order. b. names contains "John", "Jerry", "Janet" in this order. c. reverse method has a bound error. d. Compilation error due to the return statement in reverse method. 105. Which statement is true about the code snippet below?

public static void main(String[] args) { Scanner in = new Scanner(System.in); ArrayList<Double> inputs = new ArrayList<Double>(); int ind = 0; Powered by Cognero

Page 32


Name:

Class:

Date:

testbank-bj-7-ch7

while (in.hasNextDouble()) { inputs.set(ind, in.nextDouble()); ind++; } } a. The code adds all input numbers to the array list. b. The code has compile-time error. c. The array list is full after 100 numbers are entered. d. The code has a run-time error. 106. Which statement is true about the code snippet below?

ArrayList<String> names = new ArrayList<String>(); names.add("John"); names.add("Jerry"); ArrayList<String> friends = new ArrayList<String>(names); names.add("Harry"); a. The final size of names is 2; the final size of friends is 3. b. The final size of names is 3; the final size of friends is 2. c. The final size of names is 3; the final size of friends is 3. d. compilation error 107. When an integer literal is added to an array list declared as ArrayList<Integer>, Java performs: a. casting b. trimming c. auto-boxing d. auto-fixing 108. What is the output of the following statements?

ArrayList<String> names = new ArrayList<String>(); names.add("Bob"); names.add(0, "Ann"); names.remove(1); names.add("Cal"); names.set(1, "Tony"); for (String s : names) { System.out.print(s + ", "); } a. Cal, Bob, Ann b. Ann, Bob Powered by Cognero

Page 33


Name:

Class:

Date:

testbank-bj-7-ch7 c. Ann, Tony d. Cal, Bob, Tony 109. What is the output of the following statements?

ArrayList<String> names = new ArrayList<String>(); names.add("Bob"); names.add(0, "Ann"); names.remove(1); names.add("Cal"); names.set(2, "Tony"); for (String s : names) { System.out.print(s + ", "); } a. Cal, Bob, Ann b. Ann, Bob c. Ann, Cal, Tony d. array list bound error 110. What is the output of the following statements?

ArrayList<String> cityList = new ArrayList<String>(); cityList.add("London"); cityList.add("New York"); cityList.add("Paris"); cityList.add("Toronto"); cityList.add("Hong Kong"); cityList.add("Singapore"); System.out.print(cityList.size()); System.out.print(" " + cityList.contains("Toronto")); System.out.print(" " + cityList.indexOf("New York")); System.out.println(" " + cityList.isEmpty()); a. 5 true 1 false b. 6 true 2 false c. 5 false 1 false d. 6 true 1 false 111. What should you check for when calculating the smallest value in an array list? a. The array list contains at least one element. b. The array list contains at least two elements. c. The array list contains the maximum value in the first element. d. The array list contains the minimum value in the first element. Powered by Cognero

Page 34


Name:

Class:

Date:

testbank-bj-7-ch7 112. Which one of the following is the correct code snippet for calculating the largest value in an integer array list aList? a. int max = 0; for (int count = 1; count < aList.size(); count++) { if (aList.get(count) > max) { max = aList.get(count); } } b. int max = aList.get(0); for (int count = 1; count < aList.size(); count++) { if (aList.get(count) > max) { max = aList.get(count); } } c. int max = aList[1]; for (int count = 1; count < aList.size();count++) { if (aList.get(count) > max) { max = aList.get(count); } } d. int max = aList.get(0); for (int count = 1; count > aList.size();count++) { if (aList.get(count) >= max) { max = aList.get(count); } }

113. Consider the following code snippet, where the array lists contain elements that are stored in ascending order:

ArrayList<Integer> list1 = new ArrayList<Integer>(); ArrayList<Integer> list2 = new ArrayList<Integer>(); . . . int count = 0; for (int i = 0; i < list1.size() && i < list2.size(); i++) { if (list1.get(i) == list2.get(i)) { count++; } } Which one of the following descriptions is correct for the given code snippet? a. The code snippet finds the highest value out of the two array lists. b. The code snippet finds the lowest value out of the two array lists. Powered by Cognero

Page 35


Name:

Class:

Date:

testbank-bj-7-ch7 c. The code snippet compares the values of two array lists and stores the count of total matches found. d. The code snippet adds the values of the two array lists. 114. What will be printed by the statements below?

ArrayList<String> names = new ArrayList<String>(); names.add("Annie"); names.add("Bob"); names.add("Charles"); names.set(2, "Doug"); names.add(0, "Evelyn"); System.out.print (names); a. [Annie, Bob, Charles, Doug, Evelyn] b. [Evelyn, Annie, Bob, Doug] c. [Evelyn, Doug, Charles] d. [Evelyn, Annie, Doug, Charles] 115. What will be printed by the statements below?

ArrayList<String> names = new ArrayList<String>(); names.add("Annie"); names.add("Bob"); names.add("Charles"); for (int i = 0; i < 3; i++) { String extra = names.get(i); names.add (extra); } System.out.print (names); a. [Annie, Bob, Charles, Annie, Bob, Charles] b. [Annie, Bob, Charles, Charles, Bob, Annie] c. [Annie, Annie, Bob, Bob, Charles, Charles] d. [Annie, Bob, Charles, Bob, Charles] 116. Regression testing is: a. the process of stepping code forward and backward inside a debugger. b. the process of testing each method with values to exercise its limits. c. the process of testing each version of a program against a test suite. d. the process of storing different versions of a program. 117. A collection of test cases that can be used on future versions of a program is called: a. a test suite. Powered by Cognero

Page 36


Name:

Class:

Date:

testbank-bj-7-ch7 b. cycling. c. debugging. d. version control.

Powered by Cognero

Page 37


Name:

Class:

Date:

testbank-bj-7-ch7 Answer Key 1. a 2. d 3. b 4. a 5. c 6. c 7. a 8. b 9. a 10. b 11. c 12. b 13. c 14. a 15. c 16. a 17. a 18. d 19. c 20. a 21. c 22. b 23. d 24. c 25. b Powered by Cognero

Page 38


Name:

Class:

Date:

testbank-bj-7-ch7 26. d 27. a 28. a 29. d 30. d 31. b 32. c 33. a 34. b 35. c 36. d 37. b 38. d 39. c 40. d 41. a 42. a 43. b 44. c 45. d 46. d 47. b 48. b 49. b 50. c 51. b Powered by Cognero

Page 39


Name:

Class:

Date:

testbank-bj-7-ch7 52. b 53. d 54. b 55. a 56. b 57. c 58. b 59. c 60. c 61. b 62. d 63. b 64. d 65. a 66. c 67. b 68. a 69. c 70. c 71. c 72. a 73. d 74. b 75. a 76. b Powered by Cognero

Page 40


Name:

Class:

Date:

testbank-bj-7-ch7 77. c 78. a 79. c 80. b 81. c 82. a 83. b 84. a 85. b 86. c 87. d 88. c 89. a 90. c 91. d 92. d 93. b 94. d 95. b 96. d 97. a 98. b 99. a 100. a 101. c 102. c Powered by Cognero

Page 41


Name:

Class:

Date:

testbank-bj-7-ch7 103. a 104. d 105. d 106. b 107. c 108. c 109. d 110. d 111. a 112. b 113. c 114. b 115. a 116. c 117. a

Powered by Cognero

Page 42


Name:

Class:

Date:

testbank-bj-7-ch8

Indicate the answer choice that best completes the statement or answers the question. 1. Which of the following is considered by the text to be the most important consideration when designing a class? a. Each class should represent an appropriate mathematical concept. b. Each class should represent a single concept or object from the problem domain. c. Each class should represent no more than three specific concepts. d. Each class should represent multiple concepts only if they are closely related. 2. Which of the following questions should you ask to help determine if a proposed class design is on the right track? a. Does the class name contain eight or fewer characters? b. Is the class name a verb? c. Can I visualize an object of the class? d. Does the class name describe the tasks that this class will accomplish? 3. Which class category has static methods and constants, but no objects? a. Real-life entity abstraction b. Actor class c. Utility class d. Concept class 4. A class named CurrencyTranslator would most probably fall into which of the following class categories? a. Actor classes b. Starter classes c. Abstract entities d. Utility classes 5. Why does the Scanner class belong to the category of classes known as actors? a. It acts as an interface between your program and the command line. b. It serves as an abstract entity that represents a user of your program. c. It plays an important part in streamlining the operation of your system. d. It performs a task, such as scanning a stream for numbers and characters. 6. Which of the following would be an appropriate name for a game-related class? a. CompletedLevelOne b. InitialLevel c. ResetCurrentLevel d. AscendToFinalLevel 7. Which of the following most likely indicates that you have chosen a good name for your class? a. The name consists of a single word. b. You can tell by the name what an object of the class is supposed to represent. c. You can easily determine by the name how many concepts the class represents. d. The name is the task the class will perform.

Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch8 8. Which of the following describes the first thing you should do when beginning a new object-oriented programming activity? a. Consider how many concepts each class should represent. b. Determine which categories of classes may be needed for the project. c. Decide what combination of functions and methods are appropriate for the project. d. Identify the objects and the classes to which they belong. 9. Which of the following is a true statement regarding consistency in coding? a. Inconsistencies nearly always produce fatal flaws. b. Inconsistencies are an annoyance, because they can be so easily avoided. c. Consistency is not important in programming. d. Consistency always requires extra coding. 10. Under which of the following conditions would the public interface of a class be considered cohesive? a. All of its features are public and none of its features are static. b. The quality of the public interface is rated as moderate to high. c. All of its features are related to the concept that the class represents. d. It is obvious that the public interface refers to multiple concepts. 11. General Java variable naming conventions would suggest that a variable named NICKEL_VALUE would most probably be declared using which of the following combinations of modifiers? a. public void final b. public static final double c. private static double d. private static 12. Which of the following is a good indicator that a class is overreaching and trying to accomplish too much? a. The class has more constants than methods b. The public interface refers to multiple concepts c. The public interface exposes private features d. The class is both cohesive and dependent. 13. Given the following class definition, which of the following are considered part of the class’s public interface?

public class CashRegister { public static final double DIME_VALUE = 0.1; private static int objectCounter; public void updateDimes(int dimes) {. . .} private boolean updateCounter(int counter) {. . .} } a. objectCounter and updateCounter b. DIME_VALUE and objectCounter c. DIME_VALUE and updateDimes Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch8 d. updateDimes and updateCounter 14. A class (ClassOne) is considered to have a dependency on another class (ClassTwo) under which of the following conditions? a. ClassOne and ClassTwo both use a third class ClassThree. b. The public interfaces of both classes are cohesive. c. ClassTwo uses objects of ClassOne. d. ClassOne uses objects of ClassTwo. 15. A UML class diagram would be most useful in visually illustrating which of the following? a. the cohesiveness of a class’s interface. b. the amount of complexity of a class’s interface. c. dependencies between classes. d. relationships between classes and their interfaces. 16. Why is it generally considered good practice to minimize dependencies between classes? a. Low dependencies increases the operational efficiency of a program. b. High dependency implies less interface cohesion. c. High dependency increases program maintenance and hinders code reuse. d. Low dependency decreases the probability of code redundancy. 17. Which of the following represents a good strategy regarding cohesion and class dependencies? a. Maximize cohesion and remove unnecessary dependencies. b. Minimize cohesion and remove unnecessary dependencies. c. Maximize both cohesion and dependencies. d. Minimize cohesion and maximize dependencies. 18. Which of the following describes an immutable class? a. A class where all accessor and mutator methods are public. b. A class that has no accessor methods, but does have mutator methods. c. A class that has accessor methods, but does not have mutator methods. d. A class that has both accessor and mutator methods. 19. Which type of method modifies the object on which it is invoked? a. Constructor method. b. Static method. c. Accessor method. d. Mutator method. 20. The String class is an example of which of the following types of classes? a. Static class. b. Immutable class. c. Abstract class. d. Mutable class. Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch8 21. Which of the following is true regarding objects created from immutable classes? a. It is safe to give out references to immutable class objects freely. b. An immutable object can only be modified by its mutator method. c. It is not advisable to return immutable object references from accessor methods. d. Immutable classes do not have constructors. 22. Which of the following is an example of an immutable class? a. Math. b. Scanner. c. String. d. System. 23. Judging by the name of the method, which of the following methods would most likely be a mutator method? a. getListOfDeposits. b. printAccountBalance. c. isOverdrawn. d. updateDeposit. 24. Which statement is true for syntactically correct classes? a. They must have both mutator and accessor methods. b. They must have accessors, and optionally may have mutators. c. They must have mutators, and optionally may have accessors. d. They may have either mutator or accessor methods, or both. 25. Mutator methods exhibit which of the following types of side effect? a. Modification of private instance variables. b. Modification of parameter variable. c. Production of printed output. d. Acceptance of text input. 26. Which of the following is true regarding side effects of methods? a. Modification of private instance variables should be restricted to primitive data types. b. Modification of parameter varibles should never be allowed. c. Side effects involving standard output should be limited to String data. d. Minimize side effects that go beyond modification of private instance variables. 27. Given the following method header, other would be classified as which of the following parameter types?

public void transfer(double amount, BankAccount other) a. Private instance variable. b. Parameter variable. c. Global variable. Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch8 d. Mutable variable. 28. Which of the following does NOT describe a particular side effect related to standard output? a. Messages printed in a particular language may be of limited usefulness. b. Methods that rely on standard output have limited usefulness in embedded systems. c. Programmers may be surprised by unexpected method actions. d. Programmers may need values for purposes other than informational messages. 29. Why can’t Java methods change parameters of primitive type? a. Java methods can have no actual impact on parameters of any type. b. Parameters of primitive type are considered by Java methods to be local variables. c. Parameters of primitive type are immutable. d. Java methods cannot accept parameters of primitive type. 30. Which of the following classifications of method behavior is accurate? a. Methods that do not change parameter variables always have side effects. b. Methods that change parameter variables do not have side effects. c. Methods that change parameter variables always have side effects. d. Methods that do not change parameter variables never have side effects. 31. Which of the following can potentially be changed by a Java method? a. An object reference parameter. b. The state of an object reference parameter’s attribute. c. A primitive parameter. d. A String parameter. 32. Which of the following classifications of method behavior produces acceptable side effects? a. Accessor methods that do not change parameter variables. b. Mutator methods that do not change parameter variables. c. Any method that changes a parameter variable. d. Any method that changes another object. 33. Which of the following statements is true regarding method parameters in Java? a. All method parameters use the call-by-value mechanism. b. Only method parameters of primitive type use the call-by-value mechanism. c. All method parameters use the call-by-reference mechanism. d. Only method parameters of object type use the call-by-value mechanism. 34. In Java, which of the following mechanisms describe the copying of an object reference into a parameter variable? a. Call-by-reference . b. Call-by-value. c. Call-by-precondition. d. Call-by-object.

Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch8 35. What is the name of a class that has only accessor methods and no mutators methods? a. Utility b. Static c. Immutable d. Actor 36. Consider the method in the following code snippet:

public void getRewardPoints() { System.out.println(“Your Reward Points balance is now “ + pointBalance); } Which of the following statements would not be a valid criticism of the design of this method? a. It violates the design rule of minimizing the dependencies between classes. b. It assumes that the message will always need to be in English. c. It might not work in an embedded system. d. It should not be a separate method since it is only one line long. 37. Consider the partial Date class below which represents a day of the year.

public class Date { private int month; private int day;

// // //

A value between 1 and 12 A value between 1 and the last day of the month

public int getMonth() { return month; } public void setMonth(int newMonth) { if (newMonth >= 1 && newMonth <= 12) { month = newMonth; } } public int getDay() { return day; } private int lastDayOfMonth() { switch(month) { case 9: case 4: case 6: case 11: return 30; case 2: return 28; default: return 31; } } Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch8

} What type of method is getMonth? a. mutator b. constructor c. accessor d. immutable 38. Consider the partial Date class below which represents a day of the year.

public class Date { private int month; private int day;

// // //

A value between 1 and 12 A value between 1 and the last day of the month

public int getMonth() { return month; } public void setMonth(int newMonth) { if (newMonth >= 1 && newMonth <= 12) { month = newMonth; } } public int getDay() { return day; } private int lastDayOfMonth() { switch(month) { case 9: case 4: case 6: case 11: return 30; case 2: return 28; default: return 31; } } } What type of method is setMonth? a. mutator b. accessor c. constructor d. immutable 39. Consider the partial Date class below (method signatures and instance variables) which represents a day of the year:

public class Date { Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch8

private int month; private int day;

// A value between 1 and 12 // A value between 1 and the last day // of the month public int getMonth() { } // accessor method public void setMonth(int newMonth) { } // mutator method public int getDay() { } // accessor method private int lastDayOfMonth() { } // helper method } It has been suggested the accessor method below be added to the class to return the Date one day later than the given date:

public Date getNextDate() { if (day == lastDayOfMonth()) { month++; if (month == 12) { month = 1; } day = 1; } else { day++; } return this; } What is wrong with this design? a. You cannot return this from a method. b. It uses lastDayOfMonth, a private method of the class. c. It has the side effect of changing the Date. d. Since it returns a Date other than this one, the class is not consistent. 40. Which is an example of a class that needs to keep track of a total, i.e., a quantity that can go up and down? a. The string class. b. The Scanner class. c. The BankAccount class. d. The Shape class. 41. It is common for certain classes to keep track of how many times certain events have occurred over the life of an object. This is done using a. A private instance variable within the class. b. A local variable within a mutator method. c. A notification event to a helper class. d. An array of objects. 42. What mechanism is used by a class that is designed to collect and store a growing set of values? a. A local variable. b. A string. Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch8 c. An array list or array. d. Auto-boxing. 43. When an object is intended to set and manage properties, where should those properties be stored? a. An array as a local variable in a method. b. Instance variables. c. The main method of the program. d. An off-site database. 44. Suppose an object is intended to store its current position in a 2D array using private instance variables:

private int row; private int column; Which code represents a method that would move the current position of the object one column to the right on the grid? a. public void moveRight() {

column--; } b. public void moveRight() { row--; column++; } c. public void moveRight() { row++; column++; } d. public void moveRight() { column++; }

45. Suppose an object is intended to store its current position in a 2D array using private instance variables and a mutator:

private int row; private int column; public void moveLeft() { column--; } What problem could be encountered with the method moveLeft(), which is intended to move the current position of the object to the left one column on the grid? a. The method should be changing the row instance variable. b. The method should be incrementing the column instance variable. c. The method might cause the instance variables to go out of the bounds of the 2D array. Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch8 d. The method should be changing local variables instead of instance variables. 46. Which of the following types of methods are invoked on objects? a. Static method. b. Class method. c. Instance method. d. Either static or instance methods. 47. A static method can have which of the following types of parameters? a. Only implicit parameters. b. Only parameter variables. c. Both implicit parameters parameter variables. d. A static method cannot have parameter variables. 48. Which of the following constitutes a common reason for creating a static method? a. To encapsulate a computation that involves only numbers. b. To implement a computation that only involves implicit parameters. c. To test a computation prior to implementing it in a class. d. To improve efficiency by reducing overhead associated with the use of objects. 49. The use of the static keyword in a method declaration implies which of the following? a. The method can only operate on immutable objects. b. The method can only be called from within the main method. c. The method cannot be overloaded. d. The method cannot be invoked on an instance of an object. 50. Which of the following statements regarding static methods is true? a. Static methods are not very common. b. Static methods should be liberally used within classes. c. Use of static methods usually leads to good object-oriented design. d. Static methods can be easily evolved to add more functionality. 51. Why is a static variable also referred to as a class variable? a. There is a single copy available to all objects of the class. b. It is encapsulated within the class. c. Each class has one and only one static variable. d. It is stored in the separate class area of each object. 52. In which of the following cases could a static variable be declared as something other than private? a. When it will be accessed by multiple objects. b. When implementing static constants. c. When declared inside a private method. d. Static variables should never be declared as anything but private. Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch8 53. Which of the following classes has a static variable that is commonly used when communicating with standard output? a. Scanner. b. String. c. System. d. Object. 54. Which of the following statements is generally true regarding static methods and variables? a. The use of static variables and methods should be minimized. b. The use of static variables and methods should be maximized. c. A lot of static methods and variables indicate a well-designed object-oriented system. d. Always choose static methods and variables over similar object-based implementations. 55. Where in a class should static variables be declared and initialized? a. Inside the constructor method. b. Inside the class, but outside of any method body. c. Outside the class – in a separate designated static class. d. Outside the class, but inside the same physical file. 56. When are statements in a class-level initialization block executed? a. Before the code in the class constructor is executed. b. Once when the class is loaded. c. Whenever objects of the class are used to access methods. d. After the code in the class constructor is executed. 57. When are statements in a class-level static initialization block executed? a. Before the code in the class constructor is executed. b. Once when the class is loaded. c. Whenever objects of the class are used to access methods. d. After the code in the class constructor is executed. 58. Which of the following are considered members of a class? a. Private instance variables and methods only. b. All instance variables and methods. c. Non-static instance variables and methods only. d. Public instance variables and methods only. 59. Consider the following code snippet:

public class RewardPointsAccount { private int currentRewardPointBalance; private static int level1Cutoff = 15000; ... } Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch8 If a program instantiates four objects using this class, which of the following statements will be true? a. Each object will have a currentRewardPointBalance instance variable and a level1Cutoff instance variable. b. All objects will share a single currentRewardPointBalance class variable and a level1Cutoff class variable. c. Each object will have a currentRewardPointBalance instance variable, but all objects will share a level1Cutoff class variable. d. All objects will share a currentRewardPointBalance class variable and each object will have a level1Cutoff instance variable. 60. Consider the following code snippet:

public class RewardPointsAccount { private int currentRewardPointBalance; private int level1Cutoff = 15000; public void process(boolean isEliteCustomer) { int level1Cutoff = 15000; if (isEliteCustomer) { this.level1Cutoff = 12500; . . . } } Which of the following statements is true? a. It is illegal to declare the level1Cutoff variable within the process method b. The code within the process method changes the value of the instance variable level1Cutoff for elite customers c. The level1Cutoff variable within the process method does not change the level1Cutoff instance variable for elite customers d. The level1Cutoff class variable cannot have the same name as the level1Cutoff local variable within the process method 61. A new method, getMonthName, to get the name of the Date's month ("January", February", etc.) is to be added to the class Date. The Date class already has a class variable that stores the month as an integer. Which of the following headers should the new method have? a. public String getMonthName(int month) b. public String getMonthName() c. public void getMonthName(String monthName) d. public void getMonthName(int month, String monthName) 62. A new method, getMonthName, to get the name of the Date's month ("January", February", etc.) is to be added to the class Date. How will the instance variables need to be changed to handle this new method? Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch8 a. The type of the month instance variable will need to be changed to String. b. A new String variable called monthName will need to be added to the class. c. A new class called MonthNameAndNumber will need to be created to store both the name and number of the month and the type of the instance variable month will need to be changed to MonthNameAndNumber. d. No change is needed. 63. Can the method lastDayOfMonth be changed to be a static method by just changing the header to the following?

private static int lastDayOfMonth() a. No. It could no longer access the month instance variable. b. No. A class cannot have both static and non-static methods. c. Yes. No other change is necessary. d. Yes, but it must be changed to public as well. 64. What will have to change if the instance variables month and day of the Date class are replaced by the single instance integer variable dayOfTheYear? a. The implementation of the methods will change, but the interface will not need to change. b. The implementation of getDay will not change, but the implementations of the other methods will not change and the interface will not change. c. The interface will need to change to remove setMonth, but no other parts of the interface will change. d. All of the interface will need to be changed when the instance variables change. 65. A new class is proposed to collect information about a group of DVDs. Which of the following is the best name for this class? a. DVDCollection b. DVD c. StoreDVDInformation d. Collection 66. A new class is proposed to collect information about a group of DVDs. Which of the following is the best structure for this class? a. Have separate classes for a single DVD and the entire DVD collection. b. Have one class to store information about DVDs and the collection named DVDsInformation c. Have one class to store information about the collection name and send information about the DVDs as simple data (integers, Strings, etc.) d. Have one class to store information about a single DVD and just use an ArrayList to store the collection. 67. A new class is proposed to collect information about a group of DVDs. A separate class containing information about a single DVD, named DVD, has already been created. Which of the following is the best design to store the data and size of this collection? a. Have an ArrayList of DVD and use its size as the size of the collection. b. Have an ArrayList of DVD and an integer representing the number of DVD objects in the collection. c. Have an array of DVD and use its size as the size of the collection. d. Have a single DVD variable representing the last DVD added and an integer representing the number of DVDs Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch8 in the collection. 68. A theater needs a TicketCounter to keep track of the number of tickets sold. There are two types of ticket: regular and discount. What instance data should be used for this class? a. private String[] ticketsSold; // Each entry is either "regular" or "discount" b. private int regularTicketsSold; int discountTicketsSold; c. private ArrayList<String> ticketsSold; // Each entry is either "regular" or "discount" d. private double ticketsSold; // Add 1 for regular and 0.5 for discount tickets

69. A theater needs a TicketCounter to keep track of the number of tickets sold. There are two types of ticket: regular and discount. Which technique would be the best approach to printing the number of tickets sold? a. Create a toString() method in the class that creates a representation with the number of discount and regular priced tickets sold. b. Create a print() method that will print out the number of discount and regular priced tickets sold. c. Make the instance variables public so programs can access the values and print them. d. Create a getValues(int regular, int discount) method that will return the number of discount and regular priced tickets sold. 70. Which of the following names would be considered to be qualified? a. studentOne.getGraduationYear() b. this.getGraduationYear() c. getGraduationYear() d. getGraduationYear().print() 71. In order to solve complex tasks, you should apply an important skill: a. organize classes based on performance and need. b. learn to direct others with clear, simple instructions. c. simplify the problem, and solve the simpler problem first. d. involve users in the process from the very beginning. 72. The best way to learn the strategy of how to break complex problems into simpler steps is to a. read more material about programming language. b. use pictures arranged in rows. c. use a debugger to assess problem complexity and efficiency. d. practice it. 73. Consider the following code snippet:

public class Vehicle { String vehicleType; . . . } Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch8 Which of the following statements about the variable vehicleType is true? a. It can be accessed by all classes in the same package as the Vehicle class. b. It can be accessed only by code within the Vehicle class. c. It can be accessed only by public methods declared within the Vehicle class. d. It can be accessed only by private methods declared within the Vehicle class. 74. To use a public variable or method outside of its class, you must ____ the name. a. bind b. encapsulate c. instantiate d. qualify 75. Under which of the following conditions must you qualify the name of a public class member? a. If it is to be used outside its class. b. If it is to be used inside its class. c. Public class members must always be qualified. d. Public class members never need to be qualified. 76. Which of the following is not a reason to place classes into a package? a. to avoid name clashes b. to organize related classes c. to show authorship of source code for classes d. to make it easier to include a set of frequently used but unrelated classes 77. Which action is not accomplished by using the import directive? a. Reference to a class within a package without having to fully qualify it. b. The ability to use all classes within a specific package. c. The organization of packages into groups. d. Ability to document in one place all class resources used in a program. 78. If you do not include a package statement at the top of your class source file, its classes will be placed in which package? a. java.lang b. java.util c. the default package, which has no name d. java.awt 79. Consider the Checker class below.

public class Checker { public static int count = 0; public int number = 0; public Checker() Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch8

{ count++; number = count; } public int getCount() { return count; } public int getNumber() { return number; } } What is output from the code fragment below?

Checker one = new Checker(); Checker two = new Checker(); System.out.println(one.getNumber() + " " + two.getNumber()); a. 1 2 b. 1 1 c. 2 1 d. 2 2 80. Consider the Checker class below.

public class Checker { public static int count = 0; public int number = 0; public Checker() { count++; number = count; } public int getCount() { return count; } public int getNumber() { return number; } } What is output from the code fragment below?

Checker one = new Checker(); Checker two = new Checker(); System.out.println(one.getCount() + " " + two.getCount()); a. 2 2 b. 1 1 c. 1 2 Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch8 d. 2 1 81. Consider the partial class below:

public class Thing { private int number; private char letter; { number = -10; letter = 'Z'; } ... } Which code is equivalent to the code above? a. public class Thing {

private int number = -10; private char letter = 'Z'; ... } b. public class Thing { private int number; private char letter; public Thing() { number = -10; letter = 'Z'; } ... } c. public class Thing { public Thing() { int number; char letter; number = -10; letter = 'Z'; } ... } d. public class Thing { public static void main(String[] args) { int number; char letter; number = -10; letter = 'Z'; } ... Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch8 }

82. Which class does not require an import statement at the beginning of the program that uses it? a. java.lang.Double b. java.awt.Color c. java.math.BigDecimal d. java.util.GregorianCalendar 83. Which statement will import the static methods of the Math class into a program so they do not need the Math. prefix before them in the code? a. import static java.lang.Math.*; b. import * from java.lang.Math; c. static import * from java.lang.Math; d. import java.lang.Math.*; 84. If the Math class has been imported into a program using the line import static java.lang.Math.*; how can the statement below be rewritten?

result = Math.tan(Math.toRadians(degrees)); a. result = tan(toRadians(degrees)); b. result = Math.tan(toRadians(degrees)); c. result = tan.toRadians(degrees); d. result = tan(Math.toRadians(degrees)); 85. How would you create the class PackageSample in a package named bigjava.Chapter8? a. package bigjava.chapter8; public class PackageSample {} b. public package bigjava.chapter8.PackageSample {} c. public class bigjava.chapter8.PackageSample {} d. public class PackageSample : package bigjava.chapter8 {} 86. Consider the partial JUnit test below, designed to test a class that keeps a count:

@Test public void twoIncrements() { Counter ctr = newCounter(10); ctr.increment(); ctr.increment(); // Put test line here } Which line will test that the resulting value is 12? a. Assert.assertEquals(12, ctr.getValue()); b. Assert.assertEquals(ctr.getValue()); c. System.out.println(12 == ctr.getValue()); Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch8 d. if (12 == ctr.getValue()) { System.out.println("Passed"); } else { System.out.println("Failed"); }

87. Which of the following is one of the most popular testing frameworks? a. JUnit b. JUnitTest c. JTester d. JQATester 88. Which annotation is used to mark test methods when using JUnit? a. @TestMethod b. @TestCode c. @Test d. @JUnitTest

Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch8 Answer Key 1. b 2. c 3. c 4. a 5. d 6. b 7. b 8. d 9. b 10. c 11. b 12. b 13. c 14. d 15. c 16. c 17. a 18. c 19. d 20. b 21. a 22. c 23. d 24. d 25. a Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch8 26. d 27. b 28. c 29. b 30. c 31. b 32. b 33. a 34. b 35. c 36. d 37. c 38. a 39. c 40. c 41. a 42. c 43. b 44. d 45. c 46. c 47. b 48. a 49. d 50. a 51. a Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch8 52. b 53. c 54. a 55. b 56. a 57. b 58. b 59. c 60. b 61. b 62. d 63. a 64. a 65. a 66. a 67. a 68. b 69. a 70. a 71. c 72. d 73. a 74. d 75. a 76. d Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch8 77. c 78. c 79. a 80. a 81. a 82. a 83. a 84. a 85. a 86. a 87. a 88. c

Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch9

Indicate the answer choice that best completes the statement or answers the question. 1. What is a class called that represents the most general entity in an inheritance hierarchy? a. Default class. b. Superclass. c. Subclass. d. Inheritance class. 2. Which class represents a more specific entity in an inheritance hierarchy? a. Default class b. Superclass c. Subclass. d. Inheritance class. 3. You are creating a class inheritance hierarchy about motor vehicles that will contain classes named Vehicle, Auto, and Motorcycle. Which of the following statements is correct? a. Vehicle should be the default class, while Auto and Motorcycle should be the subclasses. b. Vehicle should be the superclass, while Auto and Motorcycle should be the subclasses. c. Vehicle should be the subclass, while Auto and Motorcycle should be the superclasses. d. Vehicle should be the subclass, while Auto and Motorcycle should be the default classes. 4. Which of the following statements about inheritance is correct? a. You can always use a superclass object in place of a subclass object. b. You can always use a subclass object in place of a superclass object. c. A superclass inherits data and behavior from a subclass. d. A superclass inherits only behavior from a subclass. 5. Insert the missing code in the following code fragment. This fragment is intended to call the Vehicle class's method.

public class Vehicle { . . . public void setVehicleClass(double numberAxles) { . . . } } public class Motorcycle extends Vehicle { . . . public Motorcycle() { _______________; } } Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch9 a. Motorcyle.setVehicleClass(2.0); b. Vehicle.setVehicleClass(2.0); c. numberAxles = 2.0; d. setVehicleClass(2.0); 6. Insert the missing code in the following code fragment. This fragment is intended to call the Vessel class's method.

public class Vessel { . . . public void setVesselClass(double vesselLength) { . . . } } public class SpeedBoat extends Vessel { . . . public SpeedBoat() { _______________; } } a. SpeedBoat.vesselLength(26.0); b. Vessel.vesselLength(26.0); c. vesselLength = 26.0; d. setVesselClass(26.0); 7. Consider the following inheritance hierarchy diagram: a. Auto is a superclass of LandVehicle, and LandVehicle is a superclass of Vehicle. b. Auto is a superclass of LandVehicle, and LandVehicle is a subclass of Vehicle. c. Auto is a subclass of LandVehicle, and LandVehicle is a superclass of Vehicle. d. Auto is a subclass of LandVehicle, and LandVehicle is a subclass of Vehicle. 8. Consider the following inheritance hierarchy diagram: a. Auto class inherits from LandVehicle class, and LandVehicle class inherits from Vehicle class. b. Auto class inherits from LandVehicle class, and Vehicle class inherits from LandVehicle class. c. LandVehicle class inherits from Auto class, and LandVehicle class inherits from Vehicle class. d. LandVehicle class inherits from Auto class, and Vehicle class inherits from LandVehicle class. 9. Consider the hierarchy of classes shown below. a. public class ScriptedShow extends TelevisionShow {. . .} public class Comedy extends ScriptedShow {. . .} public class TelevisionShow extends ScriptedShow {. . .} b.

Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch9 public class ScriptedShow extends Comedy {. . .} public class Drama extends TelevisionShow {. . .} c. public class Comedy extends Drama {. . .} d. public class ScriptedShow extends RealityShow {. . .} public class RealityShow extends ScriptedShow {. . .}

10. Consider the hierarchy of classes shown below. a. Comedy b. RealityShow c. Object d. TelevisionShow 11. Consider the hierarchy of classes shown below. a. Object b. Comedy c. RealityShow d. This class has no superclass 12. All hamsters are rodents and all rodents are mammals. What hierarchy best captures this information? a. Hamster is a superclass of Rodent and Rodent is a superclass of Mammal b. Mammal is a superclass of Rodent and Rodent is a superclass of Hamster c. Mammal is a superclass of Rodent and Hamster d. Hamster is a superclass of Rodent and Mammal 13. All rodents are mammals and all canines are mammals. No canines are rodents and no rodents are canines. What hierarchy best captures this information? a. Mammal is a superclass of Rodent and Mammal b. Rodent is a superclass of Mammal and Canine is a superclass of Mammal c. Mammal is a superclass of Rodent and Rodent is a superclass of Canine d. Mammal is a superclass of Canine and Canine is a superclass of Rodent 14. Consider the classes shown below:

public class Parent { public int getValue() { return 24; } public void display() { System.out.print(getValue() + " "); } } public class Child extends Parent Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch9

{ public int getValue() { return -7; } } Using the classes above, what is the output of the following lines of code?

Parent kid = new Child(); Parent adult = new Parent(); kid.display(); adult.display(); a. -7 24 b. 24 24 c. -7 -7 d. 24 -7 15. Consider the following code snippet:

public class Vessel { . . . public void setVesselAttributes() { . . . } } public class Speedboat extends Vessel { . . . public void setvesselattributes() { . . . } } Which of the following statements is correct? a. The subclass is shadowing a superclass method. b. The subclass is overloading a superclass method. c. The subclass is overriding a superclass method. d. The subclass is defining its own distinct method. 16. Consider the classes shown below:

public class Parent Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch9

{ public void doSomething(){/* Implementation not shown */} } public class Child extends Parent { public void doAnotherThing(){/* Implementation not shown */} } Which lines in the following code will compile without error?

Child kid = new Child(); kid.doSomething(); // line 1 kid.doAnotherThing(); // line 2 a. Line 1 only b. Line 2 only c. Lines 1 and 2 d. Neither line will compile without error 17. Consider the classes shown below:

public class Parent { public void doSomething(){/* Implementation not shown */} } public class Child extends Parent { public void doAnotherThing(){/* Implementation not shown */} } Which lines in the following code will compile without error?

Parent kid = new Child(); kid.doSomething(); // line 1 kid.doAnotherThing(); // line 2 a. Line 1 only b. Line 2 only c. Lines 1 and 2 d. Neither line will compile without error 18. Consider the classes shown below:

public class Parent { private int value = 100; Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch9

public int getValue() { return value; } } public class Child extends Parent { private int value; public Child(int number) { value = number; } } What is the output of the following lines of code?

Child kid = new Child(-14); Parent adult = new Parent(); System.out.println(kid.getValue() + " " + adult.getValue()); a. 100 100 b. -14 100 c. -14 -14 d. 100 -14 19. Consider the classes shown below:

public class Parent { private int value = 100; public int getValue() { return value; } } public class Child extends Parent { private int value; public Child(int number) { value = number; } public int getValue() { return value; Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch9

} } What is the output of the following lines of code?

Child kid1 = new Child(-14); Child kid2 = new Child(21); System.out.println(kid1.getValue() + " " + kid2.getValue()); a. -14 21 b. 21 21 c. 21 100 d. 100 100 20. Consider the classes shown below:

public class Parent { private int value = 100; public int getValue() { return value; } } public class Child extends Parent { private int value; public Child(int number) { value = number; } } What is the output of the following lines of code?

Child kid = new Child(-14); Parent kid2 = new Child(21); System.out.println(kid.getValue() + " " + kid2.getValue()); a. 100 100 b. -14 21 c. 21 21 d. -14 100 21. Which keyword is used to create a subclass? a. inherits b. implements Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch9 c. interface d. extends 22. You are creating a Motorcycle class which is supposed to be a subclass of the Vehicle class. Which of the following class declaration statements will accomplish this? a. public class Motorcycle extends Vehicle b. public class Motorcycle implements Vehicle c. public class Motorcycle interfaces Vehicle d. public class Motorcycle inherits Vehicle 23. Which of the following is true regarding subclasses? a. A subclass inherits methods from its superclass but not instance variables. b. A subclass inherits instance variables from its superclass but not methods. c. A subclass inherits methods and instance variables from its superclass. d. A subclass does not inherit methods or instance variables from its superclass. 24. Which of the following is true regarding subclasses? a. A subclass that inherits methods from its superclass may not override the methods. b. A subclass that inherits instance variables from its superclass may not declare additional instance variables. c. A subclass may inherit methods or instance variables from its superclass but not both. d. A subclass may inherit methods and instance variables from its superclass, and may also implement its own methods and declare its own instance variables. 25. Which of the following is true regarding subclasses? a. A subclass has access to private instance variables of its superclass. b. A subclass does not have access to public instance variables of its superclass. c. A subclass must specify the implicit parameter to use methods inherited from its superclass. d. A subclass has no access to private instance variables of its superclass. 26. Which of the following indicates that a class named ClassA class is a superclass of the ClassB class? a. public class ClassB extends ClassA b. public class ClassB implements ClassA c. public class ClassA extends ClassB d. public class ClassA implements ClassB 27. What must a subclass do to modify a private superclass instance variable? a. The subclass must simply use the name of the superclass instance variable. b. The subclass must declare its own instance variable with the same name as the superclass instance variable. c. The subclass must use a public method of the superclass (if it exists) to update the superclass's private instance variable. d. The subclass must have its own public method to update the superclass's private instance variable. 28. Consider the following code snippet:

public class Vehicle Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch9

{ private String manufacturer; . . . public void setVehicleClass(double numberAxles) { . . . } } If a Motorcycle class is created as a subclass of the Vehicle class, which of the following statements is correct? a. A Motorcycle object inherits and can directly use both the instance variable manufacturer and the method setVehicleClass. b. A Motorcycle object inherits and can directly use the instance variable manufacturer but not the method setVehicleClass. c. A Motorcycle object inherits but cannot directly use either the instance variable manufacturer or the method setVehicleClass. d. A Motorcycle object inherits and can directly use the method setVehicleClass but cannot directly use the instance variable manufacturer. 29. Consider the following class hierarchy:

public class Vehicle { private String type; public Vehicle(String type) { this.type = type; } public String displayInfo() { return type; } } public class LandVehicle extends Vehicle { public LandVehicle(String type) { super(type); } } public class Auto extends LandVehicle { public Auto(String type) { super(type); Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch9

} } You have written a program to use these classes, as shown in the following code snippet:

public class VehicleTester { public static void main(String[] args) { Auto myAuto = new Auto("sedan"); System.out.println("MyAuto type = " + ______); } } Complete the code in this program snippet to correctly display the auto's type. a. myAuto.displayInfo() b. myAuto.super.displayInfo() c. myAuto.super.super.displayInfo() d. This cannot be done unless the Auto class overrides the displayInfo method. 30. Consider the following class hierarchy:

public class Vehicle { private String type; public Vehicle(String type) { this.type = type; } public String displayInfo() { return type; } } public class LandVehicle extends Vehicle { public LandVehicle(String type) { super(type); } } public class Auto extends LandVehicle { public Auto(String type) { _________; Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch9

} } Complete the code in the Auto class constructor to store the type data. a. super(type); b. super(super(type)); c. super.super(type); d. This cannot be done unless Auto declares an instance variable named type. 31. Consider the following class hierarchy:

public class Vehicle { private String type; public Vehicle(String type) { this.type = type; } public String displayInfo() { return type; } } public class LandVehicle extends Vehicle { public LandVehicle(String type) { . . . } } public class Auto extends LandVehicle { public Auto(String type) { . . . } public String displayAutoType() { return _____; } } Complete the code in the Auto class method named displayAutoType to return the type data. a. super(type); b. super.type; Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch9 c. super.super.type; d. super.displayInfo() 32. Consider the following code snippet:

public class Vehicle { . . . public void setVehicleAttributes() { . . . } } public class Auto extends Vehicle { . . . public void setVehicleAttributes() { . . . } } Which of the following statements is correct? a. The subclass is shadowing a superclass method. b. The subclass is overloading a superclass method. c. The subclass is overriding a superclass method. d. This code will not compile. 33. Consider the classes shown below:

public class Parent { public int getValue() { return 24; } public void display() { System.out.print(getValue() + " "); } } public class Child extends Parent { public int getValue() { return -7; Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch9

} } Using the classes above, what is the output of the following lines of code?

Child kid = new Child(); Parent adult = new Parent(); kid.display(); adult.display(); a. 24 24 b. -7 -7 c. -7 24 d. 24 -7 34. Consider the following class hierarchy:

public class Vehicle { private String type; public Vehicle(String type) { this.type = type; System.out.print("Vehicle "); } public String displayInfo() { return type; } } public class LandVehicle extends Vehicle { public LandVehicle(String type) { super(type); System.out.print("Land "); } } public class Auto extends LandVehicle { public Auto(String type) { super(type); System.out.print("Auto "); } Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch9

} When an object of type Auto is constructed, what will be printed by the constructors from this inheritance hierarchy? a. Vehicle Land Auto b. Auto Land Vehicle c. Land Auto Vehicle d. Auto 35. Consider the following class hierarchy:

public class Vehicle { private String type; public Vehicle(String type) { this.type = type; System.out.print("Vehicle "); } public String displayInfo() { return type; } } public class LandVehicle extends Vehicle { public LandVehicle(String type) { super(type); System.out.print("Land "); } } public class Auto extends LandVehicle { public Auto(String type) { super(type); System.out.print("Auto "); } } When an object of type Vehicle is constructed, what will be printed by the constructors from this inheritance hierarchy? a. Vehicle Land Auto b. Auto Land Vehicle c. Vehicle d. Auto Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch9 36. Which of the following statements about superclasses and subclasses is true? a. A superclass is larger than its subclass. b. A superclass inherits from a subclass. c. A superclass extends a subclass. d. A subclass extends a superclass. 37. Suppose the class Message is partially defined as shown below:

public class Message { private String value; public Message(String initial) { value = initial; } public String getMessage() { return value; } } A subclass of Message, ExcitedMessage, is defined that will behave like Message, except that it will add two exclamation points to the end of the message. Sample code that uses ExcitedMessage is shown below.

ExcitedMessage greeting = new ExcitedMessage("Hello"); System.out.print(greeting.getMessage());// will print "Hello!!" Which ExcitedMessage constructor will give this behavior? a. public ExcitedMessage(String line) {

super(line + "!!"); } b. public ExcitedMessage(String line) { value = line + "!!"; } c. public ExcitedMessage(String line) { line = line + "!!"; super(line); } d. public ExcitedMessage(String line) { new Message(line + "!!"); }

38. Suppose the class Value is partially defined below Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch9

public class Value { private int number; public int getValue() { return number; } } A subclass of Value, LargerValue, is defined with a getValue method that returns twice the value of the parent. Which line is the body of LargerValue's getValue method? a. return getValue() * 2; b. return super.getValue() * 2; c. return number * 2; d. return super.number * 2; 39. Consider the following code snippet:

public void deposit(double amount) { transactionCount++; super.deposit(amount); } Which of the following statements is true? a. This method will call itself. b. This method calls a public method in its subclass. c. This method calls a private method in its superclass d. This method calls a public method in its superclass. 40. Which reserved word must be used to call a method of a superclass? a. this b. my c. parent d. super 41. If a subclass defines the same method name and the same parameter types for a method that appears in its superclass, which statement is true? a. the subclass method overloads the superclass method. b. the subclass method overrides the superclass method. c. the subclass has implemented the method on behalf of the superclass. d. a compiler error will occur. 42. Consider the following code snippet: Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch9

public class Vehicle { . . . public void setVehicleClass(double numberAxles) { . . . } } public class Motorcycle extends Vehicle { . . . public void setVehicleClass(double numberAxles) { . . . } } Which of the following statements is correct? a. The Motorcycle class's setVehicleClass method overrides the Vehicle class's setVehicleClass method. b. The Vehicle class's setVehicleClass method overrides the Motorcycle class's setVehicleClass method. c. The Motorcycle class's setVehicleClass method overloads the Vehicle class's setVehicleClass method. d. The Vehicle class's setVehicleClass method overloads the Motorcycle class's setVehicleClass method. 43. Consider the following code snippet:

public class Vehicle { . . . public void setVehicleClass(double numberAxles) { . . . } } public class Motorcycle extends Vehicle { . . . public void setModelName(String model) { . . . } public void setVehicleClass(double numberAxles) Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch9

{ . . . } } Which of the following statements is NOT correct? a. An object of type Motorcycle can call the setVehicleClass method of the Vehicle class on itself. b. An object of type Vehicle can call the setModelName method on itself. c. The Motorcycle class's SetVehicleClass method overrides the Vehicle class's setVehicleClass method. d. An object of type Motorcycle can call the setVehicleClass method of the Motorcycle class on itself. 44. Consider the following code snippet:

public class Employee { . . . public void setDepartment(String deptName) { . . . } } public class Programmer extends Employee { . . . public void setProjectName(String projName) { . . . } public void setDepartment(String deptName) { . . . } } Which of the following statements is correct? a. An object of type Programmer can call the setDepartment method of the Employee class on itself. b. An object of type Employee can call the setProjectName method on itself. c. The Employee class's setDepartment method overrides the Programmer class's setDepartment method. d. An object of type Employee can call the setDepartment method of the Programmer class on itself. 45. Consider the following code snippet:

public class Vehicle Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch9

{ . . . public void setVehicleClass(double numberAxles) { . . . } } public class Auto extends Vehicle { . . . public void setVehicleClass(int numberAxles) { . . . } } Which of the following statements is correct? a. The Auto class overrides the setVehicleClass method. b. The Vehicle class overrides the setVehicleClass method. c. The Auto class overloads the setVehicleClass method. d. The Vehicle class overloads the setVehicleClass method. 46. What is the term used for a subclass that defines a method with the same name as a method in its superclass, but with different parameter types? a. implementing b. inheriting c. overriding d. overloading 47. Which statement is true about a subclass that uses the same method name but different parameter types for a method that appears in its superclass? a. the subclass method has overloaded its superclass's method. b. the subclass method has overridden its superclass's method. c. the subclass has implemented its superclass's method. d. a compiler error will occur. 48. Consider the following code snippet that appears in a subclass:

public void deposit(double amount) { transactionCount ++; deposit(amount); } Which of the following statements is true? a. This method will call itself. Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch9 b. This method calls a public method in its subclass. c. This method calls a private method in its superclass d. This method calls a public method in its superclass. 49. Consider the following code snippet:

public class Auto extends Vehicle { . . . public Auto(int numberAxles) { super(numberAxles); } } What does this code do? a. It invokes the constructor of the Vehicle class from within the constructor of the Auto class. b. It invokes the constructor of the Auto class from within the constructor of the Vehicle class. c. It invokes a private method of the Vehicle class from within a method of the Auto class. d. This code will not compile. 50. Consider the following code snippet:

public class Motorcycle extends Vehicle { . . . public Motorcycle(int numberAxles) { super(numberAxles); //line #1 } } If the line marked "//line #1" was missing, which of these statements would be correct? a. The Vehicle class constructor would invoke the constructor of the Motorcycle class with no parameters. b. The Motorcycle class constructor would invoke the constructor of the Vehicle class with a parameter value of 0. c. The Motorcycle class constructor would invoke the constructor of the Vehicle class with no parameters. d. This code would not compile. 51. Consider the following code snippet:

public class Motorcycle extends Vehicle { . . . public Motorcycle(int numberAxles) { Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch9

super.numberAxles = numberAxles; } } What does this code do? a. It invokes the constructor of the Vehicle class from within the constructor of the Motorcycle class. b. It invokes the constructor of the Motorcycle class from within the constructor of the Vehicle class. c. It invokes a private method of the Vehicle class from within a method of the Motorcycle class. d. It attempts to access directly an instance variable of the Vehicle superclass rather than using a constructor or an accessor. 52. Consider the following code snippet:

public class Motorcycle extends Vehicle { private String model; . . . public Motorcycle(int numberAxles, String modelName) { super(numberAxles); model = modelName; } } What does this code do? a. It invokes the constructor of the Vehicle class from within the constructor of the Motorcycle class. b. It invokes the constructor of the Motorcycle class from within the constructor of the Vehicle class. c. It invokes a private method of the Vehicle class from within a method of the Motorcycle class. d. This code will not compile. 53. Consider the classes shown below:

public class Parent { public void doSomething() // method 1 { /* Implementation not shown */ } } public class Child extends Parent { public void doSomething(int n) // method 2 { /* Implementation not shown */ } public void doSomething() // method 3 { /* Implementation not shown */ } } Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch9 If the variable kid is defined below, which version of the doSomething method can be called on the variable kid?

Child kid = new Child(); a. Methods 1 and 2 only b. Method 2 only c. Methods 2 and 3 only d. Methods 1, 2, and 3 54. Consider the classes shown below:

public class Parent { public void doSomething() // method 1 { /* Implementation not shown */ } } public class Child extends Parent { public void doSomething(int n) // method 2 { /* Implementation not shown */ } public void doSomething() // method 3 { /* Implementation not shown */ } } If the variable kid is defined below, which version of the doSomething method can be called on the variable kid?

Parent kid = new Child(); a. Method 1 only b. Methods 2 and 3 only c. Methods 1 and 2 only d. Methods 1, 2, and 3 55. When the reserved word super is followed by a parenthesis, what does it indicate? a. A call to a superclass method. b. A call to a superclass constructor. c. A call to a subclass method. d. A call to a subclass constructor. 56. When the reserved word super is followed by a period and a method name, what does it indicate? a. A call to a superclass method. b. A call to a superclass constructor. c. A call to a subclass method. d. A call to a subclass constructor. Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch9 57. Which of the following statements is true about using the reserved word super to call a superclass constructor? a. The call must use the keyword super followed by a period and a method name. b. The call must use the keyword super with no arguments. c. The call must be the last line of the subclass constructor. d. The call must be the first line of the subclass constructor. 58. In Java, two methods can have the same name provided that what is true? a. They cannot be defined in the same class. b. They must differ in their parameter types. c. One must be private and the other public. d. They must be related to each other through inheritance. 59. In Java, if you define two methods that have the same but different parameter types, the compiler will not complain. Why not? a. The compiler will use only the most recent method definition. b. The compiler considers the two methods to be completely unrelated. c. The compiler cannot detect the difference between the two methods. d. The compiler will silently link the two methods through inheritance. 60. In Java, if you forget to call a superclass constructor explicitly in the constructor of a subclass, what will happen? a. The code will not compile. b. The default constructor (the one with no arguments) of the superclass will be invoked automatically. c. The subclass will be constructed without invoking a constructor for the superclass. d. The subclass object will be given a value of null. 61. What must a subclass method do in order to override a superclass method? a. Must use a different method name. b. Must use the same method name and the same parameter types. c. Must use a different method name and the same parameter types. d. Must use a different method name and different parameter types. 62. Consider the following code snippet:

public class Motorcycle extends Vehicle { private String model; . . . public Motorcycle(int numberAxles, String modelName) { model = modelName; super(numberAxles); } } What does this code do? Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch9 a. It invokes the constructor of the Vehicle class from within the constructor of the Motorcycle class. b. It invokes the constructor of the Motorcycle class from within the constructor of the Vehicle class. c. It invokes a private method of the Vehicle class from within a method of the Motorcycle class. d. This code will not compile. 63. Suppose the abstract class Message is defined below

public abstract class Message { private String value; public Message(String initial) { value = initial; } public String getMessage() { return value; } public abstract String translate(); } A concrete subclass of Message, called FrenchMessage, is defined. Which methods must FrenchMessage define? a. translate() only b. getMessage() only c. The FrenchMessage constructor and translate() only d. The FrenchMessage constructor, getMessage(), and translate() 64. Consider the following class hierarchy:

public class Vehicle { private String type; public Vehicle(String type) { this.type = type; } public String getType() { return type; } } public class LandVehicle extends Vehicle { public LandVehicle(String type) Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch9

{ . . . } } public class Auto extends LandVehicle { public Auto(String type) { . . . } } Which of the following code fragments is NOT valid in Java? a. Vehicle myAuto = new Auto("sedan"); b. LandVehicle myAuto = new Auto("sedan"); c. Auto myAuto = new Auto("sedan"); d. LandVehicle myAuto = new Vehicle("sedan"); 65. Consider the following code snippet:

Vehicle aVehicle = new Auto(); aVehicle.moveForward(200); If the Auto class inherits from the Vehicle class, and both classes have an implementation of the moveForward method with the same set of parameters and the same return type, which statement is correct? a. The moveForward method of the Auto class will be executed. b. The moveForward method of the Vehicle class will be executed. c. You must specify in the code which class's moveForward method is to be used. d. It is not possible to determine which class's method is called. 66. Consider the following code snippet:

Employee anEmployee = new Programmer(); anEmployee.increaseSalary(2500); If the Programmer class inherits from the Employee class, and only the Employee class has an implementation of the increaseSalary method, which statement is correct? a. The increaseSalary method call will cause a run-time error. b. The increaseSalary method of the Employee class will be executed. c. The Programmer class is required to provide an implementation of the increaseSalary method. d. Programmer objects must be cast to Employee objects before the method call can me made. 67. Consider the following code snippet:

Vehicle aVehicle = new Auto(); Powered by Cognero

Page 25


Name:

Class:

Date:

testbank-bj-7-ch9

aVehicle.moveForward(200); Assume that the Auto class inherits from the Vehicle class, and both classes have an implementation of the moveForward method with the same set of parameters and the same return type. The process for determining which class's moveForward method to execute is called ____. a. inheritance disambiguation. b. inheritance hierarchy. c. dynamic inheritance. d. dynamic method lookup. 68. Consider the following code snippet:

Vehicle aVehicle = new Auto(); aVehicle.moveForward(200); Assume that the Auto class inherits from the Vehicle class, and both classes have an implementation of the moveForward method with the same set of parameters and the same return type. What determines which class's moveForward method is to be executed? a. the actual object type. b. the variable's type. c. the hierarchy of the classes. d. it is not possible to determine which method is executed. 69. Which of the following statements about abstract methods is true? a. An abstract method has a name, parameters, and a return type, but no code in the body of the method. b. An abstract method has parameters, a return type, and code in its body, but has no defined name. c. An abstract method has a name, a return type, and code in its body, but has no parameters. d. An abstract method has only a name and a return type, but no parameters or code in its body. 70. Which of the following statements about classes is true? a. You can create an object from a concrete class, but not from an abstract class. b. You can create an object from an abstract class, but not from a concrete class. c. You cannot have an object reference whose type is an abstract class. d. You cannot create subclasses from abstract classes. 71. If a class has an abstract method, which of the following statements is NOT true? a. You can construct an object from this class. b. You can have an object reference whose type is this class. c. You can inherit from this class. d. All non-abstract subclasses of this class must implement this method. 72. Consider the following code snippet:

public abstract class Machine { public abstract void setRPMs(); Powered by Cognero

Page 26


Name:

Class:

Date:

testbank-bj-7-ch9

. . . } You wish to create a concrete subclass named PolisherMachine. Which of the following is the correct way to declare this subclass? a. public class PolisherMachine implements Machine {

public void setRPMs() { . . . } } b. public class PolisherMachine extends Machine { void setRPMs() { . . .} } c. public class PolisherMachine implements Machine { void setRPMs() { . . .} } d. public class PolisherMachine extends Machine { public void setRPMs() { . . . } }

73. The term for a class from which you cannot create objects is a. Abstract class. b. Concrete class. c. Non-inheritable class. d. Superclass. 74. Which of the following statements about classes is true? a. You can create an object from a class declared with the keyword final. b. You can override methods in a class declared with the keyword final. c. You can extend a class declared with the keyword final. d. You can create subclasses from a class declared with the keyword final. 75. What reserved word in a class definition ensures that subclasses cannot be created from the class? a. abstract b. anonymous c. final d. static 76. What reserved word in a method definition ensures that subclasses cannot override the method? a. abstract b. anonymous c. final d. static 77. Which of the following is true regarding inheritance? a. When creating a subclass, all methods of the superclass must be overridden. Powered by Cognero

Page 27


Name:

Class:

Date:

testbank-bj-7-ch9 b. When creating a subclass, no methods of a superclass can be overridden. c. A superclass can force a programmer to override a method in any subclass created from it. d. A superclass cannot prevent a programmer from overriding a method in any subclass created from it. 78. When declared as protected, which statement is true about the access to data in an object? a. The data is accessible only by that class's methods and by all of its subclasses b. The data is accessible only by that class's methods, by all of its subclasses, and by methods in classes within the same package. c. The data is accessible only by that class's methods. d. The data is accessible by any class. 79. Consider the following code snippet:

public class Vehicle { protected int numberAxles; . . . } Which statement is true about the accessibility of data in the numberAxles variable? a. It is only accessible by the Vehicle class's methods and by all of its subclasses b. It is only accessible by the Vehicle class's methods, by all of its subclasses, and by methods in classes within the same package. c. It is only accessible by the Vehicle class's methods. d. It is accessible by any class. 80. To ensure that an instance variable can only be accessed by the class that declared it, how should the variable be declared? a. public b. private c. protected d. final 81. With a few exceptions, what access should instance variables of classes always have? a. final b. private c. public d. protected 82. In designing an inheritance hierarchy it is helpful first to list classes that are part of the hierarchy and then organize those classes via an inheritance diagram. Once this has been done, what is the next step in the design? a. Determine common responsibilities among the classes. b. Decide which methods should be overridden. c. Declare the public interface of each class. d. Define and implement constructors and methods. Powered by Cognero

Page 28


Name:

Class:

Date:

testbank-bj-7-ch9 83. When identifying the proper instance variables to use in the design of an inheritance hierarchy, how do you decide where in the hierarchy a variable should be placed? a. Instance variables should only be declared in the superclass and then accessed using the super keyword. b. Instance variables should only be declared in subclasses. c. Instance variables that are common to all classes should be placed at the base of the hierarchy. d. Instance variables that are relevant to only one class should be placed at the base of the hierarchy. 84. Consider the following class hierarchy:

public final class Shape { private String mycolor; public Shape(String mycolor) { this.type = mycolor; } public String getColor() { return mycolor; } } public class Triangle extends Shape { public Triangle(String mycolor) { super(mycolor); } } } What is wrong with this class hierarchy definition? a. Nothing is wrong with the code. b. There should be more subclasses of the Shape class than just Triangle. c. There cannot be any subclasses of the Shape class. d. It is not possible to use super in the Triangle constructor. 85. What does the getClass method do? a. Returns an object that describes a class and its properties. b. Returns a string that contains the instance variables of a class. c. Returns an object that describes all subclasses of a given object. d. Returns an object that describes all superclasses of a given object. 86. When you implement equals in a subclass, you should first call equals in the superclass. Why? a. To ensure that the superclass constructor has already executed. b. To check whether the objects being compared are instances of the same class. Powered by Cognero

Page 29


Name:

Class:

Date:

testbank-bj-7-ch9 c. To prevent a bad cast and the possibility of an exception. d. To check whether the superclass instance variables match. 87. Consider the Counter class below.

public class Counter { public int count = 0; public int getCount() { return count; } public void increment() { count++; } } Using the class above and the variable declared below, what is the value of num.toString()?

Counter num = new Counter(); a. a string with count's value b. a string with num's type and hashcode c. a string with count's type and hashcode d. nothing since toString is not defined for Counter 88. Consider the Counter class below.

public class Counter { public int count = 0; public int getCount() { return count; } public void increment() { count++; } } Using the class above and the variables declared below, what is the value of num1.equals(num2)? Powered by Cognero

Page 30


Name:

Class:

Date:

testbank-bj-7-ch9

Counter num1 = new Counter(); Counter num2 = new Counter(); a. true b. false c. nothing since equals is not defined for Counter d. a syntax error 89. Consider the Counter class below.

public class Counter { public int count = 0; public int getCount() { return count; } public void increment() { count++; } } Using the class above and the variables declared below, what is the value of num1.equals(num2)?

Counter num1 = new Counter(); Counter num2 = num1; a. true b. false c. nothing since equals is not defined for Counter d. a syntax error 90. Consider the following code snippet:

Vehicle aVehicle = new Auto(4,"gasoline"); String s = aVehicle.toString(); Assume that the Auto class inherits from the Vehicle class, and neither class has an implementation of the toString() method. Which of the following statements is correct? a. The toString() method of the Object class will be used when this code is executed. b. The toString() method of the String class will be used when this code is executed. c. This code will not compile because there is no toString() method in the Vehicle class. d. This code will not compile because there is no toString() method in the Auto class. Powered by Cognero

Page 31


Name:

Class:

Date:

testbank-bj-7-ch9 91. Consider the following code snippet:

Employee anEmployee = new Programmer(); String emp = anEmployee.toString(); Assume that the Programmer class inherits from the Employee class, and only the Employee class has an implementation of the toString() method. Which of the following statements is correct? a. The toString() method of the Object class will be used when this code is executed. b. The toString() method of the Employee class will be used when this code is executed. c. The toString() method of the String class will be used when this code is executed. d. This code will not compile because there is no toString() method in the Programmer class. 92. Consider the following code snippet:

int numAxles = 4; String s = "Number of axles is " + numAxles; Which of the following statements is correct? a. The toString() method of the Object class is being used to set the value of s. b. The toString() method of the Integer class is being used to set the value of s. c. No toString() method is being used to set the value of s. d. This code will not compile. 93. Consider the following code snippet:

double salary = 45000.00; String sal = "Current salary is " + salary; Which of the following statements is correct? a. The toString() method of the Object class is being used to set the value of salary. b. The toString() method of the Double class is being used to set the value of salary. c. No toString() method is being used to set the value of salary. d. This code will not compile. 94. Consider the following code snippet:

Employee programmer = new Employee(10254, "exempt"); String s = programmer.toString(); Assume that the Employee class has not implemented its own toString() method. What value will s contain when this code is executed? a. s will contain the values of the instance variables in programmer. b. s will contain only the class name of the programmer object. c. s will contain the class name of the programmer object followed by a hash code. d. This code will not compile. Powered by Cognero

Page 32


Name:

Class:

Date:

testbank-bj-7-ch9 95. Which of the following statements about comparing objects is correct? a. The purpose of the equals method is to compare whether two references are to the same object. b. The purpose of the equals method is to compare whether two objects have the same contents. c. The == operator is used to compare whether two objects have the same contents. d. For objects other than Object, the equals method and the == operator always perform the same actions. 96. Consider the following code snippet, which is meant to override the equals() method of the Object class:

public class Coin { . . . public boolean equals(Coin otherCoin) { . . . } . . . } What is wrong with this code? a. A class cannot override the equals() method of the Object class. b. The equals() method must be declared as private. c. A class cannot change the parameters of a superclass method when overriding it. d. There is nothing wrong with this code. 97. Consider the following code snippet:

public class Coin { private String name; . . . public boolean equals(Object otherCoin) { return name.equals(otherCoin.name); } . . . } What is wrong with this code? a. The return statement should use the == operator instead of the equals method. b. The parameter in the equals method should be declared as Coin otherCoin. c. otherCoin must be cast as a Coin object before using the equals method. d. There is nothing wrong with this code. 98. Consider the following code snippet:

public class Score { Powered by Cognero

Page 33


Name:

Class:

Date:

testbank-bj-7-ch9

private String name; . . . public boolean equals(Object otherScore) { Score other = (Score) otherscore; return name.equals(other.name); } . . . } What is wrong with this code? a. The return statement should use the == operator instead of the equals method. b. The parameter in the equals method should be declared as Score otherScore. c. It is an error to cast otherScore as a Score object before using the equals method. d. There is nothing wrong with this code. 99. Consider the following code snippet:

if(anObject instanceof Auto) { Auto anAuto = (Auto)anObject; . . . } What does this code do? a. This code tests whether anObject was created from a superclass of Auto. b. This code creates a subclass type object from a superclass type object. c. This class safely converts an object of any type to an object of type Auto. d. This code safely converts an object of type Auto or a subclass of Auto to an object of type Auto. 100. To test whether an object belongs to a particular type, use a. the this reserved word. b. the subclassOf reserved word. c. the instanceof operator. d. the equals method. 101. Why is the following code, which assumes ChoiceQuestion is a subclass of Question, considered poor strategy?

if (q instanceof ChoiceQuestion) { // Do the task the ChoiceQuestion way } else if (q instanceof Question) { // Do the task the Question way Powered by Cognero

Page 34


Name:

Class:

Date:

testbank-bj-7-ch9

} a. Question should be the subclass, not the other way around. b. instanceof is not an operator but rather a method. c. instanceof should not be used for type tests that can be solved by using polymorphism. d. the instanceof reserved word should only be used in a class constructor.

Powered by Cognero

Page 35


Name:

Class:

Date:

testbank-bj-7-ch9 Answer Key 1. b 2. c 3. b 4. b 5. d 6. d 7. d 8. a 9. a 10. d 11. a 12. b 13. a 14. a 15. d 16. c 17. a 18. a 19. a 20. a 21. d 22. a 23. c 24. d 25. d Powered by Cognero

Page 36


Name:

Class:

Date:

testbank-bj-7-ch9 26. a 27. c 28. d 29. a 30. a 31. d 32. c 33. c 34. a 35. c 36. d 37. a 38. b 39. d 40. d 41. b 42. a 43. b 44. a 45. c 46. d 47. a 48. a 49. a 50. c 51. d Powered by Cognero

Page 37


Name:

Class:

Date:

testbank-bj-7-ch9 52. a 53. c 54. a 55. b 56. a 57. d 58. b 59. b 60. b 61. b 62. d 63. a 64. d 65. a 66. b 67. d 68. a 69. a 70. a 71. a 72. d 73. a 74. a 75. c 76. c Powered by Cognero

Page 38


Name:

Class:

Date:

testbank-bj-7-ch9 77. c 78. b 79. b 80. b 81. b 82. a 83. c 84. c 85. a 86. d 87. b 88. b 89. a 90. a 91. b 92. c 93. c 94. c 95. b 96. c 97. c 98. d 99. d 100. c 101. c

Powered by Cognero

Page 39


Name:

Class:

Date:

testbank-bj-7-ch10

Indicate the answer choice that best completes the statement or answers the question. 1. Which of the following statements about a Java interface is NOT true? a. A Java interface must contain more than one method. b. A Java interface defines a set of methods that are required. c. A Java interface specifies behavior that a class will implement. d. All methods in a Java interface must be public. 2. A method that has no implementation is called a/an ____ method. a. abstract b. overloaded c. interface d. implementation 3. Which statement about methods in an interface is true? a. All methods in an interface must be explicitly declared as private or public. b. All methods in an interface are automatically public. c. All methods in an interface are automatically private. d. All methods in an interface are automatically static. 4. Which of the following statements about abstract methods is true? a. An abstract method has only a name and a return type, but no parameters or code in its body. b. An abstract method has a name, a return type, and code in its body, but has no parameters. c. An abstract method has parameters, a return type, and code in its body, but has no defined name. d. An abstract method has a name, parameters, and a return type, but no code in the body of the method. 5. Which of the following statements about an interface is true? a. An interface has both public and private methods. b. An interface has methods and instance variables. c. An interface has methods but no instance variables. d. An interface has neither methods nor instance variables. 6. To use an interface, a class header should include which of the following? a. The keyword extends and the name of the interface b. The keyword extends and the name of an abstract method in the interface c. The keyword implements and the name of an abstract method in the interface d. The keyword implements and the name of the interface 7. Consider the definition of the Measurable interface and the code snippet defining the Inventory class:

public interface Measurable { double getMeasure(); } Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch10

public class Inventory implements Measurable { . . . public double getMeasure() { return onHandCount; } } Why is it necessary to declare getMeasure as public in the Inventory class? a. It is necessary only to allow other classes to use this method. b. It is not necessary to declare this method as public. c. All methods in an interface are private by default. d. All methods in a class are not public by default. 8. Which of the following statements about interfaces is NOT true? a. Interfaces can reduce the coupling between classes. b. A class can implement only one interface type. c. An interface cannot have instance variables. d. Interfaces can make code more reusable. 9. A class that implements an interface must provide an implementation for all ____ methods. a. private b. final c. static d. abstract 10. Suppose you are writing an interface called Resizable, which includes one void method called resize that accepts no parameters.

public interface Resizable { _________________________ } Which of the following can be used to complete the interface declaration correctly? a. protected void resize(); b. void resize(); c. private void resize(); d. public void resize() { System.out.println("resizing ..."); }

11. Consider the following declarations:

public interface Encryptable { void encrypt(String key); Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch10

} public class SecretText implements Encryptable { private String text; _____________________________ { // code to encrypt the text using encryption key goes here } } Which of the following method headers should be used to complete the SecretText class? a. public void encrypt() b. void encrypt(String aKey) c. public void encrypt(String aKey) d. public String encrypt(String aKey) 12. Consider the definition of the Measurable interface and the code snippet defining the Inventory class:

public interface Measurable { double getMeasure(); } public class Inventory implements Measurable { . . . double getMeasure() { return onHandCount; } } What is wrong with this code? a. The getMeasure() method must be declared as private. b. The getMeasure() method must be declared as public. c. The getMeasure() method must include the implements keyword. d. The getMeasure() method must not have any code within it. 13. Consider the following code snippet:

public interface Sizable { int LARGE_CHANGE = 100; int SMALL_CHANGE = 20; void changeSize(); Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch10

} Which of the following statements is true? a. LARGE_CHANGE and SMALL_CHANGE are instance variables. b. LARGE_CHANGE and SMALL_CHANGE are automatically public static final. c. LARGE_CHANGE and SMALL_CHANGE must be defined with the keywords private static final. d. LARGE_CHANGE and SMALL_CHANGE must be defined with the keywords public static final. 14. Consider the definition of the Measurable interface and the code snippet defining the Inventory class:

public interface Measurable { double getMeasure(); } public class Inventory implements Measurable { private int onHandCount; . . . double getMeasure() { return onHandCount; } } The compiler complains that the getMeasure method has a weaker access level than the Measurable interface. Why? a. The getMeasure method was declared as private in the Measurable interface. b. The variable onHandCount was not declared with public access. c. All of the methods in a class have a default access level of package access, while the methods of an interface have a default access level of private. d. All of the methods in a class have a default access level of package access, while the methods of an interface have a default access level of public. 15. What type of edge does UML use to denote interface implementation? a. A dotted arrow from the interface to the class terminated with a triangular tip. b. A dotted arrow from the class to the interface terminated with an open arrow tip. c. A dotted arrow from the interface to the class terminated with an open arrow tip. d. A dotted arrow from the class to the interface terminated with a triangular tip. 16. In UML, a dotted arrow with a triangular tip denotes ____________________. a. interface implementation b. dependency c. inheritance d. aggregation Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch10 17. 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. 18. 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 19. Which of the following statements about interfaces is NOT true? a. An interface can supply a default implementation. b. Interfaces can make code more reusable. c. An interface can describe the state that should be maintained. d. An interface describes the behavior that an implementation should supply. 20. Consider the following code snippet:

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 Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch10 d. public 21. Assume that the Measurable interface is defined with a static sum method that computes the sum of the Measurable objects passed in as an array, and that BankAccount implements the Measurable interface. Also assume that there is a variable branchAccounts that is an object reference to a populated array of BankAccount objects for a bank branch. Which of the following represents a correct invocation of the sum method to find the total balance of all accounts at the branch? a. Arrays.sum(branchAccounts) b. BankAccount.sum(branchAccounts) c. Measurable.sum(branchAccounts) d. branchAccounts.sum() 22. Which of the following is true about a default method in an interface declaration? a. A default method is a static method that does not have an implicit parameter. b. A default method does not provide an implementation. c. A class that implements the interface cannot override the default behavior. d. A class that implements the interface can inherit the default behavior. 23. Consider the following code snippet:

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 24. Assume a class extends another class and implements an interface, both of which define the same method. Which statement is true about this conflict of inherited methods? a. The compiler will generate an error due to the conflict. b. The code compiles but generates an exception at run time due to the conflict. c. The subclass inherits the superclass method and ignores the default method from the interface. d. There is no conflict because interfaces cannot provide method implementation. 25. Assume a class implements two interfaces, both of which define a default method with the same signature. Which statement is true about this conflict of inherited methods? a. The code compiles but generates an exception at run time due to the conflict. b. The code compiles and the implementation is chosen at run time. Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch10 c. The class must override the method and provide its own implementation. d. There is no conflict because interfaces cannot provide method implementation. 26. Which of the following are not allowed in a Java 8 interface declaration? a. instance variables b. default methods c. static methods d. constants 27. 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. 28. Which of the following is true regarding a class and interface types? a. You can convert from a class type to any interface type that the class extends. b. You cannot convert from a class type to any interface type. c. You can convert from a class type to any interface type that the class implements. d. You can convert from a class type to any interface type that is in the same package as the class. 29. Consider the following code snippet.

public interface Measurable { double getMeasure(); } public class Coin implements Measurable { public Coin(double aValue, String aName) { ... } public double getMeasure() { return value; } ... } public class BankAccount implements Measurable { public BankAccount(double initBalance) { ... } public void getMeasure() { return balance; Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch10

} ... } Which of the following statements is correct? a. Coin dime = new Coin(0.1, "dime");

BankAccount b = (Measureable)dime; b. Measureable m = new BankAccount(1000); BankAccount b = m; c. Coin dime = new Coin(0.1, "dime"); Measurable m = dime; d. Measurable m = new Coin(0.1, "dime"); Coin dime = m;

30. Which of the following statements about interfaces is true? a. You cannot define a variable whose type is an interface. b. You can define an interface variable that refers to an object of any class in the same package. c. You can define an interface variable that refers to an object only if the object belongs to a class that implements the interface. d. You can instantiate an object from an interface class. 31. If you have multiple classes in your program that have implemented the same interface in different ways, how is the correct method executed? a. The method must be qualified with the class name to determine the correct method. b. The Java virtual machine must locate the correct method by looking at the class of the actual object. c. You cannot have multiple classes in the same program with different implementations of the same interface. d. The compiler must determine which method implementation to use. 32. Consider the following declarations:

public interface Displayable { void display(); } public class Picture implements Displayable { private int size; public void increaseSize() { size++; } public void decreaseSize() { size--; } Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch10

public void display() { System.out.println(size); } public void display(int value) { System.out.println(value * size); } } What method invocation can be used to complete the code segment below?

Displayable picture = new Picture(); picture._________________; a. increaseSize() b. decreaseSize() c. display(5) d. display() 33. Which of the following can potentially be changed when implementing an interface? a. The return type of a method in the interface. b. The types of parameters of a method in the interface. c. The name of a method in the interface. d. You cannot change the name, return type, or types of parameters of a method in the interface. 34. Using the given definition of the Measurable interface:

public interface Measurable { double getMeasure(); } Consider the following code snippet, assuming that BankAccount has a getBalance method and implements the Measurable interface by providing an implementation for the getMeasure method:

Measurable m = new BankAccount(); System.out.println(m.getBalance()); Which of the following statements is true? a. The code does not compile because a variable of type Measurable does not have a getBalance method. b. The code compiles but generates an exception at run time because a Measurable object reference does not have a getBalance method. c. The code executes, displaying the balance of the bank account. Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch10 d. The code does not compile because you cannot assign a BankAccount object to a variable of type Measurable. 35. Using the given definition of the Measurable interface:

public interface Measurable { double getMeasure(); } Consider the following code snippet, assuming that BankAccount has a getBalance method and implements the Measurable interface by providing an implementation for the getMeasure method:

Measurable m = new BankAccount(); System.out.println(_________________________); Select the correct expression to display the balance of the bank account. a. m.BankAccount.getBalance() b. m.getBalance() c. ((BankAccount) m).getBalance() d. m.super.getBalance() 36. Using the given definition of the Measurable interface:

public interface Measurable { double getMeasure(); } Consider the following code snippet, assuming that BankAccount has a getBalance method and implements the Measurable interface by providing an implementation for the getMeasure method:

Measurable m = new Measurable(); System.out.println(m.getMeasure()); Which of the following statements is true? a. The code executes, displaying the measure of the Measurable object. b. The code does not compile because interface types cannot be instantiated. c. The code compiles but generates an exception at run time because getMeasure does not return a String. d. The code compiles but generates an exception at run time because m does not reference a BankAccount object. 37. Consider the following class:

public class Player implements Comparable { private String name; private int goalsScored; Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch10

// other methods go here public int compareTo(Object otherObject) { __________________________________ return (goalsScored – otherPlayer.goalsScored); } } What statement can be used to complete the compareTo() method? a. Player otherPlayer = (Player) otherObject; b. Object otherPlayer = (Player) otherObject; c. Object otherPlayer = otherObject; d. Player otherPlayer = otherObject; 38. The method below is designed to return the smaller of two Comparable objects received as arguments. Assume that the objects are instances of the same class. Select the correct expression to complete the method.

public static Comparable smaller(Comparable value1, Comparable value2) { if (_________________________ ) return value1; else return value2); } a. value1.compareTo(value2) > 0 b. value1 < value2 c. value1.compareTo(value2) < 0 d. value1.compareTo(value2) == 0 39. Consider the following class:

public class BowlingGame implements Comparable { private int score; // other methods go here public int compareTo(Object otherObject) { BowlingGame otherGame = (BowlingGame) otherObject; __________________________________; } } What statement can be used to complete the compareTo() method? Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch10 a. otherGame.score – score b. return (otherGame.score – score) c. score – otherGame.score d. return (score – otherGame.score) 40. Consider the following class:

public class Temperature implements Comparable { private int value; // other methods go here public int compareTo(Object otherObject) { Temperature otherTemp = (Temperature) otherObject; __________________________________; } } Which is the best statement to use to complete the compareTo() method? a. return Integer.compare(otherTemp.value, value) b. return (value – otherTemp.value) c. return (otherTemp.value – value) d. return Integer.compare(value, otherTemp.value) 41. Consider the following class:

public class Stock implements Comparable { private String name; private double price; // other methods go here public int compareTo(Object otherObject) { Stock otherStock = (Stock) otherObject; __________________________________; } } Which is the best statement to use to complete the compareTo() method? a. return (otherStock.price – price) b. return Integer.compare(price, otherStock.price) c. return Double.compare(otherStock.price, price) d. return Double.compare(price, otherStock.price) Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch10 42. Which of the following statements about the Object.clone method is NOT true? a. Its return type is the same as the cloned object. b. It returns a new object that has a state identical to the cloned object. c. If the object being cloned does not implement the Cloneable interface, then it throws an exception. d. It does not clone mutable instance variables. 43. Consider the following code snippet:

BankAccount account = new BankAccount(500); Which of the following statements correctly clones the account? a. BankAccount clonedAccount = Object.clone(account); b. BankAccount clonedAccount = account.super.clone(); c. BankAccount clonedAccount = account.clone(); d. BankAccount clonedAccount = (BankAccount) account.clone(); 44. Which of the following statements about a callback is NOT true? a. A callback can be implemented using an interface. b. A callback can allow you to implement a new method for a class that is not under your control. c. A callback method declared in an interface must specify the class of objects that it will manipulate. d. A callback is a mechanism for specifying code to be executed later. 45. You wish to implement a callback method for an object created from a library class that you cannot change. What is the preferred way to accomplish this? a. Extend the library class. b. Use an inner class in the interface. c. Create a new class that mimics the library class. d. Use a helper class that implements the callback method. 46. Consider the following declarations:

public interface Measurer { int measure(Object anObject); } public class StringLengthMeasurer implements Measurer { public int measure(_________________) { String str = (String) anObject; return str.length(); } } Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch10 What parameter declaration can be used to complete the callback measure method? a. String aString b. Object aString c. Object anObject d. String anObject 47. Which of the following statements about lambda expressions is NOT true? a. Lambda expressions are used to define a single function of a functional interface. b. A lambda expression defines the parameters and return value of a method in a compact notation. c. Lambda expressions are a convenient notation for callbacks. d. Lambda expressions cannot contain a method body enclosed in braces with a return statement. 48. Which of the following correctly defines a functional interface that, given an object, returns the value of a Coin? a. (Object obj) => ((Coin) obj).getValue() b. (Object obj) -> (Coin) obj.getValue() c. (Object obj) => (Coin) obj.getValue() d. (Object obj) -> ((Coin) obj).getValue() 49. Consider the following code snippet that uses the parameterized Comparable interface.

public class BowlingGame implements Comparable<BowlingGame> { private int score; ... public int compareTo(BowlingGame other) { _______________________________ } } Which of the following completes the compareTo implementation? a. BowlingGame otherGame = (Object) other; return otherGame.score - score; b. return score - other.score;

c. BowlingGame otherGame = (Object) other; return score - otherGame.score; d. return other.score - score;

50. Assuming that interface Resizable is declared elsewhere, consider the following class declaration:

public class InnerClassExample { public static void main(String[] args) { class SizeModifier implements Resizable { // class methods Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch10

} __________________________ // missing statement } } Which of the following declarations can be used to complete the main method? a. SizeModifier something = new Resizable(); b. Resizable something = new Resizable(); c. Resizable something = new InnerClassExample(); d. Resizable something = new SizeModifier(); 51. A/an ____ class defined in a method signals to the reader of your program that the class is not interesting beyond the scope of the method. a. protected b. interface c. abstract d. inner 52. Which of the following statements about an inner class is true? a. An inner class is used for a utility class that should be visible elsewhere in the program. b. An inner class that is defined inside a method is publicly accessible. c. An inner class that is defined inside a method is not publicly accessible. d. An inner class that is defined inside an enclosing class but outside of its methods is not available to all methods of the enclosing class. 53. Consider the following code snippet:

myImage.add(new Rectangle(10,10,10,10)); This code is an example of using ____. a. an anonymous class. b. an abstract class. c. an anonymous object. d. an abstract object. 54. Which of the following statements about a mock class is true? a. A mock class does not provide an implementation of the services of the actual class. b. A mock class must be an interface. c. A mock class provides a simplified implementation of the services of the actual class. d. A mock class provides a complete implementation of the services of the actual class. 55. What role does an interface play when using a mock class? a. An interface should be implemented by both the real class and the mock class to guarantee that the mock class accurately simulates the real class when used in a program. b. The mock class should be an interface that will be implemented by the real class. c. Interfaces are not involved when using mock classes. Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch10 d. The real class should be an interface that will be implemented by the mock class. 56. Which of the following statements about events and graphical user interface programs is true? a. Your program must instruct the Java window manager to send it notifications about specific types of events to which the program wishes to respond. b. The Java window manager will automatically send your program notifications about all events that have occurred. c. Your program must override the default methods to handle events. d. Your program must respond to notifications of all types of events that are sent to it by the Java window manager. 57. Consider the following class:

public class ClickListener implements ActionListener { __________________________________________ { System.out.println("button event ..."); } } Which of the following method headers should be used to complete the ClickListener class? a. public void actionPerformed(ActionEvent event) b. public void actionPerformed(ClickListener event) c. public void actionPerformed() d. public void actionPerformed(ActionListener event) 58. ____ are generated when the user presses a key, clicks a button, or selects a menu item. a. Errors b. Interfaces c. Events d. Listeners 59. An ____ belongs to a class whose methods describe the actions to be taken when a user clicks a user-interface graphical object. a. event source b. event listener c. action method d. action listener 60. Which of the following is an event source? a. An inner class. b. An event listener. c. A JButton object. d. An event adapter. Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch10 61. To respond to a button event, a listener must supply instructions for the ____ method of the ActionListener interface. a. eventAction b. actionPerformed c. actionEvent d. eventResponse 62. To associate an event listener with a JButton component, you must use the ___ method of the JButton class. a. addActionListener b. addButtonListener c. addListener d. addEventListener 63. The methods of an ____ describe the actions to be taken when an event occurs. a. event source b. event interface c. action source d. event listener 64. When an event occurs, the event source notifies all ____. a. event listeners b. components c. panels d. interfaces 65. Which container is used to group multiple user-interface components together? a. text area b. rectangle c. table d. panel 66. Consider the following code snippet:

import ____________________ import java.awt.event.ActionListener; /** An action listener that prints. */ public class ClickListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("I was clicked."); } Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch10

} Which of the following statements will complete this code? a. java.swing.event.ActionEvent;. b. javax.awt.event.ActionEvent; c. java.awt.event.ActionEvent; d. javax.swing.event.ActionEvent; 67. Event listeners are often installed as ____ classes so that they can have access to the surrounding fields, methods, and final variables. a. interface b. helper c. inner d. abstract 68. Which of the following statements about an inner class is true? a. An inner class may not be declared within a method of the enclosing scope. b. The methods of an inner class can access variables declared in the enclosing scope. c. An inner class may only be declared within a method of the enclosing scope. d. An inner class can access variables from the enclosing scope only if they are passed as constructor or method parameters. 69. Consider the following code snippet:

public class ClickListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("I was clicked."); } } public class ButtonTester { public static void main(String[] args) { JFrame frame = new JFrame(); JButton button = new JButton("Click me!"); frame.add(button); ActionListener listener = new ClickListener(); button.addActionListener(listener); ... } } Which of the following statements is correct? a. A ClickListener object has been added as a listener for the action events that buttons generate. Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch10 b. Class ClickListener is an interface type. c. Class ButtonTester implements an interface type. d. Class ButtonTester is an interface type. 70. Listeners are typically implemented as inner classes. Which of the following statements is NOT true about inner class access to variables from the surrounding class? a. Inner class objects created inside a static method can only access static variables. b. Local variables that are accessed by an inner class method must not change after they have been initialized. c. Methods of an inner class cannot access variables from the surrounding class. d. An inner class can access instance variables of the surrounding class if the instance variable belongs to the object that constructed the inner class object. 71. Which of the following correctly defines a ButtonListener as an inner class and creates an instance of ButtonListener as a listener for the button? a. class ButtonListener implements ActionListener {

public void actionPerformed(AnEvent event) { System.out.println("Button clicked"); } } button.addActionListener(new ButtonListener()); b. class ButtonListener implements ActionEvent { public void actionPerformed(ActionListener event) { System.out.println("Button clicked"); } } ActionListener listener = new ButtonListener(); button.addActionListener(listener); c. class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("Button clicked"); } } ActionListener listener = new ButtonListener(); listener.actionPerformed(event); d. class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("Button clicked"); } } button.addActionListener(new ButtonListener()); Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch10 72. Which of the following is an example of a functional interface, having a single abstract method? a. ActionListener b. KeyListener c. MouseListener d. MouseAdapter 73. Which of the following correctly completes the Java statement shown to add a listener to a button using a lambda expression?

button.addActionListener(_________________________________); a. (ActionEvent event) => System.out.println("Clicked!") b. lambda((ActionEvent event) -> System.out.println("Clicked!")) c. (ActionEvent event) -> System.out.println("Clicked!") d. lambda(ActionEvent event, System.out.println("Clicked!")) 74. Which of the following code statements creates a graphical button that has "Calculate" as its label ? a. JButton button = new JButton().label("Calculate"); b. JButton button = new JButton().add("Calculate"); c. JButton button = new JButton("Calculate"); d. Button button = new Button("Calculate"); 75. To build a user interface that contains graphical components, the components ____. a. must each be added to a separate panel. b. must be added directly to a frame component. c. must be added to a panel that is contained within a frame. d. must be added to a frame that is contained within a panel. 76. Consider the following code snippet:

JFrame frame = new JFrame(); JPanel panel = new JPanel(); Which statement would add the panel to the frame? a. frame.add(JPanel panel); b. frame.addComponent(JPanel panel); c. frame.add(panel); d. frame.addComponent(panel); 77. How do you specify what the program should do when the user clicks a button? a. Specify the actions to take in a class that implements the ButtonListener interface. b. Specify the actions to take in a class that implements the EventListener interface. c. Specify the actions to take in a class that implements the ButtonEvent interface. d. Specify the actions to take in a class that implements the ActionListener interface. Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch10 78. A ____ has an addActionListener() method for specifying which object is responsible for implementing the action associated with the object. a. JSlider b. JButton c. JFrame d. JLabel 79. Consider the following code snippet which is supposed to show the total order amount when the button is clicked:

public static void main(String[] args) { final Order myOrder = new Order(); JButton button = new JButton("Calculate"); final JLabel label = new JLabel("Total amount due"); . . . class MyListener implements ActionListener { public void actionPerformed(ActionEvent event) { label.setText("Total amount due " + myOrder.getAmountDue()); } } ActionListener listener = new MyListener(); } What is wrong with this code? a. button should be declared as final b. There is no error. c. The listener cannot access the methods of the myOrder object. d. The listener has not been attached to the button. 80. Assuming that the ClickListener class implements the ActionListener interface, what statement should be used to complete the following code segment?

ClickListener listener = new ClickListener(); JButton myButton = new JButton("Submit"); JPanel myPanel = new JPanel(); myPanel.add(myButton); ______________________ //missing statement a. myButton.addActionListener(listener); b. myPanel.addActionListener(myButton); c. myPanel.addActionListener(listener); d. myButton.addActionListener(ClickListener); 81. What is the preferred way to implement event listeners? Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch10 a. Use interfaces as event listeners. b. Use inner classes as event listeners. c. Use methods as event listeners. d. Use containers as event listeners. 82. The ____ class in the javax.swing package generates a sequence of events, spaced apart at even time intervals. a. Clock b. TimeClock c. Timer d. StopWatch 83. Assume that the TimerListener class implements the ActionListener interface. If the actionPerformed method in TimerListener needs to be executed once per second, what statement should be used to complete the following code segment?

ActionListener listener = new TimerListener(); _________________________________ // missing statement timer.start(); a. Timer timer = new Timer(listener); b. Timer timer = new Timer(1000, listener); c. Timer timer = new Timer(1, listener); d. Timer timer = new Timer(100, listener); 84. When you use a timer, you need to define a class that implements the ____ interface. a. TimerListener b. TimerActionListener c. ActionListener d. StartTimerListener 85. Consider the code snippet below:

public class RectangleComponent extends JComponent { private Rectangle box; private static final int BOX_X = 100; private static final int BOX_Y = 100; private static final int BOX_WIDTH = 20; private static final int BOX_HEIGHT = 30; public RectangleComponent() { // The rectangle that the paint method draws box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT); Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch10

} public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.draw(box); } public void moveTo(int x, int y) { box.setLocation(x, y); repaint(); } } Which statement causes the rectangle to appear at an updated location? a. g2.draw(box); b. private Rectangle box; c. box.setLocation(x, y); d. repaint(); 86. Consider the following code snippet:

class MyListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println(event); } } Timer t = new Timer(interval, listener); t.start(); What is wrong with this code? a. The Timer object must be declared as final. b. There is nothing wrong with the code. c. The listener has not been attached to the Timer object. d. The Timer object should be declared before the MyListener class. 87. You have a class that extends the JComponent class. In this class you have created a painted graphical object. Your code will change the data in the graphical object. What additional code is needed to ensure that the graphical object will be updated with the changed data? a. You must call the component object's paintComponent() method. b. You must call the component object's repaint() method. Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch10 c. You do not have to do anything – the component object will be automatically repainted when its data changes. d. You must use a Timer object to cause the component object to be updated. 88. The ____ method should be called whenever you modify the shapes that the paintComponent method draws. a. repaint b. draw c. redraw d. paint 89. To process mouse events, you need to define a class that implements the ____ interface. a. EventListener b. TimerListener c. ActionListener d. MouseListener 90. If the user presses and releases a mouse button in quick succession without moving the mouse, which methods of the MouseListener interface are called? a. Only the mouseDblClicked method. b. mousePressed, mouseReleased, and mouseClicked. c. mousePressed, mouseReleased, and mouseDblClicked d. Only the mouseClicked method. 91. If the user wants to paint a user-interface component in a special way whenever the mouse is pointing inside it, which methods of the MouseListener interface are useful? a. mouseEntered and mouseExited b. mouseEntered, mouseExited, and mouseClicked c. Only the mouseExited method d. Only the mouseEntered method 92. Suppose listener is an instance of a class that implements the MouseListener interface. How many methods does listener have? a. 0 b. at least 5 c. 3 d. 1 93. Use the ____ method to add a mouse listener to a component. a. addActionListener b. addMouseListener c. addMouseActionListener d. addListener 94. You wish to detect when the mouse is moved into a graphical component. Which methods of the MouseListener interface will provide this information? Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch10 a. mouseOver b. mouseEntered c. mouseIncoming d. mouseMoved 95. Consider the following code snippet:

class MouseClickedListener implements ActionListener { public void mouseClicked(MouseEvent event) { int x = event.getX(); int y = event.getY(); component.moveTo(x,y); } } What is wrong with this code? a. There is nothing wrong with this code. b. The class has implemented the wrong interface. c. repaint() method was not called. d. The mouseClicked method cannot access the x and y coordinates of the mouse. 96. Consider the following code snippet:

public class MyMouseListener { public void mousePressed(MouseEvent event) { double x; double y; _______ System.out.println("x: " + x + ", y: " + y); } } Which of the following statements should be in the indicated position to print out where the mouse was pressed? a. x = event.printX(); y = event.printY(); b. x = (MouseEvent) getX(); y = (MouseEvent) getY(); c. x = event.getX(); y = event.getY(); d. x = event.getXposition(); y = event.getYposition();

97. To process keyboard events, you need to define a class that implements the ____ interface. Powered by Cognero

Page 25


Name:

Class:

Date:

testbank-bj-7-ch10 a. KeyListener b. ActionListener c. EventListener d. KeyboardListener 98. If the user wants to process keystrokes, which methods of the KeyListener interface must be implemented? a. Only the keyTyped method b. keyPressed and keyReleased c. keyPressed, keyReleased, and keyTyped d. Only the keyPressed method 99. What does the MouseAdapter class provide? a. A class can implement the MouseAdapter class to handle mouse events. b. The MouseAdapter class allows your program to accept input from multiple mice. c. The MouseAdapter class implements all of the methods of the MouseListener interface as do-nothing methods, eliminating the need to provide an implementation for all 5 methods of the MouseListener interface. d. The MouseAdapter class implements all of the methods of the ActionListener interface as do-nothing methods, eliminating the need to implement the ActionListener interface. 100. Which of the following is the correct class header for a MouseClickListener class that wants to take advantage of the do-nothing methods provided by the MouseAdapter class? a. class MouseClickListener implements MouseAdapter b. class MouseClickListener extends MouseAdapter c. interface MouseClickListener extends MouseAdapter d. class MouseClickListener implements MouseListener

Powered by Cognero

Page 26


Name:

Class:

Date:

testbank-bj-7-ch10 Answer Key 1. a 2. a 3. b 4. d 5. c 6. d 7. d 8. b 9. d 10. b 11. c 12. b 13. b 14. d 15. d 16. a 17. d 18. b 19. c 20. c 21. c 22. d 23. d 24. c 25. c Powered by Cognero

Page 27


Name:

Class:

Date:

testbank-bj-7-ch10 26. a 27. b 28. c 29. c 30. c 31. b 32. d 33. d 34. a 35. c 36. b 37. a 38. c 39. d 40. d 41. d 42. a 43. d 44. c 45. d 46. c 47. d 48. d 49. b 50. d 51. d Powered by Cognero

Page 28


Name:

Class:

Date:

testbank-bj-7-ch10 52. c 53. c 54. c 55. a 56. a 57. a 58. c 59. b 60. c 61. b 62. a 63. d 64. a 65. d 66. c 67. c 68. b 69. a 70. c 71. d 72. a 73. c 74. c 75. c 76. c Powered by Cognero

Page 29


Name:

Class:

Date:

testbank-bj-7-ch10 77. d 78. b 79. d 80. a 81. b 82. c 83. b 84. c 85. d 86. c 87. b 88. a 89. d 90. b 91. a 92. b 93. b 94. b 95. b 96. c 97. a 98. c 99. c 100. b

Powered by Cognero

Page 30


Name:

Class:

Date:

testbank-bj-7-ch11

Indicate the answer choice that best completes the statement or answers the question. 1. 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) throws FileNotFoundException { String inputFileName = "dataIn.txt"; File inputFile = new File(inputFileName); Scanner in = _______________; . . . } a. new Scanner(inputFile) b. new Scanner(inputFileName) c. new Scanner(outputFileName) d. new Scanner(System.in) 2. 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 3. Insert the missing code in the following code fragment. This fragment is intended to read a file named dataIn.txt and write to a file named dataOut.txt.

public static void main(String[] args) throws FileNotFoundException { String inputFileName = "dataIn.txt"; String outputFileName = "dataOut.txt"; File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); PrintWriter out = _____________; . . . }

Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch11 a. new PrintWriter(outputFile) b. new PrintWriter(outputFileName) c. new Scanner(outputFile) d. new Scanner(outputFileName) 4. 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. 5. Under which condition will the PrintWriter constructor generate a FileNotFoundException? a. If the output file does not exist. b. If the output file cannot be opened or created due to a security error. c. If the output file already exists, but is empty. d. If the output file already exists, but has data in it. 6. Under which condition will the Scanner constructor generate a FileNotFoundException? a. If the input file already exists, but is empty. b. If the input file does not exist. c. If any I/O error occurs while opening the file. d. If the input file already exists, but has data in it. 7. Which of the following statements reflects the recommendations about closing files? a. Only the output file must be explicitly closed in the program. b. Both the input and the output file should be explicitly closed in the program. c. Only the input file must be explicitly closed in the program. d. Both the input and the output file should not be explicitly closed in the program. 8. Which of the following is the correct syntax for creating a File object? a. File inFile = new File("input.txt"); b. File inFile = File.open("input.txt"); c. File inFile = File("input.txt"); d. File inFile = new File.open("input.txt"); 9. Which of the following objects should be used for reading from a text file? a. Scanner b. PrintStream c. ReadStream d. ReadFile 10. Consider the following code snippet:

public static void main(String[] args) throws FileNotFoundException Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch11 Which of the following statements about this code is correct? a. The main method is designed to catch and handle all types of exceptions. b. The main method will not terminate if any exception occurs. c. The main method is designed to catch and handle the FileNotFoundException. d. The main method terminates if the FileNotFoundException occurs. 11. Consider the following code snippet:

public static void main(String[] args) throws IOException Which of the following statements about this code is correct? a. The main method will not terminate if any exception occurs. b. The main method is designed to catch and handle all types of exceptions. c. The main method is designed to catch and handle the IOException. d. The main method terminates if the IOException occurs. 12. Which of the following statements about a PrintWriter object is true? a. A PrintWriter will be automatically closed when the program exits. b. No data loss will occur if the program fails to close a PrintWriter before exiting. c. An exception will occur if the program fails to close a PrintWriter before exiting. d. Data loss may occur if a program fails to close a PrintWriter object before exiting. 13. Your program will read in an existing text file. You want the program to terminate if the file does not exist. Which of the following indicates the correct code for the main method header? a. public static void main(String[] args) throws FileNotFoundException b. public static void main(String[] args) throws UnknownFileException c. public static void main(String[] args) d. public static void main(String[] args) throws FileMissingException 14. Consider the following code snippet:

File inputFile = new File("input.txt"); You wish to read the contents of this file using a Scanner object. Which of the following is the correct syntax for doing this? a. Scanner in = new Scanner("input.txt"); b. Scanner in = new Scanner(inputFile); c. Scanner in = Scanner.open(inputFile); d. Scanner in = Scanner("input.txt"); 15. Select an expression to complete the following statement, which is designed to construct a PrintWriter object to write the program output to a file named dataout.txt.

PrintWriter theFile = _______________________; a. new Scanner("dataout.txt") Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch11 b. new File("dataout.txt") c. new PrintWriter("dataout.txt") d. new PrintStream("dataout.txt") 16. 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. 17. The PrintWriter class is an enhancement of the ____ class. a. File b. ReadStream c. Scanner d. PrintStream 18. Which of the following statements about reading and writing text files is correct? a. You use the Scanner class to read text files and the PrintWriter class to write text files. b. You use the Scanner class to write text files and the PrintWriter class to read text files. c. You use the Scanner class to read and write text files. d. You use the PrintWriter class to read and write text files. 19. Insert the missing code in the following code fragment. This fragment is intended to read an input file named dataIn.txt and write to an output file named dataOut.txt.

public static void main(String[] args) throws FileNotFoundException { String inputFileName = "dataIn.txt"; String outputFileName = "dataOut.txt"; File inputFile = _________________; Scanner in = new Scanner(inputFile); . . . } a. new File(inputFile) b. new File(System.in) c. new File(outputFileName) d. new File(inputFileName) 20. Insert the missing code in the following code fragment. This fragment is intended to read an input file named dataIn.txt and write to an output file named dataOut.txt. Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch11

public static void main(String[] args) throws FileNotFoundException { String inputFileName = "dataIn.txt"; String outputFileName = "dataOut.txt"; File inputFile = new File(inputFileName); Scanner in = _________; PrintWriter outFile = new PrintWriter("dataOut.txt"); . . . } a. new File("dataIn.txt") b. new Scanner(inputFile) c. new Scanner("dataIn.txt") d. new File(inputFileName) 21. Consider the following code snippet.

File hoursFile = new File("hoursWorked.txt"); Your program must read the contents of this file using a Scanner object. Which of the following is the correct syntax for doing this? a. Scanner in = new Scanner("hoursWorked.txt"); b. Scanner in = new Scanner(hoursFile); c. Scanner in = Scanner.open(hoursFile); d. Scanner in = Scanner("hoursWorked.txt"); 22. Consider the following code snippet.

PrintWriter outputFile = new PrintWriter("payrollReport.txt"); Which of the following statements about the PrintWriter object is correct? a. If a file named "payrollReport.txt" already exists, a new file named "payrollReport_1.txt" will be created and used. b. If a file named "payrollReport.txt" already exists, an exception will occur. c. If a file named "payrollReport.txt" already exists, existing data will be deleted before new data are added to the file. d. If a file named "payrollReport.txt" already exists, new data will be added to the end of the file. 23. Which of the following statements about using a PrintWriter object is NOT true? a. PrintWriter is an enhancement of the PrintStream class. b. A program can write to a PrintWriter using println. c. A PrintWriter will be automatically closed when the program exits. d. Data loss may occur if a program fails to close a PrintWriter object before exiting. 24. Your program must read in an existing text file. You want the program to terminate if any exception related to the file Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch11 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 25. Insert the missing code in the following code fragment. This fragment is intended to read an input file named hoursWorked.txt. You want the program to terminate if the file does not exist.

public static void main(String[] args)______________ { File inputFile = new File("hoursWorked.txt"); Scanner in = new Scanner(inputFile); . . . } a. throws FileMissingException b. catch FileNotFoundException c. catch FileMissingException d. throws FileNotFoundException 26. Insert the missing code in the following code fragment. This fragment is intended to write an output file named dataOut.txt that resides in a folder named reports on the C: drive of a Windows system.

public static void main(String[] args) throws IOException { PrintWriter outputFile = _______; . . . } a. new PrintWriter("c:\\reports\\dataOut.txt") b. new PrintWriter("c:/reports/dataOut.txt") c. new PrintWriter("c://reports//dataOut.txt") d. new PrintWriter("c:\reports\dataOut.txt") 27. Insert the missing code in the following code fragment. This fragment is intended to read an input file named dataIn.txt that resides in a folder named payroll on the C: drive of a Windows system.

public static void main(String[] args) throws FileNotFoundException { File inputFile = ________; Scanner in = new Scanner(inputFile); . . . } a. new File(c://payroll//"dataIn.txt") b. new File("c:\payroll\dataIn.txt") Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch11 c. new File("c:\\payroll\\dataIn.txt") d. new File(c:/payroll/"dataIn.txt") 28. Your program wishes to open a file named C:\java\myProg\input.txt on a Windows system. Which of the following is the correct code to do this? a. inputFile = new File("c:\java\myProg\input.txt"); b. inputFile = new File.open("c:\\java\\myProg\\input.txt"); c. inputFile = new File("c:\\java\\myProg\\input.txt"); d. inputFile = new File.open("c:\java\myProg\input.txt"); 29. Consider the following code snippet.

Scanner inputFile = new Scanner("dataIn.txt"); Which of the following statements is correct? a. This code will not open a file named "dataIn.txt", but will treat the string "dataIn.txt" as an input value. b. This code will open a file named "dataIn.txt" for writing. c. This code will create a new file named "dataIn.txt". d. This code will open an existing file named "dataIn.txt" for reading. 30. Consider the following code snippet.

Scanner inputFile = new Scanner("hoursWorked.txt"); Which of the following statements is correct? a. This code will open an existing file named "hoursWorked.txt" for reading. b. This code will create a new file named "hoursWorked.txt". c. This code will treat the string "hoursWorked.txt" as an input value. d. This code will open a file named "hoursWorked.txt" for writing. 31. Insert the missing code in the following code fragment. This fragment is intended to read a web page.

public static void main(String[] args) throws IOException { String address = "http://horstmann.com/index.html"; URL pageLocation = new URL(address); Scanner in = _________; . . . } a. new Scanner(pageLocation.openStream()) b. new Scanner(new File(pageLocation)) c. new Scanner("http://horstmann.com/index.html") d. new Scanner(pageLocation) Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch11 32. Which of the following statements about reading web pages is true? a. A Scanner object cannot be used to read a web page. b. You must create a URL object to use with a Scanner object to read a web page. c. You must use the openStream() method of a Scanner object to read a web page. d. You must create a File object to use with a Scanner object to read a web page. 33. Which Java class implements a file dialog box for selecting a file by a program with a graphical user interface? a. JOptionPane b. JFileChooser c. JFilePane d. JFileOption 34. Which method of the JFileChooser object will return the file object that describes the file chosen by the user at runtime? a. getSelectedFilePath() b. getSelectedFile() c. getFilePath() d. getFile() 35. Which return value of the JFileChooser object's showOpenDialog method indicates that a file was chosen by the user at run time? a. OK_OPTION b. SELECTED_OPTION c. CANCEL_OPTION d. APPROVE_OPTION 36. Insert the missing code in the following code fragment. This fragment is intended to allow the user to select a file to be opened.

JFileChooser chooser = new JFileChooser(); Scanner in = null; if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File selectedFile = __________; in = new Scanner(selectedFile); . . . } a. chooser.getFileName() b. chooser.getSelectedFileName() c. chooser.getSelectedFile() d. chooser.getFilePath() 37. Which of the following statements about character encodings is NOT true? a. It is recommended to specify the UTF-8 encoding when processing files with special symbols or characters in multiple languages. Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch11 b. Java assumes the UTF-8 encoding. c. A character is encoded as a sequence of bytes, each having a value between 0 and 255. d. Java supports the reading and writing of files in the UTF-8 encoding. 38. Assuming that inputFile is a Scanner object used to read words from a text file, select an expression to complete the following code segment, which counts the number of words in the input file.

int count = 0; while (inputFile.hasNext()) { String word = _______________; count++; } System.out.println(count); a. inputFile.nextString() b. inputFile.nextDouble() c. inputFile.next() d. inputFile.nextInt() 39. 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. 40. Consider the following code snippet.

File inputFile = new File("dataIn.txt"); Scanner in = new Scanner(inputFile); while (in.hasNext()) { String input = in.next(); } Which of the following statements about this code is correct? a. This code will read in a word at a time from the input file. b. This code will read in a line at a time from the input file. c. This code will read in the entire input file in one operation. d. This code will read in a character at a time from the input file. 41. 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 Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch11 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 42. Insert the missing code in the following code fragment. This fragment is intended to read all words from a text file named dataIn.txt.

File inputFile = new File("dataIn.txt"); Scanner in = new Scanner(inputFile); while (____________) { String input = in.next(); System.out.println(input); } a. in.getNext() b. in.nextWord() c. in.hasNext() d. in.peek() 43. Which of the following statements about white space in Java is correct? a. In Java, white space includes spaces, tab characters, newline characters, and punctuation. b. In Java, white space includes spaces and tab characters only. c. In Java, white space includes spaces, tab characters, and newline characters. d. In Java, white space includes spaces only. 44. Insert the missing code in the following code fragment. This fragment is intended to read characters from a text file.

Scanner in = new Scanner(. . .); in.useDelimiter(""); while (in.hasNext()) { char ch = ____________; System.out.println(ch); } a. in.getNext() b. in.next().charAt(0) c. in.next() d. in.nextChar() 45. Which of the following patterns should be used for the delimiter to read one character at a time using a Scanner object's next method? a. Scanner in = new Scanner(. . .); in.useDelimiter("[^0-9]+"); b. Scanner in = new Scanner(. . .); in.useDelimiter("");

Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch11 c. Scanner in = new Scanner(. . .); in.useDelimiter("[^A-Za-z]+"); d. Scanner in = new Scanner(. . .); in.useDelimiter("[A-Za-z]+");

46. The ______ method of the Scanner class specifies a pattern for word boundaries when reading text. a. setDelimiter() b. usePattern() c. useDelimiter() d. setPattern() 47. The ____ method of the Character class will indicate if a character contains white space. a. isValid() b. getChar() c. hasNext() d. isWhiteSpace() 48. Consider the following code snippet:

Scanner in = new Scanner(. . .); while (in.hasNextLine()) { String input = in.nextLine(); System.out.println(input); } Which of the following statements about this code is correct? a. This code will read in a single character from the file in each iteration of the loop. b. This code will read in the entire contents of the file in a single iteration of the loop. c. This code will read in a single word from the file in each iteration of the loop. d. This code will read in an entire line from the file in each iteration of the loop. 49. Which String class method will remove spaces from the beginning and the end of a string? a. clean() b. strip() c. truncate() d. trim() 50. Consider the following code snippet.

String line = ...; Scanner lineScanner = new Scanner(line); Which of the following statements about this code is correct? a. The methods of the Scanner class can be used on line to scan the string. b. The methods of the Scanner class can be used on lineScanner to scan the string. Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch11 c. This code will not compile because a Scanner cannot be constructed on a String. d. This code compiles but generates a run-time exception. 51. Assume inputFile is a Scanner object used to read data from a text file that contains a number of lines. Each line contains an arbitrary number of words, with at least one word per line. Select an expression to complete the following code segment, which prints the last word in each line.

while (inputFile.hasNextLine()) { String word = ""; String line = inputFile.nextLine(); Scanner words = new Scanner(line); while (_________________) { word = words.next(); } System.out.println(word); } a. words.hasNext() b. line.hasNext() c. words.hasNextInt() d. inputFile.hasNext() 52. 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() 53. 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) 54. Assume inputFile is a Scanner object used to read data from a text file that contains a number of lines. Some lines contain an alphabetic string, while others contain a single integer value. Select an expression to complete the following code segment, which counts the number of integer values in the input file.

int count = 0; while (inputFile.hasNextLine()) { if (________________________________) { count++; Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch11

} inputFile.nextLine(); } System.out.println(count); a. inputFile.hasNext() b. inputFile.hasNextInt() c. Character.isDigit(inputFile.next()) d. inputFile.nextInt() 55. Consider the following code snippet.

Scanner in = new Scanner(. . .); while (in.hasNextDouble()) { double input = in.nextDouble(); } Which of the following statements about this code is correct? a. This code will read in one word at a time from the input file. b. This code will read in one floating point value at a time from the input file. c. This code will read in one character at a time from the input file. d. This code will read in the entire input file in one operation. 56. 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() 57. Consider the following code snippet:

Scanner in = new Scanner(. . .); int ageValue = in.nextInt(); If there is no integer number appearing next in the input, what will occur? a. ageValue will contain a null value. Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch11 b. ageValue will contain a zero. c. An exception will occur. d. ageValue will contain whatever characters are encountered. 58. You wish to use the Scanner class's nextInt() method to read in whole numbers. To avoid exceptions that would occur if the input is not a whole number, you should use the ____ method before calling nextInt(). a. hasNextInteger() b. hasNext() c. hasNextInt() d. hasIntegerValue() 59. Consider the following code snippet:

Scanner in = new Scanner(. . .); String result = ""; int number = 0; if (in.hasNextInt()) { number = in.nextInt(); } result = in.next(); If the input file begins with the characters 626.14 average, what values will number and result have after this code is executed? a. number will contain the value 0 and result will contain the value average. b. number will contain the value 626.14 and result will contain the value average. c. number will contain the value 626 and result will contain the value 14. d. number will contain the value 0 and result will contain the value 626.14. 60. Consider the following code snippet:

Scanner in = new Scanner(. . .); String result = ""; double number = 0; if (in.hasNextDouble()) { number = in.nextDouble(); } result = in.next(); If the input file contains the characters 626.14 average, what values will number and result have after this code is executed? a. number will contain the value 0 and result will contain the value 626.14. b. number will contain the value 626.14 and result will contain the value average. c. number will contain the value 626 and result will contain the value 14. d. number will contain the value 0 and result will contain the value average. Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch11 61. Assume inputFile is a Scanner object used to read data from a text file that contains a series of double values. Select an expression to complete the following code segment, which reads the values and prints them in standard output, one per line, in a field 15 characters wide, with two digits after the decimal point.

while (inputFile.hasNextDouble()) { double value = inputFile.nextDouble(); ___________________________________

// statement to display double value

} a. System.out.printf("%15f",value); b. System.out.printf("%.2f",value); c. System.out.printf("%15.2f\n",value); d. System.out.printf("%15.2f",value); 62. Consider the following code snippet, assuming that description is a String and totalPrice is a double:

System.out.printf("%-12s%8.2f",description,totalPrice); Which of the following statements is correct? a. This code will produce 2 columns, with the description field left justified and the totalPrice field left justified. b. This code will produce 2 columns, with the description field right justified and the totalPrice field left justified. c. This code will produce 2 columns, with the description field right justified and the totalPrice field right justified. d. This code will produce 2 columns, with the description field left justified and the totalPrice field right justified. 63. Consider the following code snippet:

Scanner in = new Scanner(. . .); in.useDelimiter("[A-Za-z]+"); What characters will be read in using this code? a. Only alphabetic characters will be read in. b. Only numeric characters will be read in. c. Only non-numeric characters will be read in. d. Only non-alphabetic characters will be read in. 64. Consider the following code snippet:

Scanner in = new Scanner(. . .); in.useDelimiter("[^A-Za-z]+"); What characters will be ignored and not read in when using this code? Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch11 a. Only numeric characters will be ignored. b. Only non-alphabetic characters will be ignored. c. Only alphabetic characters will be ignored. d. Only non-numeric characters will be ignored. 65. Consider the following code snippet:

Scanner in = new Scanner(. . .); in.useDelimiter("[^0-9]+"); What characters will be ignored and not read in using this code? a. Only numeric characters will be ignored. b. Only non-alphabetic characters will be ignored. c. Only alphabetic characters will be ignored. d. Only non-numeric characters will be ignored. 66. Consider the following code snippet:

Scanner in = new Scanner(. . .); in.useDelimiter("[^0-9A-Za-z]+"); What characters will be ignored and not read in using this code? a. Both alphabetic and numeric characters will be ignored. b. Only numeric characters will be ignored. c. Characters that are neither alphabetic nor numeric will be ignored. d. Only alphabetic characters will be ignored. 67. Which of the following statements about command line arguments is correct? a. You must declare additional parameters in the main method to receive command line argument values. b. You cannot pass arguments to a program when starting the program from a command line prompt. c. Command line arguments can be read using the main method's args parameter. d. Command line arguments must be read with a Scanner object. 68. Which of the following is the correct syntax for starting a Java program named myProg from a command line if the program requires two arguments named arg1 and arg2 to be supplied? a. java myProg(arg1, arg2) b. java myProg "arg1" "arg2" c. java myProg arg1 arg2 d. java myProg arg1, arg2 69. When you start a Java program from a command line and supply argument values, the values ____. a. are stored as float values b. are stored as int values c. are stored as String values d. are stored as the type of value indicated by the argument Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch11 70. You have opened a command prompt window and you have entered the following:

java myProg Bob Smith Which of the following statements is correct? a. You have supplied two argument values, and these values can be accessed in the main method using the args parameter. b. You have supplied one argument value, and this value can be accessed in the main method using the arg1 parameter. c. You have supplied one argument value, and this value can be accessed in the main method using the args parameter. d. You have supplied two argument values, and these values can be accessed in the main method using the arg1 and arg2 parameters. 71. Select an expression to complete the program segment below, which is designed to read data from a file whose name is specified as the first command line argument. If no command line arguments are given, the program reads data from the default.txt file.

String fileName = "default.txt"; if ( ________________________ ) { fileName = args[0]; } // additional statements to open file and read data a. args > 0 b. args[0] != null c. args.length >= 0 d. args.length > 0 72. What is the purpose of the throw statement? a. It is used to pass control to an error handler when an error situation is detected. b. It is used to discard erroneous input. c. It is used to detect an error situation. d. It is used to pass arguments to another method. 73. Complete the code fragment below, which is designed to throw an exception if String variable accountNumber has more than seven characters.

if (accountNumber.length() > 7) { ___________________________________________ } a. throws new IllegalArgumentException("Account number exceeds maximum length"); Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch11 b. throw new IllegalArgumentException("Account number exceeds maximum length"); c. throws IllegalArgumentException("Account number exceeds maximum length"); d. throw IllegalArgumentException("Account number exceeds maximum length"); 74. Consider the following code snippet:

throw IllegalArgumentException("This operation is not allowed!"); Which of the following statements about this code is correct? a. This code constructs an object of type IllegalArgumentException and throws the object. b. This code throws an existing IllegalArgumentException object. c. This code constructs an object of type IllegalArgumentException and reserves it for future use. d. This code will not compile. 75. Consider the following code snippet:

throw new IllegalArgumentException("This operation is not allowed!"); Which of the following statements about this code is correct? a. This code throws an existing IllegalArgumentException object. b. This code will not compile. c. This code constructs an object of type IllegalArgumentException and throws the object. d. This code constructs an object of type IllegalArgumentException and reserves it for future use. 76. In the hierarchy of Exception classes, the NumberFormatException class is a subclass of the ____ class. a. ClassCastException b. IllegalStateException c. IllegalArgumentException d. ArithmeticException 77. Which of the following statements about exception reporting is true? a. Use the throw statement to report that an exception has occurred. b. Use the reportError statement to report that an exception has occurred. c. Use the reportException statement to report that an exception has occurred. d. Use the throwException statement to report that an exception has occurred. 78. Select an expression to complete the program segment below, which displays an error message and terminates normally if the String variable accountNumber does not contain an integer value.

try { int number = Integer.parseInt(accountNumber); } catch ( ________________________ ) { Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch11

System.out.println("Account number is not an integer value"); } a. NumberFormatException exception b. InputMismatchException exception c. ArithmeticException exception d. IOException exception 79. Which of the following statements about exception handling is correct? a. Statements that may cause an exception should be placed within a catch block. b. Statements that may cause an exception should be placed within a try block. c. The main method of a Java program will handle any error encountered in the program. d. Statements that may cause an exception should be placed within a throws block. 80. Which statement about handling exceptions is true? a. If an exception has no handler, the program will be terminated. b. If an exception has no handler, the error will be ignored. c. Statements to handle exceptions should be placed inside a try clause. d. Statements that may cause exceptions should be placed inside a catch clause. 81. Which method of an exception object will provide information about the chain of method calls that led to the exception? a. printStackTrace() b. getCallStack() c. printCallStack() d. getStackTrace() 82. 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) 83. Which method of an exception object will retrieve a description of the exception that occurred? Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch11 a. printStackTrace() b. printMessage() c. getDescription() d. getMessage() 84. Select an appropriate expression to complete the header for the method below.

public void openFile(String inputFile) ______________________________ { File theFile = new File(inputFile); Scanner data = new Scanner(theFile); // additional statements to input data from file } a. throws new FileNotFoundException b. throw FileNotFoundException c. throw new FileNotFoundException d. throws FileNotFoundException 85. Which of the following statements about checked and unchecked exceptions is true? a. Checked exceptions are handled by the Java runtime. b. The compiler ensures that the program is handling unchecked exceptions. c. The compiler ensures that the program is handling checked exceptions. d. All exceptions that are descendants of RunTimeException are checked exceptions. 86. The Java compiler requires that your program handle which type of exceptions? a. severe b. fatal c. checked d. unchecked 87. Which of the following statements about checked and unchecked exceptions is NOT true? a. Handling of checked exceptions is enforced by the compiler. b. Unchecked exceptions are the programmer's fault. c. Unchecked exceptions belonging to subclasses of the RunTimeException class are beyond the control of the programmer. d. Internal errors belonging to subclasses of the Error class are beyond the control of the programmer. 88. If the current method in a program will not be able to handle an exception, what should be coded into the method? a. The method should include a try/catch block for all possible exceptions. b. The method declaration should be enclosed in a try/catch block. c. The throws clause should list the name of the method to which the exception should be passed. d. The throws clause should list the names of all exceptions that the method will not handle. 89. When writing a method, which of the following statements about exception handling is true? Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch11 a. The throws clause must list all checked exceptions that this method may throw, and may also list unchecked exceptions. b. The throws clause must list all checked exceptions, but cannot list unchecked exceptions. c. The throws clause must list all unchecked exceptions, and cannot list checked exceptions. d. The throws clause must list all unchecked exceptions, and may also list checked exceptions that this method may throw. 90. Consider the following code snippet:

public void readFile(String filename) throws FileNotFoundException { File inFile = new File(filename); Scanner in = new Scanner(inFile); . . . } If the file cannot be located, which of the following statements about this code is correct? a. It cannot be determined how the method must handle the exception if the file cannot be located. b. This method must handle the exception in the body of the method. c. This method will be terminated if the file cannot be located. d. This method must use a throw statement to pass the error back to its caller. 91. An example of a fatal error that rarely occurs and is beyond your control is the ____. a. FileNotFoundException b. NumberFormatException c. RuntimeException d. OutOfMemoryError 92. 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 93. When a program throws an exception within a method that has no try-catch block, which of the following statements about exception handling is true? a. The user must decide whether to continue or terminate the program. b. The current method must decide whether to continue or terminate. c. The current method terminates immediately. d. Execution will continue with the next statement in the method. 94. Consider the following code snippet: Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch11

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. 95. Consider the following code snippet, where data is a variable defined as a double array that is populated by the readData method for valid data:

public double[] readInputFile(String filename) throws IOException { try (Scanner in = new Scanner(new File(filename))) { readData(in); return data; } } Which of the following statements about this method's code is correct? a. Any exceptions that occur in this method will be suppressed. b. This method will pass any IOException-type exception back to the caller. c. The method will never close the file if an IOException exception occurs in this method. d. This method will pass any type of exception back to the caller. 96. 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. 97. Consider the following code snippet:

File inputFile = new File(filename); try (Scanner in = new Scanner(inputFile)) { . . . } catch (Exception e) Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch11

{ } Which of the following statements about this code is correct? a. This code will not catch a FileNotFoundException that occurs in the try block. b. This code will not catch any exceptions that occur in the try block. c. This code will pass any exceptions back to its caller. d. This code will catch exceptions that occur in the try block but will do nothing about the exceptions. 98. 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); } catch (IOException exception) { . . . } Which of the following statements about this code is correct? a. The file will be closed regardless of when an exception occurs. b. The file will be closed only if the writeData() statement throws an exception. c. The file will be closed only if the PrintWriter constructor throws an exception. d. It is not possible to determine whether the file will be closed if an exception occurs. 99. 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. 100. Which exception class should you use from the standard library if you want to thrown an exception when there are insufficient funds in a bank account to cover a withdrawal? a. OutOfBoundsException Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch11 b. RunTimeException c. IOException d. IllegalArgumentException 101. 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. 102. Which of the following statements about assertions is NOT true? a. An assertion is always checked during program execution. b. If an executed assertion fails, then the assert statement throws an AssertionError exception. c. Assertion checking is particularly useful during program development and testing. d. An assertion checks that a condition is true in a particular program location. 103. Which command enables assertion checking during program execution? a. java -enableassertions MainClass b. javac -enableassertions MainClass c. javac -ea MainClass d. java -assertions MainClass 104. Which of the following statements about the try/finally statement is NOT true? a. The finally clause is executed if the body of the try completes without exception. b. The finally clause is executed if the body of the try throws exception. c. The finally clause is executed after the exception is propagated to its handler. d. The finally clause typically represents cleanup code that is to be executed whether or not an exception occurs. 105. 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.

public void String readFile() throws IOException { File inputFile = new File(. . .); try __________________________________ { while (in.hasNext()) { . . . } } } Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch11 a. {Scanner in = new Scanner(inputFile)} b. (Scanner in = new Scanner(inputFile)) c. Scanner in = new Scanner(inputFile); d. (FileNotFound exception) 106. 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.

public void String readFile() _________________ { File inputFile = new File(. . .); try (Scanner in = new Scanner(inputFile)) { while (in.hasNext()) { . . . } } } a. throws FileNotFound b. throws IllegalArgumentException c. throws IOException exception d. throws IOException 107. Consider the following code snippet, assuming in is an instantiated Scanner:

if (in.hasNext()) { throw new IOException("End of file expected"); } Which of the following statements about this code is correct? a. The program will display the message "End of file expected" if there is no data. b. The program will throw an exception if there is no data. c. The program will display the message "End of file expected" if there is data left in the input when the if statement is executed. d. The program will throw an exception if there is data left in the input when the if statement is executed. 108. Select the missing expression in the code fragment below. The method should continue to prompt the user for a valid integer value until one is entered. The method returns the final value entered.

public static int getAge() { boolean done = false; Scanner console = new Scanner(System.in); int value = 0; Powered by Cognero

Page 25


Name:

Class:

Date:

testbank-bj-7-ch11

while (!done) { try { System.out.print("Please enter your age in years: "); value = console.nextInt(); done = true; } _____________________ { System.out.println("Invalid value. Try again."); console.nextLine(); } } return value; } a. catch (IllegalArgumentException exception) b. finally c. catch (NumberFormatException exception) d. catch (NoSuchElementException exception)

Powered by Cognero

Page 26


Name:

Class:

Date:

testbank-bj-7-ch11 Answer Key 1. a 2. b 3. b 4. d 5. b 6. b 7. b 8. a 9. a 10. d 11. d 12. d 13. a 14. b 15. c 16. b 17. d 18. a 19. d 20. b 21. b 22. c 23. c 24. c 25. d Powered by Cognero

Page 27


Name:

Class:

Date:

testbank-bj-7-ch11 26. a 27. c 28. c 29. a 30. c 31. a 32. b 33. b 34. b 35. d 36. c 37. b 38. c 39. d 40. a 41. d 42. c 43. c 44. b 45. b 46. c 47. d 48. d 49. d 50. b 51. a Powered by Cognero

Page 28


Name:

Class:

Date:

testbank-bj-7-ch11 52. b 53. c 54. b 55. b 56. b 57. c 58. c 59. d 60. b 61. c 62. d 63. d 64. b 65. d 66. c 67. c 68. c 69. c 70. a 71. d 72. a 73. b 74. d 75. c 76. c Powered by Cognero

Page 29


Name:

Class:

Date:

testbank-bj-7-ch11 77. a 78. a 79. b 80. a 81. a 82. d 83. d 84. d 85. c 86. c 87. c 88. d 89. a 90. c 91. d 92. c 93. c 94. b 95. b 96. a 97. d 98. a 99. c 100. d 101. a 102. a Powered by Cognero

Page 30


Name:

Class:

Date:

testbank-bj-7-ch11 103. a 104. c 105. b 106. d 107. d 108. d

Powered by Cognero

Page 31


Name:

Class:

Date:

testbank-bj-7-ch12

Indicate the answer choice that best completes the statement or answers the question. 1. Which of the following most likely indicates that you have chosen a good name for your class? a. The name consists of a single word. b. You can tell by the name what an object of the class is supposed to represent. c. You can easily determine by the name how many concepts the class represents. d. The name describes what task the class will perform. 2. Which of the following questions should you ask yourself in order to determine if you have named your class properly? a. Does the class name contain eight or fewer characters? b. Is the class name a verb? c. Can I describe an object of the class? d. Does the class name describe the tasks that this class will accomplish? 3. Which of the following would be an appropriate name for a class used in an inventory application? a. Product b. InitializeInventoryLevel c. ResetCurrentInventoryLevel d. ReceiveNewProducts 4. You are designing an application to support an automobile rental agency. Which of the following probably should NOT be represented as an object? a. Automobile b. Customer c. Payment amount d. Rental contract 5. Classes often correspond to ____ in a requirements description. a. Verbs b. Nouns c. Dependencies d. Relationships 6. A/an ____ is used to create objects with the same behavior. a. Association b. Aggregation c. Dependency d. Class 7. After you have identified a set of classes needed for a program, you should now ____. a. Define the behavior of each class. b. Look for nouns that describe the tasks. c. Begin writing the code for the classes. d. Establish the relationships between the classes. Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch12 8. A CRC card describes ____. a. A class, its responsibilities, and its collaborating classes. b. A class, its methods, and its constructors. c. A class, its relationships, and its collaborating classes. d. A class, its requirements, and its concurrent classes. 9. When using the CRC method, other classes that are needed to fulfill the responsibilities of a given class are called its ____. a. Related classes b. Responsible classes c. Collaborators d. Concurrent classes 10. When using the CRC method, if you determine that a class cannot carry out a particular task by itself and needs the help of another class to complete the task, you should ____. a. Do nothing on this class's CRC card. The task will be shown on the other class's CRC card. b. Add this class onto the other class's CRC card as a collaborator. c. Add the other class onto this class's CRC card as a collaborator. d. Add each class onto the other class's CRC card as a collaborator. 11. How many responsibilities is/are recommended by researchers on a CRC card? a. Only one per card. b. At most two per card. c. At most three per card. d. There is no limit of responsibilities per card. 12. Which of the following is the most important consideration when designing a class? a. Each class should represent an appropriate mathematical concept. b. Each class should represent a single concept or object from the problem domain. c. Each class should represent no more than three specific concepts. d. Each class should represent multiple concepts only if they are closely related. 13. What is a general naming convention for a class? a. The name for such a class should be an adjective that describes the concept b. The name for such a class should be a noun that describes the concept c. The name for such a class should be a verb that describes the concept d. None of the above 14. When you begin designing a program, you work from a ____, a description of what your program should do. a. Requirements specification b. Blueprint c. UML Diagram d. Recipe 15. A class (ClassOne) is considered to have a dependency on another class (ClassTwo) under which of the following Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch12 conditions? a. Each class uses objects of the other. b. The public interfaces of both classes are cohesive. c. ClassTwo uses objects of ClassOne. d. ClassOne uses objects of ClassTwo. 16. A UML class diagram would be most useful in visually illustrating which of the following? a. The cohesiveness of a class's interface. b. The amount of complexity of a class's interface. c. Dependencies between classes. d. Relationships between classes and their interfaces. 17. Why is it generally considered good practice to minimize coupling between classes? a. Low coupling increases the operational efficiency of a program. b. High coupling implies less interface cohesion. c. High coupling increases program maintenance and hinders code reuse. d. Low coupling decreases the probability of code redundancy. 18. Dependency between classes denotes that ____. a. Objects of one class inherit from objects of its superclass. b. Objects of one class can be inherited by its subclasses. c. Objects of one class implement an interface. d. Methods in the objects of one class use an object of another class. 19. In a UML diagram, dependency is denoted by ____. a. A dotted/dashed line with a closed arrow tip. b. A solid line with a closed arrow tip. c. A dotted/dashed line with an open arrow tip. d. A solid line with an open arrow tip. 20. If many classes of a program depend on each other, we say that ____. a. cohesiveness is high. b. cohesiveness is low. c. coupling is high. d. coupling is low. 21. UML means____. a. Unified Mode Language b. User Modeling Language c. User Mode Language. d. Unified Modeling Language. 22. The dependency relationship is sometimes referred to as the ____ relationship. a. is-a Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch12 b. has-a c. depends-on d. knows-about 23. Which statement correctly describes the class relationship shown in this diagram? a. CashRegister class depends on Coin class b. Coin class depends on CashRegister class c. CashRegister class aggregates Coin class. d. Coin class inherits from CashRegister class. 24. Which of the following code snippets denotes that the Purse class depends on the Wallet class? a. public class Purse extends Wallet b. public class Wallet extends Purse c. public class Wallet {

private Purse aPurse; } d. public class Purse { private void setWallet(Wallet aWallet){}; }

25. Which of the following code snippets denotes that the Pen class depends on the Ink class? a. public class Pen extends Ink b. public class Ink extends Pen c. public class Pen {

private Ink anInk; } d. public class Ink { private Pen aPen; }

26. Which of the following code snippets denotes that the Kitchen class depends on the Stove class? a. public class Kitchen extends Stove b. public class Stove {

private Kitchen[] kitchens; } c. public class Kitchen { private Stove aStove; } d. public class Kitchen implements Stove

27. ____ is often described as the has-a relationship. a. Inheritance Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch12 b. Aggregation c. Polymorphism d. Dependency 28. Which of the following statements is correct? a. Dependency is a stronger form of aggregation. b. Aggregation indicates high cohesiveness. c. Aggregation indicates low coupling. d. Aggregation is a stronger form of dependency. 29. Consider the following code snippet:

public class Motorcycle { private Tire[] tires; . . . } This code is best described as an example of ____. a. Inheritance. b. Aggregation. c. Polymorphism. d. Association. 30. Consider the following code snippet:

public class Motorcycle { private Tire[] tires; . . . } Which of the following statements correctly describes the relationship between the Motorcycle and Tire classes? a. Motorcycle exhibits the has-a relationship with regards to Tire. b. Motorcycle exhibits the is-a relationship with regard to Tire. c. Tire exhibits the has-a relationship with regards to Motorcycle. d. Tire exhibits the is-a relationship with regards to Motorcycle. 31. Consider the following code snippet:

public class Purse { private Coin coin; . . . } This code is best described as an example of ____. Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch12 a. Inheritance. b. Aggregation. c. Polymorphism. d. Association. 32. Consider the following code snippet:

public class Purse { private Coin[] coins; . . . } Which of the following statements is correct? a. Purse aggregates Coin. b. Coin depends on Purse. c. The Coin class must be declared as an inner class within Purse. d. Coin inherits from Purse. 33. Aggregation denotes that ____. a. Objects of one class inherit from objects of its superclass. b. Objects of one class can be inherited by its subclasses. c. Objects of one class contain references to objects of its superclass. d. Objects of one class contain references to objects of another class. 34. A CashRegister class contains an array list of Coin objects. This is best described as an example of ____. a. Association b. Inheritance c. Cohesiveness d. Aggregation 35. A Quiz class contains an array of Question objects. This is best described as an example of ____. a. Aggregation b. Cohesiveness c. Association d. Inheritance 36. In a UML diagram, aggregation is denoted by ____. a. A solid line with a diamond-shaped symbol next to the aggregating class. b. An arrow with an open triangle pointing to the aggregating class. c. A dotted line with a diamond-shaped symbol next to the aggregating class. d. A dotted line with an open arrow tip pointing to the aggregating class. 37. In general, you need ____ when an object needs to remember another object between method calls. a. Inheritance Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch12 b. Aggregation c. Association d. An interface implementation 38. Which statement correctly describes the class relationship shown in this diagram? a. Quiz class depends on Question class b. Question class aggregates Quiz class c. Quiz class aggregates Question class. d. Question class inherits from Quiz class. 39. Which of the following code snippets denotes that the Kitchen class aggregates the Dish class? a. public class Kitchen extends Dish b. public class Dish extends Kitchen c. public class Kitchen {

private Dish dish; } d. public class Dish { private Kitchen myKitchen; }

40. ____ is often described as the is-a relationship. a. Inheritance b. Aggregation c. Polymorphism d. Dependency 41. Consider the following code snippet:

public class Motorcycle extends Vehicle { private Tire[] tires; . . . } This code is best described as an example of ____. a. Inheritance and multiplicities. b. Aggregation and dependency. c. Inheritance and aggregation. d. Inheritance and interface. 42. Consider the following code snippet:

public class Motorcycle extends Vehicle { . . . } Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch12 Which of the following statements correctly describes the relationship between the Motorcycle and Vehicle classes? a. Motorcycle exhibits the has-a relationship with regards to Vehicle. b. Motorcycle exhibits the is-a relationship with regard to Vehicle. c. Vehicle exhibits the has-a relationship with regards to Motorcycle. d. Vehicle exhibits the is-a relationship with regards to Motorcycle. 43. Consider the following code snippet:

public class Motorcycle extends Vehicle { private Tire[] tires; private Engine anEngine; . . . } Which of the following statements describing relationships between the Motorcycle, Tire, Engine and Vehicle classes is NOT correct? a. Motorcycle exhibits the has-a relationship with regards to Tire. b. Motorcycle exhibits the is-a relationship with regard to Vehicle. c. Vehicle exhibits the has-a relationship with regards to Motorcycle. d. Motorcycle exhibits the knows-about relationship with regards to Engine. 44. Consider the following code snippet:

public class PowerBoat extends Vessel { private Engine[] engines; . . . } This code is best described as an example of ____. a. Inheritance and multiplicities. b. Aggregation and association. c. Inheritance and aggregation. d. Association and multiplicities. 45. Consider the following code snippet:

public class SailBoat extends Vessel { private Engine[] engines; private Sail mainsail; . . . } Which of the following statements is NOT correct? Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch12 a. SailBoat inherits from Vessel. b. Sail depends on Sailboat. c. Sailboat aggregates Engine. d. SailBoat aggregates Sail. 46. Consider the following code snippet:

public class SailBoat extends Vessel { . . . } public class Catamaran extends SailBoat { . . . } Which of the following statements is NOT correct? a. SailBoat inherits from Vessel. b. Catamaran inherits from Vessel. c. Catamaran inherits from Sailboat. d. Catamaran depends on SailBoat. 47. Consider the following code snippet:

public class Manager extends Employee { private Project[] projects; private Address address; . . . } Which of the following statements is NOT correct? a. Manager inherits from Employee. b. Address aggregates Manager. c. Manager aggregates Address. d. Manager aggregates Project. 48. In a UML diagram, inheritance is denoted by ____. a. A solid line with a diamond-shaped symbol next to the superclass. b. A solid line with a closed arrow tip pointing to the superclass. c. A dotted line with an open arrow tip pointing to the superclass. d. A solid line with an open arrow tip pointing to the superclass. 49. Which of the followings statements about class relationships is correct? a. Inheritance represents the is-a relationship, while aggregation represents the has-a relationship. b. Inheritance represents the has-a relationship, while dependency represents the knows about relationship. c. Aggregation represents the is-a relationship, while inheritance represents the knows about relationship. d. Aggregation represents the has-a relationship, while dependence represents the is-a relationship. Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch12 50. Which of the following code snippets denotes that the Rose class inherits from the Flower class? a. public class Flower extends Rose b. public class Rose extends Flower c. public class Rose {

private Flower[] flowers; } d. public class Flower { private Rose[] limes; }

51. When designing classes, if you find classes with common behavior you should ____. a. Combine them all into a single class. b. Place some common behavior into a superclass. c. Place the common behavior into a subclass. d. Give them similar names. 52. In a UML diagram, an interface implementation is denoted by ____. a. A dotted line with a closed arrow tip. b. A solid line with a closed arrow tip. c. A dotted line with an open arrow tip. d. A solid line with an open arrow tip. 53. In a UML diagram, the relationship symbol shown below denotes ____. a. Inheritance b. Aggregation c. Dependency d. Interface implementation 54. In a UML diagram, the relationship symbol shown below denotes ____. a. Inheritance b. Aggregation c. Dependency d. Interface implementation 55. In a UML diagram, the relationship symbol shown below denotes ____. a. Inheritance b. Aggregation c. Dependency d. Interface implementation 56. Which statement correctly describes the class relationship shown in this diagram? a. Vehicle class depends on Car class b. Car class depends on Vehicle class Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch12 c. Vehicle class inherits from Car class. d. Car class inherits from Vehicle class. 57. Which statement correctly describes the class relationship shown in this diagram? a. Tire class aggregates Car class. b. Car class aggregates Tire class. c. Car class inherits from Tire class. d. Tire class inherits from Car class. 58. You have determined a need for a Book class and a Page class in your program. Which relationship is most appropriate between these classes? a. Inheritance b. Aggregation c. Dependency d. Interface implementation 59. You have determined a need for an Employee class and a TemporaryEmployee class in your program. Which relationship is most appropriate between these classes? a. Inheritance b. Aggregation c. Dependency d. Interface implementation 60. ____ relationships come from the collaboration columns on the CRC cards. a. Association b. Inheritance c. Dependency d. Attribute 61. When using CRC cards, UML diagrams should be created ___. a. Prior to discovering classes. b. After you have discovered classes and their relationships. c. During the implementation phase. d. To produce final documentation of the system. 62. Which of the following statements about class attributes is true? a. An attribute always corresponds to an instance variable of the class. b. An attribute is an externally observable property that objects of the class have. c. An attribute is used to represent aggregation with another class. d. Attributes cannot be represented in UML diagrams. 63. How does a UML diagram denote classes and their attributes and methods? a. A class rectangle contains the class name in the top, methods in the middle, and attributes in the bottom. b. A class rectangle contains the class name in the top, attributes in the middle, and methods in the bottom. Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch12 c. A class rectangle contains the methods in the top, class name in the middle, and attributes in the bottom. d. A class rectangle contains the attributes in the top, methods in the middle, and class name in the bottom. 64. How does a UML diagram denote a multiplicity of one or more in an aggregation relationship? a. * b. 1..* c. *..1 d. 1..n 65. Given the following diagram: a. A bank account may be owned by only one customer. b. A bank account may be owned by one or more customers. c. A customer may have only one bank account. d. A customer may have one or more bank accounts. 66. Which of the following statements about associations between classes is true? a. A class is associated with another class if both classes are in the same package. b. A class is associated with another class if the class inherits from the other class. c. A class is associated with another class if the other class inherits from this class. d. A class is associated with another class if you can navigate from objects of one class to objects of the other class. 67. You have determined the need for a File class and a Folder class in your program. Which of the following would best describe the relationship between these classes? a. Aggregation b. Association c. Composition d. Inheritance 68. Select a code segment to complete the Name class, so that it reflects a dependency relationship between Name and String.

public class Name ___________________________ a. extends String {

. . . } b. {

private String first; private String second; . . .

} c. implements String { . . . } Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch12 d. {

private ArrayList<Name> names; . . .

}

69. Select a code segment to complete the Team class, so that it reflects an aggregation relationship between Team and Player.

public class Team ___________________________ a. extends Player {

. . . } b. {

private Team aTeam; . . .

} c. implements Player { . . . } d. { private ArrayList<Player> players; . . . }

70. Select a code segment to complete the Player class, so that it reflects an inheritance relationship between Player and Person.

public class Player ___________________________ a. extends Person {

. . . } b. {

private PersonthePlayer; . . .

} c. implements Person { . . . } d. { private ArrayList<Person> players; . . . }

71. Select a code segment to complete the SmartPhone class, so that it reflects an interface implementation relationship between SmartPhone and MP3Player. Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch12

public class SmartPhone ___________________________ a. extends MP3Player {

. . . } b. {

private MP3Player musicPlayer; . . .

} c. implements MP3Player { . . . } d. implements interface MP3Player { . . . }

72. Which of the following statements is true about Coupling? a. Coupling between classes is high if there are no dependencies between classes b. Coupling between classes is high if there are few dependencies between classes c. Coupling between classes is low if there are no dependencies between classes d. Coupling between classes is low if there are few dependencies between classes 73. All smartphones are phones, but not all phones are smartphones. This type of relationship is best described by: a. Aggregation b. Dependency c. Inheritance d. Coupling 74. Every dolphin has a fin. Every dolphin is an animal. What kind of relationship would best describe the first and second statements? a. Dependency : Inheritance b. Coupling : Dependency c. Inheritance : Aggregation d. Aggregation : Inheritance 75. The textbook recommends a five-part program development process consisting of the following activities: I Use UML diagrams to record class relationships. II Gather requirements. III Implement the program. IV Use CRC cards to identify classes. V Use javadoc to document method behavior. Which is the correct order in which these activities should be completed? a. IV, II, I, III, V b. IV, II, I, V, III Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch12 c. II, IV, I, III, V d. II, IV, I, V, III 76. Before you begin designing a solution, you should ____. a. Document the methods that will be needed. b. Gather and document all requirements for the program in plain English. c. Determine the classes that will be needed. d. Create the UML diagrams to represent the classes. 77. You are designing a software solution for an automobile rental company. You have decided that the following nouns apply to the requirements: Auto, Customer, Address, Rental Contract, Mileage, Rental Date, Daily Rate, Total. Which of these should be represented as classes? a. All of them. b. Auto, Customer, Address, Rental Contract. c. Auto, Customer, Address, Rental Contract, Mileage. d. Auto, Customer, Address, Rental Contract, Mileage, Rental Date, Daily Rate. 78. You are designing a software solution for an automobile rental company. You have decided that the following nouns apply to the requirements: Auto, Customer, Address, Rental Contract, Mileage, Rental Date, Daily Rate, Total. Which of these should be represented as instance variables? a. Mileage b. Mileage, Daily Rate. c. Mileage, Rental Date, Daily Rate. d. Mileage, Rental Date, Daily Rate, Total. 79. You are designing a software solution for a veterinary clinic. The clinic provides various services for each pet on each visit. You have decided that the following nouns apply to the requirements: Customer, Address, Pet, Visit, Visit Date, Service Charge, Total Charge, Next Appointment. Which of these should be represented as classes? a. All of them. b. Customer, Address, Pet, Visit. c. Customer, Address, Pet, Visit, Service Charge. d. Customer, Address, Pet, Visit, Service Charge, Total Charge, Visit Date, Next Appointment. 80. You are designing a software solution for an automobile rental company. A customer may rent only a single auto at a given time. You have decided that the following classes are needed: Auto, Customer, Address, Rental Contract. Which of these should be represented as aggregation? a. Rental Contract class aggregates Address class b. Rental Contract class aggregates Customer and Address classes. c. Rental Contract class aggregates Customer, Address, and Auto classes. d. Rental Contract class does not aggregate any of the other classes. 81. You are designing a software solution for a veterinary clinic. The clinic provides various services for each pet on each visit. You have decided that the following classes are needed: Customer, Address, Pet, and Visit. Which of these should be represented as aggregation? a. Customer class aggregates Address, Pet, and Visit classes. b. Visit class aggregates Address class. Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch12 c. Pet class aggregates Address class. d. Pet class aggregates Customer class. 82. Given the following diagram showing class relationships: a. LineItem inherits from Invoice. b. LineItem aggregates Invoice. c. Invoice aggregates LineItem. d. Invoice inherits from LineItem. 83. Given the following diagram showing class relationships: a. Product inherits from Invoice. b. Product aggregates Invoice. c. Invoice inherits from Product. d. Invoice is dependent on Product. 84. Given the following diagram showing class relationships: a. Product inherits from LineItem. b. Product aggregates LineItem. c. LineItem aggregates Product. d. LineItem inherits from Product. 85. Given the following diagram showing class relationships: a. Address inherits from Invoice. b. Invoice aggregates Address. c. Address aggregates Invoice. d. Invoice inherits from Address. 86. The final step of the design phase recommended by the textbook is to ____. a. Write the documentation of the discovered classes and methods b. Write the code for each class and all of its methods. c. Identify the classes and methods that will be required. d. Create the UML diagrams to represent the classes. 87. When documenting discovered classes and methods during the design phase, you should ____. a. Create a Java source file for each class, write the method signatures, and use javadoc comments to describe the methods, but leave the method bodies blank. b. Create a Java source file for each class and write code to implement all of its methods, and use javadoc comments to document them. c. Create a Java source file for each class, use javadoc comments to document the methods that are to be added later, but do not write any code for the methods. d. Documentation of methods should not be done during the design phase. 88. Which of the following can be used to record the behavior of classes? a. Javadoc comments Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch12 b. Nouns and verbs in the problem description c. Polymorphism d. UML notation 89. During the implementation phase, which of the following statements is true? a. Aggregated classes will yield subclasses. b. Aggregated classes will yield instance variables. c. Aggregated classes will yield class packages. d. Aggregated classes will yield interfaces. 90. During the implementation phase, which of the following statements is true? a. Method parameter variables are available from the CRC cards. b. Method parameter variables are available from the javadocs created during the design phase. c. You must determine the method parameter variables during implementation phase. d. Method parameter variables are available from the UML diagrams. 91. During the implementation phase, which of the following statements is true? a. Class instance variables are available from the CRC cards. b. Class instance variables are available from the javadocs created during the design phase. c. You must determine the class instance variables during implementation phase. d. Class instance variables can be determined from the UML diagrams. 92. When using UML to create state diagrams, a state is denoted by ____. a. A rectangle with double border. b. A rectangle with rounded corners. c. An oval with double border. d. A standard rectangle with square corners. 93. When using UML to create state diagrams, state change is denoted by ____. a. Arrows with labels that connect rectangles. b. Double arrows with labels that connect rectangles. c. An oval between two rectangles, connected with arrows. d. Dividing the state rectangle into several parts, one for each state change. 94. Given the following diagram showing class relationships: a. Customer aggregates Bank, indicating that a customer may deal with many banks. b. Bank aggregates Customer, indicating that a bank may deal with many customers. c. Bank depends on Customer, indicating that a bank may deal with many customers. d. Customer depends on Bank, indicating that a customer may deal with many banks. 95. Given the following diagram showing class relationships: a. Customer aggregates BankAccount, indicating that a customer may have 2 bank accounts. b. BankAccount aggregates Customer, indicating that 2 customers may share a bank account. c. BankAccount depends on Customer, indicating that many customers may have 2 bank accounts. Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch12 d. Customer depends on BankAccount, indicating that a customer may have 2 bank accounts. 96. Suppose that the invoice-printing application from section 12.3 needs to be enhanced by including the computation and printing of sales taxes as needed. Since some vendors charge no sales taxes, the original Invoice class needs to be preserved. Select the code segment that best illustrates reuse of the existing Invoice class.

public class TaxableInvoice ___________________________ a. extends Invoice {

. . . } b. {

private Invoice originalInvoice; . . .

} c. implements Invoice { . . . } d. { private ArrayList<Invoice> invoices; . . . }

97. Regarding the invoice-printing application from section 12.3, it is decided that a Customer class is needed to store customer information, including the name, billing address, and a customer id number to be printed at the top of each invoice. Since the existing Address class already stores the customer’s name and physical address, the new Customer class can simply reuse Address. Select the code segment that best illustrates how the Customer class can reuse the existing Address class.

public class Customer ___________________________ a. extends Address {

private String idNumber; . . . } b. {

private Address information; private String idNumber; . . .

} c. implements Address { private String idNumber; . . . } d. { private Address information; private String name; Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch12 private String street; private String city; private String state; private String zip; private String idNumber; . . . }

98. Suppose that the invoice-printing application from section 12.3 needs to be enhanced by making it possible for class InvoicePrinter to store several invoices to be printed. Select the code segment that best illustrates reuse of the existing Invoice class for this purpose.

public class InvoicePrinter ___________________________ a. extends Invoice {

. . . } b. {

Invoice invoice1; Invoice invoice2; . . .

} c. implements Invoice { . . . } d. { ArrayList<Invoice> invoices; . . . }

99. Suppose you are developing a payroll application that computes and displays weekly paycheck amounts for various employees. As a result of the design phase, the partial Employee class below is developed. Select the method header that best completes the class, according to the method comments.

public class Employee { private int hoursWorked; /** Computes the weekly salary for this employee. @param hourlyRate the rate per hour earned by the employee @return the weekly salary */ _________________________________________ { // method body } } Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch12 a. public void computeSalary(double hourlyRate) b. public double computeSalary(double hourlyRate, int hoursWorked) c. public double computeSalary(double hourlyRate) d. public double computeSalary(int hoursWorked) 100. Suppose you are developing a payroll application that computes and displays weekly paycheck amounts for various employees. As a result of the design phase, an Employee class is developed. In addition, the Payroll class is designed to store and process information for various employees. Select the code segment that best completes the Payroll class.

public class Payroll ___________________________ a. extends Employee {

. . . } b. {

} c. {

} d. {

public static void main(String[] args) { Employee anEmployee; . . . }

int hoursWorked; double hourlyRate; . . .

ArrayList<Employee> employees; . . .

}

101. Suppose you are developing a payroll application that computes and displays weekly paycheck amounts for various employees. As a result of the design phase, the partial Employee class below is developed. Select the method header that best completes the class, according to the method comments.

public class Employee { private double hourlyRate; private int hoursWorked; /** Modifies the hourly rate for this employee. @param newHourlyRate the rate per hour earned by the employee */ _________________________________________ { // method body Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch12

} } a. public void changeRate(double newHourlyRate) b. public void changeRate(double newHourlyRate, int hoursWorked) c. public double changeRate(double newHourlyRate) d. public double changeRate(double newHourlyRate, int hoursWorked) 102. The United States has few legal protections against computer ____ ? a. Theft b. Privacy invasion c. Programmers d. Sales 103. How do databases affect companies? a. Lower cost of doing business b. Improve quality of service a company can offer c. Saves time d. All of the above. 104. What is not a component of a CRC Card? a. Collaborators b. Responsibilities c. Class d. UML Diagram

Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch12 Answer Key 1. b 2. c 3. a 4. c 5. b 6. d 7. a 8. a 9. c 10. c 11. c 12. b 13. b 14. a 15. d 16. c 17. c 18. d 19. c 20. c 21. d 22. d 23. a 24. d 25. c Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch12 26. c 27. b 28. d 29. b 30. a 31. b 32. a 33. d 34. d 35. a 36. a 37. b 38. c 39. c 40. a 41. c 42. b 43. c 44. c 45. b 46. d 47. b 48. b 49. a 50. b 51. b Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch12 52. a 53. b 54. d 55. a 56. d 57. b 58. b 59. a 60. c 61. b 62. b 63. b 64. b 65. d 66. d 67. c 68. b 69. d 70. a 71. c 72. d 73. c 74. d 75. d 76. b Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch12 77. b 78. c 79. b 80. c 81. a 82. c 83. d 84. c 85. b 86. a 87. a 88. a 89. b 90. b 91. d 92. b 93. a 94. b 95. a 96. a 97. b 98. d 99. c 100. d 101. a 102. b Powered by Cognero

Page 25


Name:

Class:

Date:

testbank-bj-7-ch12 103. d 104. d

Powered by Cognero

Page 26


Name:

Class:

Date:

testbank-bj-7-ch13

Indicate the answer choice that best completes the statement or answers the question. 1. What is required to make a recursive method successful? I special cases that handle the simplest computations directly II a recursive call to simplify the computation III a mutual recursion a. I, II, and III b. II only c. I only d. I and II only 2. Consider the getArea method from the textbook shown below.

public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Where is/are the recursive call(s)? a. lines #1 and #2 b. line #4 c. line #1 d. line #2 3. Consider the getArea method from the textbook shown below.

public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Where is/are the terminating condition(s)? a. line #2 Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch13 b. line #4 c. line #1 d. lines #1 and #2 4. Consider the getArea method from the textbook shown below:

public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Assume the code in line #3 is changed to:

Triangle smallerTriangle = new Triangle(width); This change would cause infinite recursion for which triangles? a. Those with width equal to 0. b. Triangles of any width. c. Those with width equal to 1. d. Those with width greater than or equal to 2. 5. Consider the getArea method from the book shown below.

public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Assume lines #1 and #2 were replaced with this:

if (width == 1) { return 1; } // replacement for lines #1 and #2 What will happen when this code is executed? a. Nothing - the method would still be correct. Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch13 b. We would lose our only recursive case. c. A positive width would reduce the correct area by 1. d. A negative or zero width would cause problems. 6. Consider the getArea method from the textbook shown below.

public int getArea() { if (width <= 0) { return 0; } // line #1 else if (width == 1) { return 1; } // line #2 else { Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } } Assume line #1 is replaced with this line:

if (width <= 0) {return width;} What will be the result? a. The method will return incorrect results for triangles with width equal to 0. b. The method will return incorrect results for triangles with width equal to 1. c. The method will return area to be one too high for all triangles. d. The method will still return correct results for all non-negative width triangles. 7. Consider the following code snippet for recursive addition:

int add(int i, int j) { // assumes i >= 0 if (i == 0) { return j; } else { return add(i - 1, j + 1); } } Identify the terminating condition in this recursive method. a. there is no terminating condition b. i == 0 c. return j Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch13 d. return add(i - 1, j + 1) 8. Consider the following code snippet for calculating Fibonacci numbers recursively:

int fib(int n) { // assumes n >= 0 if (n <= 1) { return n; } else { return (fib(n - 1) + fib(n - 2)); } } Identify the terminating condition in this recursive method. a. n < 1 b. n <= 1 c. fib(n - 1) d. fib(n - 1) + fib(n - 1) 9. Consider the following recursive code snippet:

public static int mystery(int n, int m) { if (n <= 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } Identify the terminating condition(s) of method mystery? a. n <= 0 b. n > 0 c. n == 1 d. n <= 0 or n == 1 10. Consider the following recursive code snippet:

public int mystery(int n, int m) { Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch13

if (n == 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } What value is returned from a call to mystery(1,5)? a. 1 b. 11 c. 5 d. 6 11. Consider the following recursive code snippet:

public int mystery(int n, int m) { if (n == 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } What value is returned from a call to mystery(3,6)? a. 18 b. 3 c. 6 d. 729 12. Consider the recursive method myPrint:

public void myPrint(int n) { if (n < 10) { System.out.print(n); } Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch13

else { int m = n % 10; System.out.print(m); myPrint(n / 10); } } What is printed for the call myPrint(8)? a. 4 b. 21 c. 10 d. 8 13. Consider the recursive method myPrint in this code snippet:

public void myPrint(int n) { if (n < 10) { System.out.print(n); } else { int m = n % 10; System.out.print(m); myPrint(n / 10); } } What is printed for the call myPrint(821)? a. 821 b. 12 c. 10 d. 128 14. Consider the recursive method myPrint shown in this code snippet:

public void myPrint(int n) { if (n < 10) { System.out.print(n); } else { int m = n % 10; Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch13

System.out.print(m); myPrint(n / 10); } } What does this method do? a. Prints a positive int value forward, digit by digit. b. Divides the int by 10 and prints out the result. c. Divides the int by 10 and prints out its last digit. d. Prints a positive int value backward, digit by digit. 15. Complete the code for the recursive method printSum shown in this code snippet, which is intended to return the sum of digits from 1 to n:

public static int printSum(int n) { if (n == 0) { return 0; } else { ______________________________ } } a. return (n + printSum(n - 1)); b. return (n - printSum(n - 1)); c. return (n + printSum(n + 1)); d. return (printSum(n - 1)); 16. Consider the code for the recursive method mystery shown in this code snippet:

public static int mystery(int n) { if (n == 0) { return 0; } else { return (n + mystery(n-1)); } } What will be printed by the statement System.out.println(mystery(-4));? a. Nothing - a StackoverflowError exception will occur Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch13 b. 0 c. -22 d. -10 17. Consider the code for the recursive method riddle shown in this code snippet:

public static int riddle(int n) { if (n == 0) { return 0; { else { return (n + riddle(n - 1)); } } To avoid infinite recursion, which of the following lines of code should replace the current terminating case? a. if (n <= 0) b. if (n == -1) c. if (n >= 0) d. The terminating case as shown will avoid infinite recursion. 18. Insert the missing code in the following code fragment. This fragment is intended to recursively compute xn, where x and n are both non-negative integers:

public int power(int x, int n) { if (n == 0) { ____________________ } else { return x * power(x, n - 1); } } a. return power(x, n - 1); b. return x; c. return 1; d. return x * power(x, n - 1); 19. If recursion does not have a special terminating case, what error will occur? a. Illegal argument b. Out of memory Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch13 c. Stack overflow d. Index out of range 20. A recursive method without a special terminating case would _________ a. be more efficient. b. never terminate. c. end immediately. d. not be recursive. 21. Consider the following recursive code snippet:

public int mystery(int n, int m) { if (n == 0) { return 0; } if (n == 1) { return m; } return m + mystery(n - 1, m); } What parameter values for n would cause an infinite recursion problem in the following method? a. all n with n < 0 b. n == 0 c. all n with n >= 0 d. n == 1 22. ____ recursion can occur when a recursive algorithm does not contain a special case to handle the simplest computations directly. a. Non-mutual b. Terminating condition c. Mutual d. Infinite 23. If a recursive method does not simplify the computation within the method and the base case is not called, what will be the result? a. The recursion calculation will occur correctly regardless. b. Infinite recursion will occur. c. This cannot be determined. d. The terminating condition will be executed and recursion will end. 24. When a recursive method is called correctly, and it does not perform recursion, what must be true? a. Both a terminating condition and a recursive case condition were true. Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch13 b. A terminating condition was true. c. All recursive case conditions were true. d. One recursive case condition was true. 25. Consider the getArea method from the textbook shown below:

public int getArea() { if (width <= 0) { return 0; } // line #1 if (width == 1) { return 1; } // line #2 Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } Assume that line #3 is changed to this:

Triangle smallerTriangle = new Triangle(width); This would cause infinite recursion for ____. a. triangles with width equal to 1 b. triangles with width equal to 0 c. triangles with width greater than or equal to 2 d. triangles of any width 26. Consider the getArea method from the textbook shown below:

public int getArea() { if (width <= 0) { return 0; } // line #1 if (width == 1) { return 1; } // line #2 Triangle smallerTriangle = new Triangle(width - 1); // line #3 int smallerArea = smallerTriangle.getArea(); // line #4 return smallerArea + width; // line #5 } If line #1 was eliminated from the method, what would be the result when calling getArea? a. A positive width would reduce the correct area by 1. b. We would lose our only recursive case. c. Nothing - the method would still work correctly. d. A negative or zero width would cause problems. 27. How many recursive calls to the fib method shown below would be made from an original call to fib(4)? (Do not count the original call)

public int fib(int n) { // assumes n >= 0 Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch13

if (n <= 1) { return n } else { return (fib(n - 1) + fib(n - 2)); } } a. 8 b. 4 c. 1 d. 2 28. Would switching the special case order affect the return value of the following method?

public int mystery(int n, int m) { if (n == 0) // special case #1 { return 0; } if (n == 1) // special case #2 { return m; } return m + mystery(n - 1, m); } a. An exception will be thrown. b. Yes c. No d. It is impossible to tell. 29. Which of the following options could be used as a terminating condition for a recursive method that finds the middle character of a String with any number of characters? I the length of the String is 1 II first and last String characters match III the String is not empty a. I only b. I and III only c. I, II and III d. II only 30. Consider the problem of arranging matchsticks so as to form a row of squares, as shown below for three squares and ten matchsticks. Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch13

|

|

-

| -

| -

Complete the recursive method below, which is designed to return the number of matchsticks needed to form n squares.

public static int matchsticks(int squares) { if (squares == 1) // 1 square can be formed with 4 matchsticks { return 4; } else { return ___________________________ } } a. 4 * squares; b. 3 + matchsticks(squares - 1); c. 4 + matchsticks(squares - 1); d. matchsticks(squares + 4); 31. Consider the method below, which implements the exponentiation operation recursively. Select the statement that should be used to complete the method so that it handles the special case correctly.

public static double power(int base, int exponent) { if (exponent == 0) { _______________ } else { return base * power(base, exponent - 1); } } a. return 0; b. return 1 * power(base, exponent - 1); c. return base; d. return 1; 32. Consider the method below, which displays the characters from a String in reverse order. Each character appears on a separate line. Select the statement that should be used to complete the method so that it performs a recursive method call correctly. Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch13

public static void printReverse(String word) { if (word.length() > 0) { ___________________________ System.out.println(word.charAt(0)); } } a. printReverse(word.length() - 1); b. printReverse(word.substring(1)); c. printReverse(word); d. printReverse(new String(word.charAt(1))); 33. Consider the method below, which prints the digits of an arbitrary positive integer in reverse order, one digit per line. The method should print the last digit first. Then, it should recursively print the integer obtained by removing the last digit. Select the statements that should be used to complete the method.

public static void printReverse(int value) { if (value > 0) { _____________________ // print last digit _____________________ // recursive call to print value without last digit } } a. System.out.println(value / 10); printReverse(value / 10); b. System.out.println(value / 10); printReverse(value % 10); c. System.out.println(value % 10); printReverse(value / 10); d. System.out.println(value % 10); printReverse(value % 10);

34. Consider the method powerOfTwo shown below:

public boolean powerOfTwo(int n) { if (n == 1) // line #1 { return true; } else if (n % 2 == 1) // line #2 { Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch13

return false; } else { return powerOfTwo(n / 2); }

// line #3

} What is the best interpretation of line #1? a. 1 is an invalid choice for n b. Any multiple of one is a power of two c. One is not a power of two d. One is a power of two 35. Consider the method powerOfTwo shown below:

public boolean powerOfTwo(int n) { if (n == 1) // line #1 { return true; } else if (n % 2 == 1) // line #2 { return false; } else { return powerOfTwo(n / 2); // line #3 } } How many recursive calls are made from the original call powerOfTwo(63) (not including the original call)? a. 1 b. 6 c. 0 d. 4 36. Consider the method powerOfTwo shown below:

public boolean powerOfTwo(int n) { if (n == 1) // line #1 { return true; } else if (n % 2 == 1) // line #2 Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch13

{ return false; } else { return powerOfTwo(n / 2); }

// line #3

} How many recursive calls are made from the original call of powerOfTwo(64) (not including the original call)? a. 6 b. 4 c. 8 d. 2 37. Complete the code for the myFactorial recursive method shown below, which is intended to compute the factorial of the value passed to the method:

public int myFactorial(int anInteger) { if (anInteger == 1) { return 1; } else { ______________________ } } a. return (anInteger * (myFactorial(anInteger - 1))); b. return (anInteger * (myFactorial(anInteger))); c. return ((anInteger - 1) * (myFactorial(anInteger))); d. return ((anInteger - 1)*(myFactorial(anInteger - 1))); 38. Complete the code for the myFactorial recursive method shown below, which is intended to compute the factorial of the value passed to the method:

public int myFactorial(int anInteger) { _____________________________ { return 1; } else { return(anInteger * myFactorial(anInteger - 1)); Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch13

} } a. if (anInteger * (anInteger - 1) == 1) b. if (anInteger == 1) c. if (myFactorial(anInteger) == 1) d. if ((anInteger - 1) == 1) 39. Complete the code for the myFactorial recursive method shown below, which is intended to compute the factorial of the value passed to the method:

public int myFactorial(int anInteger) { if (anInteger == 1) { ______________________ } else { return (anInteger * myFactorial(anInteger - 1)); } } a. return 0; b. return myFactorial(anInteger); c. return 1; d. return -anInteger; 40. Complete the code for the recursive method shown below, which is intended to compute the sum of the first n positive integers:

public int s(int n) { if (n == 1) { return 1; } else { _________________ } } a. return n + s(n - 1); b. return s(n) + n - 1; c. return n + (n - 1); d. return n + s(n + 1); Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch13 41. Complete the code for the calcPower recursive method shown below, which is intended to raise the base number passed into the method to the exponent power passed into the method:

public static int calcPower(int baseNum, int exponent) { int answer = 0; ________________________ { answer = 1; } else { answer = baseNum * calcPower (baseNum, exponent - 1); } return answer; } a. if (exponent == -1) b. if (exponent == 1) c. if (exponent != 1) d. if (exponent == 0) 42. Complete the code for the calcPower recursive method shown below, which is intended to raise the base number passed into the method to the exponent power passed into the method:

public static int calcPower(int baseNum, int exponent) { int answer = 0; if (exponent == 0) { _____________________ } else { answer = baseNum * calcPower (baseNum, exponent - 1); } return answer; } a. answer = 0; b. answer = 1; c. answer = calcPower(1); d. answer = -1; 43. Complete the code for the calcPower recursive method shown below, which is intended to raise the base number passed into the method to the exponent power passed into the method: Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch13

public static int calcPower(int baseNum, int exponent) { int answer = 0; if (exponent == 0) { answer = 1; } else { _______________________________________ } return answer; } a. answer = baseNum * calcPower (baseNum -1, exponent - 1); b. answer = baseNum * calcPower (baseNum, exponent); c. answer = baseNum * calcPower (baseNum -1, exponent); d. answer = baseNum * calcPower (baseNum, exponent - 1); 44. Given the following class code:

public class RecurseSample { public static void main(String[] args) { recurse(3); } public static int recurse(int n) { int total = 0; if (n == 0) { return 0; } else { total = 3 + recurse(n - 1); } System.out.println(total); return total; } } What values will be printed? a. 1, 3, and 6 Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch13 b. 3, 6, 9, and 12 c. 1, 3, 6, and 9 d. 3, 6, and 9 45. Given the following class code:

public class RecurseSample { public static void main(String[] args) { System.out.println(recurse(3)); } public static int recurse(int n) { int total = 0; if (n == 0) { return 0; } else { total = 3 + recurse(n - 1); } return total; } } What values will be printed when this code is executed? a. 3, 6, and 9 b. 6 c. 1, 3, 6, and 9 d. 9 46. Given the following class code:

public class RecurseMore { public static void main(String[] args) { recurse(4); } public static int recurse(int n) { int total = 0; if (n == 0) { Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch13

return 0; } else { total = 4 + recurse(n - 2); } System.out.println(total); return total; } } What values will be printed when this code is executed? a. 4 b. 8 c. 0, 4, and 8 d. 4 and 8 47. Given the following code snippet:

public static int newCalc(int n) { if (n < 0) { return -1; } else if (n < 10) { return n; } else { return (n % 10) + newCalc(n / 10); } } What value will be returned when this code is executed with a call to newCalc(15)? a. 2 b. 6.5 c. 2.5 d. 6 48. Given the following code snippet:

public static int newCalc(int n) { if (n < 0) { Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch13

return -1; } else if (n < 10) { return n; } else { return (n % 10) + newCalc(n / 10); } } What value will be returned when this code is executed with a call to newCalc(5)? a. 2.5 b. 5.5 c. 5 d. 2 49. Given the following code snippet:

public static int newCalc(int n) { if (n < 0) { return -1; } else if (n < 10) { return n; } else { return (1 + newCalc(n / 10)); } } What value will be returned when this code is executed with a call to newCalc(5)? a. 5 b. 1.5 c. 5.5 d. 1 50. Given the following code snippet:

public static int newCalc(int n) { if (n < 0) Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch13

{ return -1; } else if (n < 10) { return n; } else { return (1 + newCalc(n / 10)); } } What value will be returned when this code is executed with a call to newCalc(15)? a. 2.5 b. 5 c. 5.5 d. 2 51. Given the following class code:

public class RecurseMore { private static int total; public static void main(String[] args) { System.out.println(recurse(4)); } public static int recurse(int n) { int total = 0; if (n == 0) { return 0; } else { total = 4 + recurse(n - 2); } return total; } } What values will be printed when this code is executed? a. 8 b. 4 Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch13 c. 4 and 8 d. 0, 4, and 8 52. Complete the following code snippet, which is intended to be a recursive method that will find the smallest value in an array of double values from index to the end of the array:

public static double minVal(double[] elements, int index) { if (index == elements.length - 1) { return elements[index]; } double val = __________________; if (elements[index] < val) { return elements[index]; } else { return val; } } a. minVal(elements, index - 1) b. minVal(index - 1) c. minVal(elements, index + 1) d. minVal(index + 1) 53. Complete the following code snippet, which is intended to be a recursive method that will find the smallest value in an array of double values from index to the end of the array:

public static double minVal(double[] elements, int index) { if (index == elements.length - 1) { __________________ } double val = minVal(elements, index + 1); if (elements[index] < val) { return elements[index]; } else { return val; } Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch13

} a. return elements[index]; b. return 0; c. return 1; d. return elements[0]; 54. Complete the following code snippet, which is intended to be a recursive method that will find the sum of all elements in an array of double values from the beginning of the array to index:

// return the sum of all elements in arr[] public static double findSum(double arr[], int index) { if (index == 0) { return arr[index]; } else { _____________________ } } Assume that this method would be called using an existing array named myArray as follows:

findSum(myArray, myArray.length - 1); a. return (arr[index] + findSum(arr, index + 1)); b. return (findSum(arr, index - 1)); c. return (findSum(arr, index + 1)); d. return (arr[index] + findSum(arr, index - 1)); 55. Complete the following code snippet, which is intended to be a recursive method that will find the sum of all elements in an array of double values from the beginning of the array to index:

// return the sum of all elements in arr[] public static double findSum(double arr[], int index) { if (index == 0) { _____________________ } else { return (arr[index] + findSum(arr, index - 1)); } } Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch13 Assume that this method would be called using an existing array named myArray as follows:

findSum(myArray,myArray.length - 1); a. return arr[index + 1]; b. return arr[1]; c. return arr[index - 1]; d. return arr[index]; 56. Complete the following code snippet, which is intended to be a recursive method that reverses a String value:

public static String reverseIt(String s) { if (s.length() <= 1) { _________ } else { return reverseIt(s.substring(1)) + s.charAt(0); } } a. return s.charAt(0); b. return 0; c. return s.substring(1); d. return s; 57. Complete the following code snippet, which is intended to be a recursive method that reverses a String value:

public static String reverseIt(String s) { if (s.length() <= 1) { return s; } else { ________________________ } } a. return reverseIt(s.substring(0)) + s.charAt(1); b. return reverseIt(s.substring(1)) + s.charAt(1); c. return reverseIt(s.substring(0)) + s.charAt(0); d. return reverseIt(s.substring(1)) + s.charAt(0); Powered by Cognero

Page 25


Name:

Class:

Date:

testbank-bj-7-ch13 58. Consider the code for the recursive method printSum shown in this code snippet, which is intended to return the sum of digits from 1 to n:

public static int printSum(int n) { if (n <= 0) // line #1 { return 0; // line #2 } else { return (n + printSum(n)); //line #3 } } Which of the following statements is correct? a. line #3 is incorrect, and should be changed to return (n + printSum(n + 1)); b. line #1 is incorrect, and should be changed to if (n <= 1) c. line #3 is incorrect, and should be changed to return (n + printSum(n - 1)); d. line #3 is incorrect, and should be changed to return (printSum(n - 1)); 59. The method below generates all nonempty substrings of a word passed as argument. Assuming that the string contains no duplicate characters, select the statement to complete the method so that it prints all nonempty substrings correctly.

public static void printSubstrings(String word) { if (word.length() > 0) { for (int j = 1; j <= word.length(); j++) // print substrings that begin with the first character { System.out.println(word.substring(0, j)); } _________________________________ // print substrings without the first character } } a. printSubstrings(word.substring(0)); b. printSubstrings(word.substring(1)); c. printSubstrings(word.substring(word.length())); d. printSubstrings(word.substring(word.length() - 1)); 60. Which of the following is NOT true about debugging a recursive method by setting a breakpoint on the line containing Powered by Cognero

Page 26


Name:

Class:

Date:

testbank-bj-7-ch13 a return statement? a. You cannot debug a recursive method with the debugger. b. The debugger's call stack will show all the calls to the recursive method that are pending. c. You can select a pending call and then inspect the value of its variables. d. The last call on the stack represents the first recursive call to reach the return statement. 61. Consider the code for the myFactorial recursive method shown below, which is intended to compute the factorial of the value passed to the method:

public int myFactorial(int anInteger) { if (anInteger == 1) // line #1 { return 1; // line #2 } else { return (anInteger * myFactorial(anInteger - 1)); // line #3 } } If you set a breakpoint on line #2 and then call myFactorial(4), how many calls to myFactorial will be visible on the debugger's call stack when the program suspends for the breakpoint? a. 0 because the answer was returned b. 3 c. 4 d. 1 62. A palindrome is a word or phrase that reads the same forward or backward. Consider the methods palindrome and isPal shown below:

public boolean palindrome(String string) { return isPal(string, 0, string.length() - 1); } private boolean isPal(String string, int left, int right) { if (left >= right) { return true; } else if (string.charAt(left) == string.charAt(right)) { return isPal(string, left + 1, right - 1); } else Powered by Cognero

Page 27


Name:

Class:

Date:

testbank-bj-7-ch13

{ return false; } } The method isPal as shown here would be considered to be a ____ method. a. terminating b. static c. recursive helper d. public 63. A palindrome is a word or phrase that reads the same forward or backward. Consider the following code snippet:

public boolean palindrome(String string) { return isPal(string, 0, string.length() - 1); } private boolean isPal(String string, int left, int right) { if (left >= right) { return true; } else if (string.charAt(left) == string.charAt(right)) { return isPal(string, left + 1, right - 1); } else { return false; } } What is the purpose of the palindrome method? a. Recursively call itself. b. Provide the string, along with its first and last indexes to the recursive isPal method. c. Send the recursive isPal method its terminating condition. d. Return the palindrome to the calling method. 64. A palindrome is a word or phrase spelled which reads the same forward or backward. Consider the following code snippet:

public boolean palindrome(String string) { return isPal(string, 0, string.length() - 1); } Powered by Cognero

Page 28


Name:

Class:

Date:

testbank-bj-7-ch13

private boolean isPal(String string, int left, int right) { if (left >= right) { return true; } else if (string.charAt(left) == string.charAt(right)) { return isPal(string, left + 1, right - 1); } else { return false; } } What does the method palindrome return? a. false b. a palindrome not found exception c. the Boolean value returned from the isPal method d. true 65. A palindrome is a word or phrase that reads the same forward or backward. Consider the following code snippet:

public boolean palindrome(String string) { return isPal(string, 0, string.length() - 1); } private boolean isPal(String string, int left, int right) { if (left >= right) { return true; } else if (string.charAt(left) == string.charAt(right)) { return isPal(string, left + 1, right - 1); } else { return false; } } What does the condition left >= right refer to? a. You have reached the middle of the string. Powered by Cognero

Page 29


Name:

Class:

Date:

testbank-bj-7-ch13 b. It cannot be determined if the string is a palindrome. c. An empty or one-character string is considered a palindrome. d. The string is not a palindrome. 66. Consider the square method shown below that takes a non-negative int argument. Complete the code for the square method so that it correctly calls the squareHelper method to produce the square of n.

public int square(int n) { ____________________; } public int squareHelper(int c, int n) { if (c == 1) { return n; } else { return n + squareHelper(c - 1, n); } } a. return squareHelper(n - 1, n) b. return squareHelper(n, n - 1) c. return square(n) d. return squareHelper(n, n) 67. Consider the square method shown below that takes a non-negative int argument:

public int square(int n) { return squareHelper(n, n); } public int squareHelper(int c, int n) { if (c == 1) { return n; } else { return n + squareHelper(c - 1, n); } Powered by Cognero

Page 30


Name:

Class:

Date:

testbank-bj-7-ch13

} Assume that the last return statement in the squareHelper method is changed to this:

return squareHelper(c - 1, n); What would a call to square(7) return? a. 7 b. 14 c. 13 d. 49 68. Consider the square method shown below that takes a non-negative int argument.

public int square(int n) { return squareHelper(n, n); } public int squareHelper(int c, int n) { if (c == 1) { return n; } else { return n + squareHelper(c - 1, n); } } Assume that the last return statement in the squareHelper method is changed to this:

return n * squareHelper(c - 1, n); What would a call to square(4) return? a. 256 b. 4 c. 16 d. 64 69. Consider the helper method reversePrint, which uses recursion to display in reverse the elements in a section of an array limited by the firstIndex and lastIndex arguments. What statement should be used to complete the recursive method?

public static void reversePrint(int[] array, int firstIndex, int lastIndex) { Powered by Cognero

Page 31


Name:

Class:

Date:

testbank-bj-7-ch13

if (firstIndex < lastIndex) { ________________________________________ } System.out.println(array[firstIndex]); } public static void main(String[] args) { int [] numbers = { 4, 7, 1, 0, 2, 7 }; reversePrint(numbers, 0, numbers.length - 1); } a. reversePrint(array, firstIndex, lastIndex - 1); b. reversePrint(array, firstIndex + 1, lastIndex); c. reversePrint(array, firstIndex + 1, lastIndex - 1); d. reversePrint(array, firstIndex, lastIndex + 1); 70. Consider the helper method reversePrint, which uses recursion to display in reverse the elements in a section of an array limited by the firstIndex and lastIndex arguments. What statement should be used to complete the recursive method?

public static void reversePrint(int[] array, int firstIndex, int lastIndex) { if (firstIndex < lastIndex) { reversePrint(array, firstIndex + 1, lastIndex); } System.out.println(_________________); } public static void main(String[] args) { int [] numbers = { 4, 7, 1, 0, 2, 7 }; reversePrint(numbers, 0, numbers.length - 1); } a. array[firstIndex] b. array[firstIndex+1] c. array[lastIndex-1] d. array[lastIndex] 71. Assume that recursive method search returns true if argument value is one of the elements in the section of the array limited by the firstIndex and lastIndex arguments. What statement can be used in main to determine if the Powered by Cognero

Page 32


Name:

Class:

Date:

testbank-bj-7-ch13 value 7 is one of the elements in array values?

public static boolean search(int value, int[] array, int firstIndex, int lastIndex) { if (firstIndex <= lastIndex) { if (array[firstIndex] == value) { return true; } else { return search(value, array, firstIndex + 1, lastIndex); } } return false; } public static void main(String[] args) { int [] values = { 4, 7, 1, 0, 2, 7 }; if (_________________________________ ) { System.out.println("7 is in the array"); } } a. search(7, values, 1, values.length) b. search(7, values, 1, values.length - 1) c. search(7, values, 0, values.length) d. search(7, values, 0, values.length - 1) 72. Consider the problem of displaying a pattern of asterisks that form a triangle of height h, as shown below for h = 4:

* ** *** **** *** ** * The problem can be solved with the recursive helper method shape below. The method takes two parameters: low and high. It first prints a row of asterisks corresponding to parameter low. If high is higher than low, it recursively generates a shape in which low is incremented by one, and then prints another row of low asterisks. Select a statement to complete method triangle, so that the helper method shape is invoked with the correct arguments in order to display Powered by Cognero

Page 33


Name:

Class:

Date:

testbank-bj-7-ch13 a triangle with parameter height.

public static void shape(int low, int high) { if (high >= low) { asterisksRow(low); if (high > low) { shape(low + 1, high); asterisksRow(low); } } } public static void asterisksRow(int n) stars { for (int j = 1; j < n; ++j) { System.out.print("*"); }

// Method to display a row of n

System.out.println("*"); } public static void triangle(int height) { if (height > 1) { _______________________ } } a. shape(0, height - 1); b. shape(0, height - 1); c. shape(1, height); d. shape(0, height); 73. Why does the best recursive method usually run slightly slower than its iterative counterpart? a. Each recursive method call takes processor time. b. Multiple recursive cases must be considered. c. Checking multiple terminating conditions take more processor time. d. Testing the terminating condition takes longer. 74. Consider the fib method from the textbook shown below: Powered by Cognero

Page 34


Name:

Class:

Date:

testbank-bj-7-ch13

public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } Computing the 7th fibonacci number, fib(7), recursively computes fib(6), fib(5), and fib(4) ___ times respectively. a. 6, 5, and 4 b. 3, 2, and 1 c. 1, 2, and 3 d. 4, 5, and 6 75. Consider the fib method from the textbook shown below.

public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } Calling fib(3) will trigger ___ recursive call(s) and execute the terminating condition ___ time(s), respectively. a. 1, 1 b. 1, 2 c. 2, 2 d. 2, 1 76. Consider the recursive version of the fib method from the textbook shown below:

public static long fib(int n) { if (n <= 2) { return 1; Powered by Cognero

Page 35


Name:

Class:

Date:

testbank-bj-7-ch13

} else { return fib(n - 1) + fib(n - 2); } } How many recursive calls to fib(2) will be made from the original call of fib(6)? a. 4 b. 3 c. 5 d. 2 77. Consider the recursive version of the fib method from the textbook shown below:

public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } How many total recursive calls (not counting the original call) to fib will be made from the original call of fib(6)? a. 14 b. 12 c. 6 d. 20 78. Consider the recursive version of the fib method from the textbook shown below:

public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } Powered by Cognero

Page 36


Name:

Class:

Date:

testbank-bj-7-ch13 How many total recursive calls (not counting the original call) to fib will be made from the original call of fib(7)? a. 12 b. 32 c. 24 d. 30 79. Consider the recursive version of the fib method from the textbook shown below:

public static long fib(int n) { if (n <= 2) { return 1; } else { return fib(n - 1) + fib(n - 2); } } How many more recursive calls to fib will be made from the original call of fib(7) than from the original call of fib(6) (not counting the original calls)? a. 2 b. 10 c. 5 d. 1 80. The method below implements the exponentiation operation recursively by taking advantage of the fact that, if the exponent n is even, then xn = (x n/2)2. Select the expression that should be used to complete the method so that it computes the result correctly.

public static double power(double base, int exponent) { if (exponent % 2 != 0) // if exponent is odd { return base * power(base, exponent - 1); } else if (exponent > 0) { double temp = ________________________ ; return temp * temp; } return base; } a. power(base, exponent / 2) * power(base, exponent / 2) b. power(base, exponent) / 2 Powered by Cognero

Page 37


Name:

Class:

Date:

testbank-bj-7-ch13 c. power(base, exponent / 2) d. power(base, exponent / 2) + power(base, exponent / 2) 81. Consider the iterative version of the fib method from the textbook shown below:

public static long fib(int n) { if (n <= 2) { return 1; } long fold = 1; long fold2 = 1; long fnew = 1; for (int i = 3; i <= n; i++) { fnew = fold + fold2; fold2 = fold; fold = fnew; } return fnew; } How many iterations of the for loop will there be for the call fib(6)? a. 3 b. 5 c. 6 d. 4 82. Which statement(s) about recursion are true? I Recursion is faster than iteration. II Recursion is often easier to understand than iteration. III Recursive design has an economy of thought. a. I only b. II only c. II and III only d. I and III only 83. In recursion, the recursive call is analogous to a loop ____. a. termination b. iteration c. call d. return 84. In recursion, the non-recursive case is analogous to a loop ____. a. termination Powered by Cognero

Page 38


Name:

Class:

Date:

testbank-bj-7-ch13 b. call c. iteration d. condition 85. A termination condition in a loop is analogous to _____________ in a recursive method. a. iteration b. a special case c. an initialization condition d. a recursive call 86. Which of the following statements about recursion is correct? a. In many cases, a recursive solution may be easier to understand and to implement than an iterative solution. b. It is not necessary to have a special terminating case in all recursions. c. A recursive solution will always run faster than an equivalent iterative solution. d. It is not necessary to simplify the argument in the recursive call. 87. Consider the permutations method from the textbook, which is intended to return all permutations of the word passed in as a parameter. Which line contains the terminating condition in the permutations recursive method?

public static ArrayList<String> permutations(String word) { ArrayList<String> result = new ArrayList<String>(); if (word.length() == 0) // line #1 { result.add(word); // line #2 return result; // line #3 } else { for (int i = 0; i < word.length(); i++) // line #4 { String shorter = word.substring(0, i) + word(substring(i + 1); // line #5 ArrayList<String> shorterPermutations = permutations(shorter); // line #6 for (String s : shorterPermutations) // line #7 { result.add(word.charAt(i) + s); // line #8 } } return result; // line #9 } } a. line #1 b. line #9 Powered by Cognero

Page 39


Name:

Class:

Date:

testbank-bj-7-ch13 c. line #6 d. line #8 88. Consider the permutations method from the textbook, which is intended to return all permutations of the word passed in as a parameter. Which line contains the recursive call in the permutations method?

public static ArrayList<String> permutations(String word) { ArrayList<String> result = new ArrayList<String>(); if (word.length() == 0) // line #1 { result.add(word); // line #2 return result; // line #3 } else { for (int i = 0; i < word.length(); i++) // line #4 { String shorter = word.substring(0, i) + word(substring(i + 1); // line #5 ArrayList<String> shorterPermutations = permutations(shorter); // line #6 for (String s : shorterPermutations) // line #7 { result.add(word.charAt(i) + s); // line #8 } } return result; // line #9 } } a. line #7 b. line #8 c. line #5 d. line #6 89. Consider the permutations method from the textbook, which is intended to return all permutations of the word passed in as a parameter. What special cases for the simplest values are used by the permutations method to terminate the recursion?

public static ArrayList<String> permutations(String word) { ArrayList<String> result = new ArrayList<String>(); if (word.length() == 0) // line #1 { result.add(word); // line #2 return result; // line #3 } Powered by Cognero

Page 40


Name:

Class:

Date:

testbank-bj-7-ch13

else { for (int i = 0; i < word.length(); i++) // line #4 { String shorter = word.substring(0, i) + word(substring(i + 1); // line #5 ArrayList<String> shorterPermutations = permutations(shorter); // line #6 for (String s : shorterPermutations) // line #7 { result.add(word.charAt(i) + s); // line #8 } } return result; // line #9 } } a. It terminates the recursion when it encounters a string with one character. b. It terminates the recursion when it encounters a string with two characters. c. It terminates the recursion when it encounters the empty string or a string with one character. d. It terminates the recursion when it encounters the empty string. 90. Consider the permutations method from the textbook, which is intended to return all permutations of the word passed in as a parameter. How does the permutations method simplify its input for the recursive call?

public static ArrayList<String> permutations(String word) { ArrayList<String> result = new ArrayList<String>(); if (word.length() == 0) // line #1 { result.add(word); // line #2 return result; // line #3 } else { for (int i = 0; i < word.length(); i++) // line #4 { String shorter = word.substring(0, i) + word(substring(i + 1); // line #5 ArrayList<String> shorterPermutations = permutations(shorter); // line #6 for (String s : shorterPermutations) // line #7 { result.add(word.charAt(i) + s); // line #8 } } return result; // line #9 } Powered by Cognero

Page 41


Name:

Class:

Date:

testbank-bj-7-ch13

} a. It finds permutations of a shorter word by removing both the first and last character. b. It finds permutations of a shorter word by removing the last character. c. It finds permutations of shorter words formed by removing the ith character. d. It finds permutations of a shorter word by removing the first character. 91. Consider the permutations method from the textbook, which is intended to return all permutations of the word passed in as a parameter.

public static ArrayList<String> permutations(String word) { ArrayList<String> result = new ArrayList<String>(); if (word.length() == 0) // line #1 { result.add(word); // line #2 return result; // line #3 } else { for (int i = 0; i < word.length(); i++) // line #4 { String shorter = word.substring(0, i) + word(substring(i + 1); // line #5 ArrayList<String> shorterPermutations = permutations(shorter); // line #6 for (String s : shorterPermutations) // line #7 { result.add(word.charAt(i) + s); // line #8 } } return result; // line #9 } } If line #8 is changed to add the removed character to the end of each permutation of the shorter word, which change best describes the returned list?

result.add(s + word.charAt(i)); // line #8 revised a. It contains all permutations. b. It is an incomplete list of permutations. c. It contains strings that are not permutations. d. It contains duplicates of some permutations. 92. In a _____________, a set of cooperating methods calls each other repeatedly. a. infinite recursion Powered by Cognero

Page 42


Name:

Class:

Date:

testbank-bj-7-ch13 b. permutation c. mutual recursion d. stack overflow error 93. Consider the mutually recursive methods below. Select the method call that could be used to generate the output sequence: A5 B4 A3 B2 A1

public static void methodA(int value) { if (value > 0) { System.out.print(" A" + value); methodB(value - 1); } } public static void methodB(int value) { if (value > 0) { System.out.print(" B" + value); methodA(value - 1); } } a. methodA(5); b. methodA(4); c. methodB(5); d. methodB(4); 94. Recursion will take place if any of the following happen: I method A calls method B, which calls method C II method A calls method B, which calls method A III method A calls method A a. I and II only b. II and III only c. I only d. II only 95. Which of the following executions represent mutual recursion? I method E calls method T, which calls method F II method E calls method T, which calls method F, which calls method E III method F calls method F a. I and II only b. II and III only c. II only Powered by Cognero

Page 43


Name:

Class:

Date:

testbank-bj-7-ch13 d. I only 96. Recursion does NOT take place if any of the following happen: I method A calls method B, which calls method C, which calls method B II method A calls method B, which calls method A III method A calls method B, B returns, and A calls B again a. III only b. II only c. I only d. I and II only 97. Consider the following code snippet:

public static boolean isEven(int n) { if (n % 2 == 0) { return true; } else { return (isOdd(n)); } } public static boolean isOdd(int n) { if (n % 2 == 1) { return true; } else { return (isEven(n)); } } For any given value of n, what is the maximum number of function calls that could occur, including the original call? a. 1 b. 0 c. cannot be determined d. 2 98. Complete the following code snippet, which is intended to determine if a value is even or odd using mutual recursion:

public static boolean isEven(int n) { if (n == 0) { Powered by Cognero

Page 44


Name:

Class:

Date:

testbank-bj-7-ch13

return true; } else { return isOdd(Math.abs(n) - 1); } } public static boolean isOdd(int n) { if (n == 0) { _________ } else { return isEven(Math.abs(n) - 1); } } a. return true; b. return false; c. return isOdd(Math.abs(n)); d. return isOdd(Math.abs(n)-1); 99. Which statement is true about backtracking? a. Backtracking starts with a partial solution and builds it up to get closer to the goal. b. Backtracking never abandons a partial solution. c. Backtracking starts from the end of the program and works backward to the beginning. d. Backtracking explores only one path toward a solution 100. Which problem-solving technique examines partial solutions, abandons unsuitable ones, and returns to consider other candidate solutions. a. Backtracking b. Recursion c. Traceback d. Debugging

Powered by Cognero

Page 45


Name:

Class:

Date:

testbank-bj-7-ch13 Answer Key 1. d 2. b 3. d 4. d 5. d 6. d 7. b 8. b 9. d 10. c 11. a 12. d 13. d 14. d 15. a 16. a 17. a 18. c 19. c 20. b 21. a 22. d 23. b 24. b 25. c Powered by Cognero

Page 46


Name:

Class:

Date:

testbank-bj-7-ch13 26. d 27. a 28. c 29. a 30. b 31. d 32. b 33. c 34. d 35. c 36. a 37. a 38. b 39. c 40. a 41. d 42. b 43. d 44. d 45. d 46. d 47. d 48. c 49. a 50. d 51. a Powered by Cognero

Page 47


Name:

Class:

Date:

testbank-bj-7-ch13 52. c 53. a 54. d 55. d 56. d 57. d 58. c 59. b 60. a 61. c 62. c 63. b 64. c 65. c 66. d 67. a 68. a 69. b 70. a 71. d 72. c 73. a 74. c 75. c 76. c Powered by Cognero

Page 48


Name:

Class:

Date:

testbank-bj-7-ch13 77. a 78. c 79. b 80. c 81. d 82. c 83. b 84. a 85. b 86. a 87. a 88. d 89. d 90. c 91. a 92. c 93. a 94. b 95. c 96. a 97. d 98. b 99. a 100. a

Powered by Cognero

Page 49


Name:

Class:

Date:

testbank-bj-7-ch14

Indicate the answer choice that best completes the statement or answers the question. 1. What type of algorithm places elements in order? a. deletion b. searching c. sorting d. insertion 2. In each iteration, selection sort places which element in the correct location? a. The smallest in the array. b. The largest element in the array. c. A random element. d. The smallest element not yet placed in prior iterations. 3. Consider the sort method shown below for selection sort:

public static void sort(int[] a) { for (int i = 0; i < a.length – 1; i++) { int minPos = minimumPosition(i); swap(minPos, i); } } Suppose we modify the loop condition to read i < a.length. What would be the result? a. The sort would work exactly the same as before the code modification. b. The sort would work, but run one more iteration. c. The sort would work but with one less iteration. d. An exception would occur. 4. Consider the sort method shown below for selection sort:

public static void sort(int[] a) { for (int i = 0; i < a.length – 1; i++) { int minPos = minimumPosition(i); swap(minPos, i); } } Suppose we modify the call to the swap method call to read swap(i, minPos). What would be the result? a. An exception would occur. b. The sort would produce incorrect results. c. The sort would produce correct results. Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch14 d. The sort would work, but sort backwards. 5. Consider the sort method for selection sort shown below:

public static void sort(int[] a) { for (int i = 0; i < a.length – 1; i++) { int minPos = minimumPosition(i); swap(minPos, i); } } Suppose we modify the loop control to read int i = 1; i < a.length – 1; i++. What would be the result? a. The sort would still work correctly. b. The sort would not consider the first array element. c. An exception would occur d. The sort would not consider the last array element. 6. Which of the following completes the selection sort method minimumPosition()?

private static int minimumPosition(int[] a, int from) { int minPos = from; for (int i = from + 1; i < a.length; i++) { ________________ } return minPos; } a. if (a[i] > a[minPos]) { minPos = i; } b. if (a[i] < a[j]) { minPos = i; } c. if (a[i] < a[minPos]) { minPos = i; } d. if (a[i] < a[minPos]) { i = minPos; } 7. Consider the minimumPosition method from the SelectionSorter class. Complete the code to write a maximumPosition method that returns the index of the largest element in the range from index from to the end of the array.

private static int minimumPosition(int[] a, int from) { int minPos = from; for (int i = from + 1; i < a.length; i++) { if (a[i] < a[minPos]) { minPos = i; } } Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch14

return minPos; } private static int maximumPosition(int[] a, int from) { int maxPos = from; for (int i = from + 1; i < a.length; i++) { ________________ } return maxPos; } a. if(a[i] == a[maxPos]) { maxPos = i; } b. if(a[i] <= a[maxPos]) { maxPos = i; } c. if(a[i] > a[maxPos]) { maxPos = i; } d. if(a[i] < a[maxPos]) { maxPos = i; } 8. Consider the swap method shown below from the SelectionSorter class. If we modified it as shown in the swap2 method shown below, what would be the effect on the sort method?

private static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } private static void swap2(int[] a, int i, int j) { a[i] = a[j]; a[j] = a[i]; } a. Some array elements would be overwritten. b. It would sort the array in reverse order. c. It would still be correct, but run a little faster. d. There would be no effect. 9. After 9 iterations of selection sort working on an array of 10 elements, what must hold true? a. The largest element is correctly placed by default. b. The largest element is incorrectly placed. c. One more iteration is needed to complete the sort. d. The smallest element is incorrectly placed. 10. The largestPosition method below returns the index of the largest element in the tail range of an array of integers. Select the expression that would be needed to complete the selectionSort method below, so that it sorts the Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch14 elements in descending order.

/** Finds the largest element in the tail range of an array. @param a the array to be searched @param from the first position in a to compare @return the position of the largest element in range a[from]..a[a.length – 1] */ private static int largestPosition(int[] a, int from) { int maxPos = from; for(int j = from + 1; j < a.length; j++) { if (a[j] > a[maxPos]) { maxPos = j; } } return maxPos; } public static void selectionSort(int[] a) { for____________________________________ { int maxPos = largestPosition(a, i); ArrayUtil.swap(a, maxPos, i); } } a. (int i = 0; i < a.length – 1; i++) b. (int i = a.length – 1; i > 0; i--) c. (int i = a.length; i > 0; i--) d. (int i = 0; i < a.length; i++) 11. Which process is recommended for calculating the elapsed running time of an algorithm? a. Use a physical stopwatch to record the length of time it takes to run the program. b. Calculate the difference obtained by calls to the method System.currentTimeMillis() just before the start of the algorithm and just after the end of the algorithm. c. Calculate the difference obtained by calls to the method System.currentTimeMillis() at the start of the program and at the end of the program so that the elapsed time includes the display of the result. d. Use the value returned by the method System.currentTimeMillis() just after the end of the algorithm as the elapsed time. 12. The code segment below is designed to add the elements in an array of integers. Select the expression needed to complete the code segment so that it calculates the elapsed running time. Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch14

long start = System.currentTimeMillis(); int sum = 0; for (int k = 0; k < values.length; k++) { sum = sum + values[k]; } long runningTime = ____________________________; a. System.currentTimeMillis() - start b. System.currentTimeMillis() + start c. System.currentTimeMillis() d. runningTime + start - System.currentTimeMillis() 13. The performance of an algorithm is most closely related to what? a. The type of elements b. The total number of elements c. The total number of element visits d. The number of lines of code in the method 14. Consider an array with n elements. If we visit each element n times, how many total visits will there be? a. nn b. n c. 2n d. n2 15. Suppose an array has n elements. We visit element #1 one time, element #2 two times, element #3 three times, and so forth. How many total visits will there be? a. n2 b. n3 c. n(n+1)/2 d. 2n 16. Suppose an algorithm requires a total of 3n3 + 2n2 – 3n + 4 visits. In big-Oh notation, the total number of visits is of what order? a. n2 * n2 b. n2 c. n3 d. n6 17. In big-Oh notation, when we consider the order of the number of visits an algorithm makes, what do we ignore? I power of two terms II the coefficients of the terms Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch14 III all lower order terms a. II and III only b. II only c. I and II only d. I only 18. In big-Oh notation, suppose an algorithm requires an order of n3 element visits. How does doubling the number of elements affect the number of visits? a. It number of visits goes up by a factor of eight. b. It triples the number of visits. c. It quadruples the number of visits. d. It doubles the number of visits. 19. What is the smallest value of n for which n2> 3n + 4? a. 6 b. 5 c. 4 d. 3 20. How large does n need to be so 0.3n2 is greater than 2.5n – 3? a. 9 b. 5 c. 7 d. 3 21. If you increase the size of a dataset fivefold, how much longer does it take to sort it with the selection sort algorithm? a. Approximately 100 times longer b. Approximately 5 times longer c. Approximately 20 times longer d. Approximately 25 times longer 22. How many comparisons does selection sort make when sorting an array of length n? a. log(2n) b. n c. n( n + 1) / 2 d. n 23. In Big-Oh notation, selection sort is a(n) ____ algorithm. a. O(1) b. O(n2) c. O(log n2) d. log n Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch14 24. When the size of an array increases by a factor of 100, the time required by selection sort increases by a factor of ____. a. 5,000 b. 10,000 c. 12,000 d. 2,000 25. Which notation, big-Oh, theta, or omega describes the growth rate of a function? I big-Oh II theta III omega a. II and III only b. I only c. I and II only d. I, II, and III 26. In general, the expression ____ means that f grows no faster than g. a. f(n) = log g b. f(n) = log g2 c. g(n) = O(f(n)) d. f(n) = O(g(n)) 27. Find the simplest order of growth of the following expression: (n3 + n + 3)2. a. θ(2n) b. θ(n9) c. θ(n5) d. θ(n6) 28. Find the simplest order of growth of the following expression: n3 + log(n5). a. θ(log(n5)) b. θ(n3+ log(n)) c. θ(n+ log(n)) d. θ(n3) 29. Choose the order of the following growth rates, from slowest to fastest: θ(n3), θ(nlog(n)), θ(n3/2), θ(2n). a. θ(n log(n)), θ(n3/2), θ(n3), θ(2n) b. θ(n3), θ(n log(n)), θ(n3/2), θ(2n) c. θ(n3/2), θ(n log(n)), θ(n3), θ(2n) d. θ(2n), θ(n3), θ(n3/2), θ(n log(n)) 30. Which function has a faster growth rate: θ(n1/2) or θ(log(n))? Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch14 a. θ(n1/2) b. θ(log(n)) c. They can’t be compared. d. They are the same. 31. Consider the following code snippet:

public static void sort(int[] a) { for (int i = 1; i < a.length; i++) { int next = a[i]; int j = i; while (j > 0 && a[j - 1] > next) { a[j] = a[j - 1]; j--; } a[j] = next; } } What sort algorithm is used in this code? a. quicksort b. insertion sort c. merge sort d. selection sort 32. Which sort algorithm starts with an initial sequence of size 1, which is assumed to be sorted, and increases the size of the sorted sequence in the array in each iteration? a. selection sort b. quicksort c. merge sort d. insertion sort 33. What is the worst-case performance of insertion sort? a. O(log (n)) b. O(n2) c. O(n) d. O(n log (n)) 34. If the array is already sorted, what is the performance of insertion sort? a. O(log n) b. O(n2) c. O(n log n) Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch14 d. O(n) 35. Which sort algorithm starts by cutting the array in half and then recursively sorts each half? a. insertion sort b. quicksort c. merge sort d. selection sort 36. How many times can an array with 4,096 elements be cut into two equal pieces? a. 10 b. 8 c. 16 d. 12 37. The merge sort algorithm presented in section 14.4, which sorts an array of integers in ascending order, uses the merge method which is partially shown below. Select the condition that would be needed to complete the method so that the elements are sorted in descending order.

private static void merge(int[] first, int[] second, int[] a) { int iFirst = 0; int iSecond = 0; int j = 0; while (iFirst < first.length && iSecond < second.length) { if (_____________________________) { a[j] = first[iFirst]; iFirst++; } else { a[j] = second[iSecond]; iSecond++; } j++; } // rest of the method follows here } a. first[iFirst] > second[iSecond] b. first[iFirst] < second[iSecond] c. iFirst > iSecond d. iFirst < iSecond

Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch14 38. The number of element visits for merge sort totals n + 5n log2 n. Which of the following is the appropriate big-Oh notation for merge sort? a. n log2 n b. n+ log2 n c. n+ 5n d. 5n log2 n 39. Selection sort has O(n2) complexity. If a computer can sort 1,000 elements in 4 seconds, approximately how many seconds will it take the computer to sort 1,000 times that many, or 1,000,000 elements? a. 4,000,000 b. 1,000,000 c. 1,000 d. 16 40. Merge sort has a O(n log2(n)) complexity. If a computer can sort 1,024 elements in an amount of time x, approximately how long will it take the computer to sort 1,024 times that many, or 1,048,576 elements? a. 8,192x b. 1,024x c. 2,048x d. 1,048,576x 41. Merge sort is a(n) ____ algorithm. a. O(log n) b. O(n log(n)) c. O(n2) d. O(n) 42. Assume we are using quicksort to sort an array in ascending order. Into which array location does quicksort’s strategy place a pivot element after partitioning? a. closer to its correct final location b. lowest index in array still available c. its final correct location d. highest index in array still available 43. Assume we are using quicksort to sort an array in ascending order. What can we conclude about the indexes of two pivot elements placed in consecutive recursive calls? a. They are both in the same half of the array. b. They are in different halves of the array. c. They are adjacent. d. They are randomly located. 44. Assume we are using quicksort to sort an array in ascending order. What can we conclude about the elements to the left of the currently placed pivot element? a. They are all less than or equal to the pivot element. Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch14 b. They are all greater than or equal to the pivot element. c. They are all sorted. d. None can equal the pivot element. 45. When does quicksort’s worst-case run-time behavior occur? I when the data is randomly initialized in the array II when the data is in ascending order III when the data is in descending order a. III only b. I only c. II only d. II and III only 46. Which sort algorithm starts by partitioning the array and selecting a pivot element? a. insertion sort b. quicksort c. merge sort d. selection sort 47. A version of which sort algorithm is used in the sort method in the Java Arrays class? a. merge sort b. insertion sort c. quicksort d. selection sort 48. Which sort algorithm is used in the sort method in the Java Arrays class when the array length is less than 7? a. merge sort b. quicksort c. selection sort d. insertion sort 49. Which of the sorts in the textbook are based on the strategy of divide and conquer? I quicksort II mergesort III insertion sort a. III only b. I and II only c. II only d. I only 50. Which of the sorts in the textbook can be characterized by the fact that the best case will have a running time of θ(n) if the data is already sorted? I quicksort II selection sort III insertion sort a. III only Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch14 b. II only c. I only d. I and III only 51. Which of the sorts in the textbook can be characterized by the fact that even in the worst case the running time will be O(n log(n)))? I quicksort II selection sort III merge sort a. I and III only b. I only c. II only d. III only 52. In the worst case, quicksort is a(n) ____ algorithm. a. O(log(n)) b. O(n2) c. O(n log n) d. O(n) 53. In the worst case, a linear search locates a value in an array of length n in ____ steps. a. O(log n2) b. O(n) c. O(log n) d. O(n2) 54. The following code is an example of a ___ search.

public static int search(int[] a, int v) { for (int i = 0; i < a.length; i++) { if (a[i] == v) { return i; } } return -1; } a. binary b. sorted c. linear d. random 55. If an element is present in an array of length n, how many element visits, in the worst case, are necessary to find it using a linear search? a. n Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch14 b. 2n c. n / 2 d. n2 56. If an element is present in an array of length n, how many element visits, on average, are necessary to find it using a linear search? a. n / 2 b. 2n c. n d. n2 57. Another name for linear search is ____ search. a. random b. sequential c. sorted d. binary 58. Binary search is an ____ algorithm. a. O(log n) b. O(n2) c. O(n log n) d. O(n) 59. Given an ordered array with 15 elements, how many elements must be visited in the worst case of binary search? a. 2 b. 8 c. 4 d. 3 60. Given an ordered array with 31 elements, how many elements must be visited in the worst case of binary search? a. 16 b. 8 c. 5 d. 4 61. The analysis for the number of visits in a binary search begins with the equation, T(n) = T(n / 2) + 1. What does the number 1 represent in this equation? a. The fact that the number of elements is odd. b. The total number of recursions required. c. The fact that we search either the left half or the right half, but not both. d. One element visit before a recursive call on one half of the array. 62. Suppose we are using binary search on an array with approximately 1,000,000 elements. How many visits should we expect to make in the worst case? Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch14 a. 16 b. 30 c. 20 d. 1 63. A binary search is generally ____ a linear search. a. faster than b. less efficient than c. slower than d. equal to 64. A search technique where, in each step, you split the size of the search in half is called a____ search. a. random b. merging c. linear d. binary 65. Can you search the following array using binary search?

int[] A = {6, 5, 4, 2, 0, 1, -1, -17}; a. No, negative numbers are not allowed because they indicate that a value is not present. b. Yes. Binary search can be applied to any array. c. No. Binary search can be applied to a sorted array only. d. Yes, but the algorithm runs slower because the array is in descending order. 66. The partial linear search method below is designed to search an array of String objects. Select the expression that would be needed to complete the method.

public static int search(String[] a, String item) { for(int i = 0; i < a.length; i++) { if ( ____________________________ ) { return i; } return -1; } } a. a[i] == item b. a[i].compareTo(item) c. a[i].equals(item) d. a[i].indexOf(item) Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch14 67. The partial binary search method below is designed to search an array of String objects sorted in ascending order. Select the expression that would be needed to complete the method.

public static int search(String[] a, int low, int high, String item) { if(low <= high) { int mid = (low + high) / 2; int result = ____________________________; if (result == 0) { return mid; } else if (result < 0) { return search(a, mid + 1, high, item); } else { return search(a, low, mid - 1, item); } } return -1; } a. a[low].compareTo(item) b. item.compareTo(a[mid]) c. item.equals(a[mid]) d. a[mid].compareTo(item) 68. A portion of your program implements a loop over n elements in which each step contains a fixed number of actions. What can you conclude about the running time of this section of code? a. Its running time will be O(n2). b. Its running time will be O(log (n)). c. Its running time will be O(n log (n)). d. Its running time will be O(n). 69. Which of the following statements about running times of algorithms is correct? a. When determining the running time, lower-order terms must be taken into consideration. b. When determining the running time, constants are not taken into consideration. c. An algorithm that is O(1) means that only one comparison takes place. d. An algorithm that is O(n) means that the number of comparisons does not grow as the size of the array increases. 70. A portion of your program includes the loop shown in the code snippet below to examine the elements of an array arr: Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch14

int count = 0; int targetVal = 70; for (int i = 0; i < arr.length; i++) { if (arr[i] >= targetVal) { count++; } } What can you conclude about the running time of this section of code? a. Its running time will be O(n log (n)). b. Its running time will be O(n2). c. Its running time will be O(n). d. Its running time will be O(log (n)). 71. The method findLargest examines the elements of an array arr which contains non-negative values

public static int findLargest(int[] arr) { int curLargest = -1; for (int i = 0; i < arr.length; i++) { if (arr[i] >= curLargest) { curLargest = arr[i]; } } return curLargest; } What can you conclude about the running time of this section of code? a. Its running time will be O(n2). b. Its running time will be O(n). c. Its running time will be O(log (n)). d. Its running time will be O(n log (n)). 72. The method checkArray examines an array arr:

public static boolean checkArray(int[] arr) { if (arr[0] >= arr[arr.length -1]) { return true; } return false; Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch14

} What can you conclude about the running time of this section of code? a. Its running time will be O(1). b. Its running time will be O(n). c. Its running time will be O(log (n)). d. Its running time will be O(n2). 73. An algorithm that tests whether the first array element is equal to any of the other array elements would be an ____ algorithm. a. O(n log (n)) b. O(log (n)) c. O(1) d. O(n) 74. A portion of your program includes the loops shown in the code snippet below to examine the elements of two arrays, arr1 and arr2, both of length n:

int matches = 0; for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr2.length; j++) { if (arr1[i].equals(arr2[j])) { matches++; } } } What can you conclude about the running time of this section of code? a. Its running time will be O(log (n)). b. Its running time will be O(n). c. Its running time will be O(n log (n)). d. Its running time will be O(n2). 75. A portion of your program includes the method shown in the code snippet below to examine the elements of an array arr:

private int findElement(int[] arr, int newVal) { int pos = Arrays.binarySearch(arr, newVal); return pos; } What can you conclude about the running time of this section of code? a. Its running time will be O(log (n)). Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch14 b. Its running time will be O(n). c. Its running time will be O(n log (n)). d. Its running time will be O(n2). 76. An algorithm that cuts the work in half in each step is an ____ algorithm. a. O(log (n)) b. O(n log (n)) c. O(n2) d. O(n) 77. The code segment below prints some of the elements in an array with size n. Select an expression to complete the code segment so that the resulting algorithm has O(log n) running time.

for __________________________ { System.out.println(array[j]); } a. (int j = 0; j < array.length; j = j + 2) b. (int j = 0; j < array.length / 2; j++) c. (int j = 1; j < array.length; j = j * 2) d. (int j = 0; j < array.length; j++) 78. The code segment below displays a pattern of asterisks. Select an expression to complete the code segment so that the resulting algorithm has O(n) running time.

for (int k = 0; k < n; k++) { for _______________________ { System.out.print("*"); } System.out.println(); } a. (int j = n; j > 0; j = j / 2) b. (int j = 1; j <= 10; j++) c. (int j = 1; j < k; j++) d. (int j = n; j > 0; j--) 79. The code segment below displays a table of numbers. Select an expression to complete the code segment, so that the resulting algorithm has O(n2) running time.

for (int k = 1; k <=n; k++) { Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch14

for _______________________ { System.out.print(j + ""); } System.out.println(); } a. (int j = 1; j <= 200; j++) b. (int j = 1; j < k; j = j * 2) c. (int j = 0; j < k; j++) d. (int j = n; j > 0; j = j / 2) 80. Assume that names is an array of String objects that has been initialized with a large number of elements. Select the statement that would sort the elements in names in ascending alphabetic order. a. Collections.sort(names); b. Arrays.sort(names, 0, names.length - 1); c. Arrays.sort(names); d. Collections.sort(names, 0, names.length - 1); 81. Assume that bands is an ArrayList of String objects, which contains a number of elements in ascending order. Select a statement to complete the code segment below, which invokes the Java library binarySearch method to search for the string "Beatles". If the list does not already contain the string, it should be inserted in an appropriate location so that the list remains sorted.

int index = Collections.binarySearch(bands, "Beatles"); if (index < 0) { __________________________ } a. bands.add(-1 * index, "Beatles"); b. bands.add(-1 - index, "Beatles"); c. bands.add(-1 * index + 1, "Beatles"); d. bands.add(index + 1, "Beatles"); 82. The sort method of the Arrays class sorts arrays containing objects of classes that implement the ____ interface. a. Ordered b. Sortable c. Array d. Comparable 83. The ____ class contains a sort method that can sort array lists. a. Sorting b. Linear c. Collections Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch14 d. Arrays 84. The binarySearch method of the Collections class returns a value in the form of –k - 1 when the target item you are searching for was not found in the array. What does k represent? a. It represents the index at which the target item should be inserted. b. It represents the number of times the array was accessed by the binarySearch method, and can be used for analyzing performance. c. Nothing – it is an arbitrary value. d. It is the position of an existing item, and indicates that your target item should come after this existing item. 85. Given the following code snippet for searching an array:

int[] arr = {3, 8, 12, 14, 17}; int newVal = 15; int pos = Arrays.binarySearch(arr, newVal); What value will pos have when this code is executed? a. 6 b. -5 c. -6 d. 5 86. Given the following code snippet for searching an array:

int[] arr = {23, 25, 29, 34, 42}; int newVal = 15; int pos = Arrays.binarySearch(arr, newVal); What value will pos have when this code is executed? a. 0 b. 1 c. -2 d. -1 87. If a call to the Arrays static method binarySearch returns a value of -10, what can be concluded? I the element is not in the array II the element is at index 10 III the element can be inserted at index 9 a. II only b. I and III only c. III only d. I only 88. If a call to the Arrays static method binarySearch returns a value of 7, what can be concluded? I the element is not in the array II the element is at index 7 Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch14 III the element occurs 7 times in the array a. II and III only b. I only c. II only d. III only 89. The Comparable interface consists of a single method called ____. a. comparator b. comparable c. compare d. compareTo 90. Which of the following classes implement the Comparable interface? I Date II Collections III String a. I only b. I and III only c. I and II only d. II and III only 91. Suppose the call obj1.compareTo(obj2) returns 0. What can definitely be concluded from the return value? I obj1 and obj2 are the same object II obj1 and obj2 objects cannot be compared III the properties of obj1 and obj2 that are being compared have equal values a. II only b. III only c. I only d. I and III only 92. Which of the following arrays can be used in a call to the Arrays.sort method? I Any array with primitive numeric data, such as int, double, … II Arrays of String or numeric wrapper classes like, Integer, Double, … III Any class that implements the Comparable interface a. I, II and III b. II only c. I only d. I and II only 93. Suppose objects a and b are from a user-defined class that implements the Comparable interface. Which condition tests the compareTo method’s return value to determine that a will precede b when the sort method is called? a. a.compareTo(b) == -1 b. a.compareTo(b) < 0 c. a.compareTo(b) == 0 d. a.compareTo(b) > 0 Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch14 94. Suppose objects a and b are from a user-defined class that implements the Comparable interface. What must be true about the return value of a.compareTo(b) for the compareTo method that this class implements? a. It must return 1 if a comes before b, 0 if they are the same, and -1 if a comes after b. b. It must return -1 if a comes before b, 0 if they are the same, and 1 if a comes after b. c. It must return a negative value if a comes before b, 0 if they are the same, and a positive value if a comes after b. d. It must return a positive value if a comes before b, 0 if they are the same, and a negative value if a comes after b. 95. Suppose you wish to implement the Comparable interface to allow your Vehicle class to compare Auto objects only. Which of the following is the correct way to do this? a. public class Auto implements Comparable<Vehicle> b. public class Vehicle implements Comparable(Auto) c. public class Vehicle implements Comparable d. public class Vehicle implements Comparable<Auto> 96. Suppose a developer gets class XYZ files and documentation from a subcontractor. This class does not implement the Comparable interface. What must be true in order for the developer to sort an array of XYZ objects without modifying the XYZ class? a. The XYZ class must implement the Sortable interface. b. XYZ objects must be randomly distributed. c. XYZ objects must be ordered. d. The developer must supply a comparator object belonging to a class that implements the Comparator<XYZ> interface. 97. Suppose you wish to sort an array list of objects, but the object class does not implement the Comparable interface. Because you are not allowed to modify this class, you decide to provide a comparator object that implements the Comparator interface. Which method must you implement from this interface to achieve your objective? a. sort b. compareObject c. compare d. compareTo 98. Complete the code shown to define the Comparator interface for comparing Auto objects.

public interface Comparator<Auto> { _____________________ } a. boolean compare(Auto a, Auto b); b. single compare(Auto a, Auto b); c. single compareTo(Auto a, Auto b); d. int compare(Auto a, Auto b); Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch14 99. Complete the code shown to define the Comparator interface for comparing Auto objects.

___________________________ { int compare(Auto a, Auto b); } a. public class Comparator<Auto> b. public class Comparator<Auto> implements Comparator c. public interface Comparator<Auto> d. public interface Auto<Comparator> 100. What must be true about the return value from the implementation of the compare method for the Comparator interface when comparing two objects, a and b with a call to compare(a, b)? a. It must return 1 if a comes before b, 0 if they are the same, and -1 if a comes after b. b. It must return a negative value if a comes before b, 0 if they are the same, and a positive value if a comes after b. c. It must return a positive value if a comes before b, 0 if they are the same, and a negative value if a comes after b. d. It must return -1 if a comes before b, 0 if they are the same, and 1 if a comes after b. 101. Which of the following statements correctly provides a comparator function using lambda expressions to sort an array of countries by population, assuming the existence of a getPopulation method? a. Arrays.sort(countries, comparator(c -> c.getPopulation())); b. Arrays.sort(countries, compare(c1 -> c1.getPopulation(), c2 -> c2.getPopulation()); c. Arrays.sort(countries, (c1, c2) -> c1.getPopulation() c2.getPopulation()); d. Arrays.sort(countries, c -> c.getPopulation()); 102. Which of the following statements correctly specifies the use of lambda expressions and the comparing method of the Comparator functional interface to sort an array of countries by population, assuming the existence of a getPopulation method? a. Arrays.sort(countries, Comparator.comparing(c1 -> c1.getPopulation(), c2 > c2.getPopulation()); b. Arrays.sort(countries, comparing(c -> c.getPopulation())); c. Arrays.sort(countries, c -> c.getPopulation()); d. Arrays.sort(countries, Comparator.comparing(c -> c.getPopulation());

Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch14 Answer Key 1. c 2. d 3. b 4. c 5. b 6. c 7. c 8. a 9. a 10. a 11. b 12. a 13. c 14. d 15. c 16. c 17. a 18. a 19. b 20. c 21. d 22. c 23. b 24. b 25. d Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch14 26. d 27. d 28. d 29. a 30. a 31. b 32. d 33. b 34. d 35. c 36. d 37. a 38. a 39. a 40. c 41. b 42. c 43. d 44. a 45. d 46. b 47. c 48. d 49. b 50. a 51. d Powered by Cognero

Page 25


Name:

Class:

Date:

testbank-bj-7-ch14 52. b 53. b 54. c 55. a 56. a 57. b 58. a 59. c 60. c 61. d 62. c 63. a 64. d 65. c 66. c 67. d 68. d 69. b 70. c 71. b 72. a 73. d 74. d 75. a 76. a Powered by Cognero

Page 26


Name:

Class:

Date:

testbank-bj-7-ch14 77. c 78. b 79. c 80. c 81. b 82. d 83. c 84. a 85. b 86. d 87. b 88. c 89. d 90. b 91. b 92. a 93. b 94. c 95. d 96. d 97. c 98. d 99. c 100. b 101. c 102. d Powered by Cognero

Page 27


Name:

Class:

Date:

testbank-bj-7-ch14

Powered by Cognero

Page 28


Name:

Class:

Date:

testbank-bj-7-ch15

Indicate the answer choice that best completes the statement or answers the question. 1. The ArrayList class implements the ____ interface. a. Stack b. Queue c. List d. Set 2. A list is a collection that ____. a. does not allow elements to be inserted in any position. b. only allows items to be added at one end and removed at the other end. c. manages associations between keys and values. d. should be used when you need to remember the order of elements in the collection. 3. A stack is a collection that ____. a. does not remember the order of elements but allows elements to be added in any position. b. remembers the order of elements, and allows elements to be added and removed only at one end. c. remembers the order of elements and allows elements to be inserted only at one end and removed only at the other end. d. remembers the order of elements and allows elements to be inserted in any position. 4. A queue is a collection that ____. a. remembers the order of elements, and allows elements to be added and removed only at one end. b. remembers the order of elements and allows elements to be inserted only at one end and removed only at the other end. c. does not remember the order of elements but allows elements to be added in any position. d. remembers the order of elements and allows elements to be inserted in any position. 5. A collection without an intrinsic order is called a ____. a. queue b. stack c. set d. list 6. A collection that allows items to be added only at one end and removed only at the other end is called a ____. a. set b. stack c. queue d. list 7. A collection that remembers the order of items, and allows items to be added and removed only at one end is called a ____. a. queue b. stack c. list Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch15 d. set 8. A collection that allows speedy insertion and removal of already-located elements in the middle of it is called a ____. a. linked list b. stack c. set d. queue 9. Which data structure would best be used for keeping track of groceries to be purchased at the food market? a. stack b. queue c. list d. array 10. Select an appropriate expression to complete the following code segment, which is designed to print a message if the string stored in name is part of the players collection.

Collection<String> players = new ArrayList<>(); // code to add elements to the collection here if ______________________________________ { System.out.print(name + " is one of the players in the collection."); } a. (players.contains(name)) b. (players.indexOf(name)) c. (players.search(name)) d. (players.equals(name)) 11. What is included in a linked list node? I a reference to its neighboring nodes II an array reference III a data element a. II only b. I and III only c. I only d. II and III only 12. Which of the following statements about linked lists is correct? a. When a node is removed, all nodes after the removed node must be moved down. b. Visiting the elements of a linked list in random order is efficient. c. Linked lists should be used when you know the correct position and need to insert and remove elements efficiently. d. Even if you have located the correct position, adding elements in the middle of a linked list is inefficient. Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch15 13. 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 14. Which nodes need to be updated when we insert a new node to become the fourth node from the beginning of a doubly-linked list? a. The current third and fourth nodes. b. The current fourth and fifth nodes. c. The current first node. d. The current third node. 15. A binary search requires ____ access. a. sorted b. random c. arbitrary d. sequential 16. A linear search only requires ____ access. a. sorted b. arbitrary c. sequential d. random 17. Rather than storing values in an array, a linked list uses a sequence of ____. a. accessors b. nodes c. elements d. indexes 18. Which of the following algorithms would be efficiently executed using a LinkedList? a. Remove first n/ 2 elements from a list of n elements. b. Read n / 2 elements in random order from a list of n elements. c. Tracking paths in a maze. d. Binary search. 19. What type of access does a LinkedList provide for its elements? a. sorted b. sequential c. random d. semi-random Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch15 20. 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 21. Consider the following code snippet:

LinkedList<String> words = new LinkedList<>(); words.addFirst("abc"); words.addLast("def"); words.addFirst("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. ghiabcdef b. defghiabc c. abcdefghi d. abcghidef 22. The term ____ is used in computer science to describe an access pattern in which the elements are accessed in arbitrary order. a. sequential access b. sorted access c. arbitrary access d. random access 23. Which Java package contains the LinkedList class? a. java.lang b. java.io c. java.collections d. java.util 24. What can a generic class be parameterized for? Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch15 a. methods b. iterators c. type d. properties 25. Assume you have created a linked list named myList that currently holds some number of String objects. Which of the following statements correctly adds a new element to the beginning of myList? a. myList.insert("Harry"); b. myList.addFirst("Harry"); c. myList.add("Harry"); d. myList.put("Harry"); 26. 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(); 27. A ____ is a data structure used for collecting a sequence of objects that allows efficient addition and removal of already-located elements in the middle of the sequence. a. queue b. priority queue c. stack d. linked list 28. Which method is NOT part of the ListIterator interface? a. next b. delete c. add d. previous 29. Consider the code snippet shown below. Assume that employeeNames is an instance of type LinkedList<String>.

for (String name : employeeNames) { // Do something with name here } Which element(s) of employeeNames does this loop process? a. elements meeting a condition b. the most recently added elements c. no elements d. all elements Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch15 30. Which method is NOT part of the ListIterator interface? a. hasPrevious b. hasMore c. add d. hasNext 31. Select an appropriate expression to complete the following code segment, which is designed to print a message if the string stored in name is the first element of the players linked list.

LinkedList<String> players = new LinkedList<>(); // code to add elements to the linked list if ______________________________________ { System.out.print(name + " is the first player on the list."); } a. (players.getFirst().equals(name)) b. (players[0].equals(name)) c. (players.contains(name)) d. (players.indexOf(name) == 1) 32. Select an appropriate expression to complete the method below. The method should return the number of times that the string stored in name appears in theList.

public static int count(LinkedList<String> theList, String name) { int number = 0; Iterator<String> iter = theList.iterator(); while (______________________) { if (iter.next().equals(name)) { number++; } } return number; } a. theList.next() != null b. iter.hasNext() c. theList.hasNext() d. iter.next() != null 33. Select an appropriate expression to complete the following method, which is designed to visit the elements in Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch15 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"); 34. When using a list iterator, on which condition will the IllegalStateException be thrown? a. Calling next after calling previous. b. Calling remove after calling previous. c. Calling remove after calling remove. d. Calling remove after calling next. 35. When using a list iterator, on which condition will the IllegalStateException be thrown? a. Calling remove after calling next. b. Calling remove after calling add. c. Calling add after calling previous. d. Calling previous after calling previous. 36. When using the add method of the ListIterator to add an element to a linked list, which of the following statements is correct? a. The new element is inserted before the iterator position, and a subsequent call to next would be unaffected. b. The new element is inserted after the iterator position, and a subsequent call to next would return the new element. c. The new element is inserted after the iterator position, and a subsequent call to previous would be unaffected. d. The new element is inserted before the iterator position, and a subsequent call to next would return the new element. 37. 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. Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch15 c. Calling remove after calling previous. d. Calling next when the iterator points to the last element. 38. You use a(n) ____ to access elements inside a linked list. a. queue b. accessor c. list iterator d. index 39. The nodes of a(n) ____ linked list class store two links: one to the next element and one to the previous one. a. array b. singly c. randomly d. doubly 40. Assume you are using a doubly-linked list data structure with many nodes. What is the minimum number of node references that are required to be modified to remove a node from the middle of the list? Consider the neighboring nodes. a. 3 b. 2 c. 4 d. 1 41. In a linked list data structure, when does the reference to the first node need to be updated? I inserting into an empty list II deleting from a list with one node III deleting an inner node a. I and II only b. I only c. II only d. III only 42. Consider the following code snippet:

LinkedList<String> myLList = new LinkedList<>(); myLList.add("Mary"); myLList.add("John"); myLList.add("Sue"); ListIterator<String> iterator = myLList.listIterator(); iterator.next(); iterator.next(); iterator.add("Robert"); iterator.previous(); iterator.previous(); iterator.remove(); System.out.println(myLList); Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch15 What will be printed when this code is executed? a. [Mary, John, Robert, Sue] b. [John, Robert, Sue] c. [Mary, Robert, Sue] d. [Mary, John, Sue] 43. 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. 44. Which of the following statements about hash tables is NOT correct? a. Elements are grouped into smaller collections that share the same characteristic. b. You can form hash tables holding objects of type String. c. The value used to locate an element in a hash table is called a hash code. d. You can add an element to a specific position within a hash table. 45. Which of the following statements about the TreeSet class is NOT correct? a. Elements are stored in nodes. b. Elements are arranged in linear fashion. c. To use a TreeSet, it must be possible to compare the elements. d. Elements are stored in sorted order. 46. Select an appropriate declaration to complete the following code segment, which is designed to read strings from standard input and display them in increasing alphabetical order, excluding any duplicates.

_________________________________________ Scanner input = new Scanner(System.in); while (input.hasNext()) { words.add(input.next()); } System.out.print(words); a. LinkedList<String> words = new LinkedList<>(); b. Set<String> words = new TreeSet<>(); c. Set<String> words = new Set<>(); d. Set<String> words = new HashSet<>(); 47. Select an appropriate expression to complete the following method, which is designed to return the number of elements in the parameter array numbers. If a value appears more than once, it should be counted exactly once.

public static int countElementsOnce(int[] numbers) { Set<Integer> values = new HashSet<>(); Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch15

for (int num: numbers) { values.add(num); } ______________________ } a. return numbers.length – values.size(); b. return values.size(); c. return numbers.length; d. return values.length(); 48. To create a TreeSet for a class of objects, the object class must ____. a. implement the Set interface. b. implement the Comparable interface. c. create an iterator. d. create a Comparator object. 49. Which of the following statements about manipulating objects in a set is correct? a. If you try to remove an element that does not exist, an exception will occur. b. If you try to add an element that already exists, an exception will occur. c. A set iterator visits elements in the order in which the set implementation keeps them. d. You can add an element at the position indicated by an iterator. 50. Which of the following statements about manipulating objects in a set is correct? a. A set iterator visits elements in the order in which they were added to the set. b. You can remove an element at the position indicated by an iterator. c. If you try to add an element that already exists, an exception will occur. d. You can add an element at the position indicated by an iterator. 51. Assume that you have declared a set named mySet to hold String elements. Which of the following statements will correctly insert an element into mySet? a. mySet.put(apple"); b. mySet.insert("apple"); c. mySet.add("apple"); d. mySet.push("apple"); 52. Assume that you have declared a set named mySet to hold String elements. Which of the following statements will correctly delete an element from mySet? a. mySet.delete("apple"); b. mySet.remove("apple"); c. mySet.get("apple"); d. mySet.pop("apple"); 53. Which of the following statements about manipulating objects in a map is NOT correct? Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch15 a. Use the remove method to remove a value from the map. b. Use the get method to retrieve a value from the map. c. Use the keyset method to get the set of keys for the map. d. Use the add method to add a new element to the map. 54. 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(); 55. 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<>(); . . . Set<String> mapKeySet = myMap.keySet(); for (String aKey : mapKeySet) { ___________________________; System.out.println("ID: " + aKey + "->" + name); } a. String name = myMap.next(aKey); b. String name = MapKeySet.get(aKey); c. String name = myMap.get(aKey); d. String name = MapKeySet.next(aKey); 56. Assume that you have declared a map named myMap to hold String values with Integer keys. Which of the following statements will correctly add an association into myMap? a. myMap.insert(3, "apple"); b. myMap.add(3, "apple"); c. myMap.put(3, "apple"); d. myMap.push(3, "apple"); Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch15 57. Assume that you have declared a map named myMap to hold String values with Integer keys. Which of the following statements will correctly delete an association from myMap? a. myMap.remove(3); b. myMap.remove("apple"); c. myMap.delete(3); d. myMap.pop(3); 58. Assume that you have declared a map named myMap to hold String values with Integer keys. Which of the following statements will correctly retrieve the value associated with a key from myMap? a. myMap.peek(3); b. myMap.get("apple"); c. myMap.peek("apple"); d. myMap.get(3); 59. Your program uses a Map structure to store a number of user ids and corresponding email addresses. Although each user must have a unique id, two or more users can share the same email address. Assuming that all entries in the map have valid email addresses, select an appropriate expression to complete the method below, which adds a new id and email address to the map only if the id is not already in use. If the id is already in use, an error message is printed.

public static void addUserID(Map<String, String> users, String id, String email) { String currentEmail = users.get(id); if (___________________) { users.put(id, email); } else { System.out.println(id + " is already in use."); } } a. !currentEmail.equals(email) b. currentEmail.equals(email) c. currentEmail != null d. currentEmail == null 60. Which of the following statements about manipulating objects in a map is NOT correct? a. Use the put method to add an element to the map. b. If you attempt to retrieve a value with a key that is not associated with any value, you will receive a null result. c. Use the get method to retrieve a value associated with a key in the map. d. You cannot change the value of an existing association in the map; you must delete it and re-add it with the new values. Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch15 61. Consider the following code snippet:

Map<String, Integer> scores; If you need to visit the keys in sorted order, which of the following statements will create a structure to support this? a. scores = new HashTable<>; b. scores = new HashMap<>; c. scores = new TreeMap<>; d. scores = new Map<>; 62. Consider the following code snippet:

Map<String, Integer> scores; You expect to retrieve elements randomly by key, and want fastest retrieval times. Which of the following statements will create a structure to support this? a. scores = new HashMap<>; b. scores = new Map<>; c. scores = new TreeMap<>; d. scores = new TreeSet<>; 63. You want to enumerate all of the keys in a map named myMap whose keys are type String. Which of the following statements will allow you to do this? a. Set<String> keySet = myMap.getKeySet(); for (String key : keySet) {. . . } b. Set<String> keySet = myMap.keySet(); for (String key : keySet) {. . . } c. Set<String> keySet = myMap.keys(); for (String key : keySet) {. . . } d. Set<String> keySet = myMap.getKeys(); for (String key : keySet) {. . . } 64. Using the merge method of the Map interface, which statement correctly updates the wordCount map of type Map<String,Integer> to count all of the occurrences of a word in a file? a. wordCount.merge(word, 1, (k,v) -> v + 1); b. word.merge(wordCount,(k,v) -> v + 1); c. word.merge(wordCount, 1, (k,v) -> v + 1); d. wordCount.merge(word,(k,v) -> v + 1); 65. Using the merge method of the Map interface, which statement correctly updates the salesTotalByDept map of type Map<String,Integer> to update the sales total for a dept by an integer sales value? a. salesTotalByDept.merge(dept, sales,(d,s) -> s + 1); b. sales.merge(salesTotalByDept, dept, (d,s) -> s + sales); c. dept.merge(salesTotalByDept, sales, (d,s) -> s + sales); d. salesTotalByDept.merge(dept, sales, (d,s) -> s + sales); 66. You need to access values by an integer position. Which collection type should you use? a. Queue b. Map c. Hashtable Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch15 d. ArrayList 67. You need to access values in objects by a key that is not part of the object. Which collection type should you use? a. Hashtable b. ArrayList c. Map d. Queue 68. You need to access values in the order in which they were added (first in, first out), and not randomly. Which collection type should you use? a. Queue b. Map c. Stack d. Hashtable 69. You need to access values in the opposite order in which they were added (last in, first out), and not randomly. Which collection type should you use? a. Hashtable b. Map c. Queue d. Stack 70. You need to access values using a key, and the keys must be sorted. Which collection type should you use? a. Queue b. TreeMap c. HashMap d. ArrayList 71. Which data structure would best be used for storing a set of numbers and sorting them in ascending order? a. queue b. array c. stack d. list 72. Which of the following algorithms would be efficiently executed on an ArrayList? a. remove first n / 2 elements from a list of n elements b. add 1 element to the middle of a list with n elements c. add n / 2 elements to a list with n / 2 elements d. read n / 2 elements in random order from a list of n elements 73. What operation is least efficient in a LinkedList? a. Linear traversal step. b. Random access of an element. c. Adding an element in a position that has already been located. Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch15 d. Removing an element when the element's position has already been located. 74. You need to write a program to simulate the effect of adding an additional cashier in a supermarket to reduce the length of time customers must wait to check out. Which data structure would be most appropriate to simulate the waiting customers? a. map b. stack c. linked list d. queue 75. 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. 76. Which of the following statements about hash functions is NOT correct? a. Using a prime number as a hash multiplier will produce better hash codes. b. If you supply your own hashCode method for a class, it must be compatible with that class's equals method. c. A good hash function will minimize the number of objects that are assigned the same hash code. d. A hash function produces a unique integer-valued hash code value for each distinct object. 77. Which of the following statements about stacks is correct? a. A stack implements random retrieval. b. A stack implements last-in, first-out retrieval. c. A stack stores elements in sorted order. d. A stack implements first-in, first-out retrieval. 78. An Undo feature in a word processor program that allows you to reverse a previously completed command is probably implemented using which structure type? a. stack b. queue c. hash table d. linked list 79. Which of the following correctly declares a stack that will hold String elements? a. Stack s = new Stack<>(); b. Stack<String> s = new Stack<>(); c. String s = new Stack(); d. String s = new Stack<>(); 80. Assume that you have declared a stack named myStack to hold String elements. Which of the following statements will correctly add an element to myStack? Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch15 a. myStack.addItem("apple"); b. myStack.put("apple"); c. myStack.insert("apple"); d. myStack.push("apple"); 81. Assume that you have declared a stack named myStack to hold String elements. Which of the following statements will correctly remove an element from myStack? a. myStack.delete(); b. myStack.pop(); c. myStack.remove(); d. myStack.get(); 82. Assume that you have declared a stack named myStack to hold String elements. Which of the following statements will correctly retrieve the top element from myStack without removing it? a. myStack.pop(); b. myStack.get(); c. myStack.peek(); d. myStack.next(); 83. Consider the code snippet shown below:

Stack<String> words1 = new Stack<>(); Stack<String> words2 = new Stack<>(); words1.push("abc"); words1.push("def"); words1.push("ghi"); while (!words1.empty()) { words2.push(words1.pop()); } while (!words2.empty()) { System.out.print(words2.pop()); } What will be printed when this code is executed? a. defghiabc b. abcghidef c. abcdefghi d. ghiabcdef 84. Which operations from the list data structure could be used to implement the push and pop operations of a stack data structure? I addLast II addFirst Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch15 III removeFirst a. I and II only b. II and III only c. II only d. I only 85. 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, 86. Select an appropriate expression to complete the method below, which is designed to print the element at the bottom of a Stack collection. The contents of the original stack are restored before the method terminates. It is safe to assume that the original stack contains at least one element.

public static void printBottom(Stack<String> theStack) { Stack<String> anotherStack = new Stack<>(); while (!theStack.empty()) { anotherStack.push(theStack.pop()); } ____________________________ while (!anotherStack.empty()) { theStack.push(anotherStack.pop()); } } a. System.out.println(theStack.pop()); b. System.out.println(anotherStack.pop()); c. System.out.println(anotherStack.peek()); d. System.out.println(theStack.peek()); Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch15 87. Print jobs submitted to a printer would probably be stored in which type of data structure? a. linked list b. queue c. stack d. hash table 88. Assume that you have declared a queue named myQueue to hold String elements. Which of the following statements will correctly delete an element from myQueue? a. myQueue.delete(); b. myQueue.remove(); c. myQueue.get(); d. myQueue.pop(); 89. 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"); 90. Assuming that names is a Queue of String objects, select a statement to complete the code segment below. The code is designed to remove the last element from the queue, which is guaranteed to have at least one element.

Queue<String> aQueue = new LinkedList<>(); while (names.size() > 1) { aQueue.add(names.remove()); } names.remove(); while (aQueue.size() > 0) { ____________________________ } a. aQueue.add(names.peek()); b. aQueue.add(names.remove()); c. names.add(aQueue.peek()); d. names.add(aQueue.remove()); 91. Select an appropriate expression to complete the following method, which is designed to return the sum of the two smallest values in the parameter array numbers.

public static int sumTwoLowestElements(int[] numbers) { PriorityQueue<Integer> values = new PriorityQueue<>(); for (int num: numbers) Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch15

{ values.add(num); } ______________________ } a. return values.remove() * 2; b. return values.peek() + values.remove(); c. return values.peek() + values.peek(); d. return values.remove() + values.remove(); 92. Suppose you push integer elements 1,2,3,4 onto a stack in that order. Then pop an element off the stack and add that element to a queue. You repeat that process three more times. In what order will you remove the elements from the queue? a. 1,2,4,3 b. 4,3,2,1 c. 4,3,1,2 d. 1,2,3,4 93. Suppose we have two String objects and treat the characters in each string from beginning to end in the following way: With one string, we push each character on a stack. With the other string, we add each character to a queue. After processing both strings, we then pop one character from the stack and remove one character from the queue, and compare the pair of characters to each other. We do this until the stack and the queue are both empty. What does it mean if all the character pairs match? a. The strings are the identical. b. We can only conclude the strings are of the same length. c. One string is the reverse of the other. d. The strings are different. 94. Consider the following code snippet:

Queue<String> stringQueue = new LinkedList<>(); stringQueue.add("ab"); stringQueue.add("abc"); stringQueue.add("a"); while (stringQueue.size() > 0) { System.out.print(stringQueue.remove() + ","); } What output will be produced when this code is executed? a. ab,abc,a, b. abc,ab,a, c. a,abc,ab, d. a,ab,abc, 95. Suppose we create a deque (double-ended queue) data structure. It is basically a queue, with its addLast and Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch15 removeFirst operations, but we also add the addFirst and removeLast operations. Which of the following is best modeled by the deque data structure? a. A cross country race. b. A toll booth on a highway. c. A Memorial Day parade. d. A computer keyboard typing buffer. 96. Which of the following statements about a priority queue structure is correct? a. Elements must be removed in priority order. b. New items must be inserted at the end of the queue. c. It uses a FIFO discipline. d. It uses a LIFO discipline. 97. Which of the following statements about a priority queue structure is NOT correct? a. The insert method is used to add a new element to the priority queue. b. The remove method is used to remove an element from the priority queue. c. Elements added to a priority queue must belong to a class that implements the Comparable interface. d. New elements can be inserted in any order. 98. Consider the following code snippet:

PriorityQueue<String> stringQueue = new PriorityQueue<>(); stringQueue.add("ab"); stringQueue.add("abc"); stringQueue.add("a"); while (stringQueue.size() > 0) { System.out.print(stringQueue.remove() + ","); } What output will be produced when this code is executed? a. ab,abc,a, b. a,ab,abc, c. abc,ab,a, d. a,abc,ab, 99. 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 100. You need a data structure in your program for balancing parentheses in an expression. Which data structure would be most appropriate to model this situation? a. list Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch15 b. stack c. array d. queue 101. You need a data structure in your program for evaluating algebraic expressions. Which data structure would be most appropriate to model this situation? a. list b. array c. queue d. stack 102. 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

Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch15 Answer Key 1. c 2. d 3. b 4. b 5. c 6. c 7. b 8. a 9. c 10. a 11. b 12. c 13. d 14. a 15. b 16. c 17. b 18. a 19. b 20. c 21. b 22. d 23. d 24. c 25. b Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch15 26. d 27. d 28. b 29. d 30. b 31. a 32. b 33. d 34. c 35. b 36. a 37. a 38. c 39. d 40. b 41. a 42. c 43. c 44. d 45. b 46. b 47. b 48. b 49. c 50. b 51. c Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch15 52. b 53. d 54. c 55. c 56. c 57. a 58. d 59. d 60. d 61. c 62. a 63. b 64. a 65. d 66. d 67. c 68. a 69. d 70. b 71. b 72. d 73. b 74. d 75. b 76. d Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch15 77. b 78. a 79. b 80. d 81. b 82. c 83. c 84. b 85. d 86. c 87. b 88. b 89. a 90. d 91. d 92. b 93. c 94. a 95. d 96. a 97. a 98. b 99. d 100. b 101. d 102. a Powered by Cognero

Page 25


Name:

Class:

Date:

testbank-bj-7-ch15

Powered by Cognero

Page 26


Name:

Class:

Date:

testbank-bj-7-ch16

Indicate the answer choice that best completes the statement or answers the question. 1. What is included in a linked list node? I a reference to the next node II an array reference III a data element a. I b. II c. II and III d. I and III 2. In the textbook implementation, the Node class is a private inner class of the LinkedList class. Which of the following statements regarding this implementation is NOT correct? a. The methods of the LinkedList class can access the public features of the Node class. b. The methods of the Node class can access the public features of the LinkedList class. c. The methods of the Node class can be directly accessed by other classes. d. The Node class's instance variables that represent the node element and its next node reference are declared as public. 3. Which Java package contains the LinkedList class? a. java.lang b. java.util c. java.collections d. java.io 4. Insert the missing code in the following code fragment. This fragment is intended to add a new node to the head of a linked list:

public class LinkedList { . . . public void addFirst(Object element) { Node newNode = new Node(); newNode.data = element; _________ _________ } . . . } a. first = newNode;

newNode.next = first; b. newNode.next = first; first = newNode; c. first = newNode.next; newNode.next = first; Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch16 d. first = newNode.next; newNode = first;

5. Insert the missing code in the following code fragment. This fragment is intended to remove a node from the head of a linked list:

public class LinkedList { . . . public Object removeFirst() { if (first == null) { throw new NoSuchElementException(); } Object element = first.data; ________________ ________________ } . . . } a. first = first.next;

return element; b. first.next = first; return element; c. first = element.next; return element; d. first = element.next; return null;

6. Which of the following statements about removing a node from a linked list is correct? a. A node's data is discarded when it is removed from the linked list, and its memory space is immediately reclaimed. b. A node's data is returned to the program when the node is removed from the linked list, and its memory space is immediately reclaimed. c. A node's data is discarded when it is removed from the linked list, and its memory space is reclaimed later by the garbage collector. d. A node's data is returned to the program when the node is removed from the linked list, and its memory space is reclaimed later by the garbage collector. 7. In the textbook implementation, the LinkedListIterator class is a private inner class of the LinkedList class. Which of the following statements regarding this implementation is NOT correct? a. The methods of the LinkedList class can access the public features of the LinkedListIterator class. b. The methods of the LinkedListIterator class can access the public features of the LinkedList class. c. The methods of the LinkedListIterator class can be directly accessed by other classes. d. Clients of the LinkedListClass do not know the name of the LinkedListIterator class. 8. The linked list iterator described in the textbook maintains a reference to the last visited node, called position, and a reference to the last node before that, called previous. Which of the following statements is NOT correct regarding advancing this iterator? Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch16 a. If another node exists, when the iterator is to be advanced, the position reference must be updated to position.next. b. If the iterator currently points before the first element of the list, when the iterator is to be advanced, position must be set to point to the first node in the linked list. c. If another node exists, when the iterator is to be advanced, the previous reference must be updated to point to the current location of the iterator d. If the iterator currently points before the first element of the list, when the iterator is to be advanced, the position reference must be set to position.next and the previous reference must be set to point to the first node in the linked list. 9. Which of the following statements about a linked list iterator is NOT correct? a. The iterator is at the end of the list if the linked list's first node reference is null. b. The iterator is at the end of the list if the position.next reference is null. c. The iterator is at the end of the list if the position reference is null. d. The list is empty if the linked list's first node reference is null. 10. Using the textbook's implementation of a singly linked list and linked list iterator, the following steps are required to remove a node from the middle of a linked list. Place these steps into the order in which they should be performed. I The preceding node's next reference must be updated to skip the removed node. II The iterator's position reference must be set to the previous reference. III The previous reference must be checked to see if it is equal to the position reference. a. III, I, II b. I, III, II c. II, I, III d. III, II, I 11. When using the textbook’s implementation of a singly linked list to remove an element in the middle of the list, why it is necessary to check whether the previous reference equals the position reference? a. If previous equals position, the action does not follow a call to next. b. If previous equals position and an attempt is made to remove the node, the iterator would have to start at the beginning of the list to rebuild the links. c. If previous equals position, the iterator is at the beginning of the list and does not point to a valid node. d. If previous equals position, the iterator is at the end of the list and does not point to a valid node. 12. Consider the following code snippet:

LinkedList<String> words = new LinkedList<String>(); words.addFirst("xyz"); words.addLast("jkl"); words.addLast("def"); System.out.print(words.removeFirst()); System.out.print(words.removeLast()); System.out.print(words.removeLast()); What does this code print? a. xyzjkldef Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch16 b. defxyzjkl c. xyzdefjkl d. defjklxyz 13. Using the textbook's implementation of a linked list, which of the following statements about changing the data stored in a previously visited element is correct? a. The node that will be updated is the most recently visited node. b. The position.next reference must be updated when the data is updated. c. The set method can be called again immediately after calling the add method. d. The previous reference must be updated when the node is updated. 14. Assume that the linked list implementation includes a reference to the last node as well as to the first node. Which of the following statements about the efficiency of the linked list is correct? a. Adding an element to the middle of the linked list at the current position of the iterator is O(n). b. Removing an element other than the last element from the linked list at the current position of the iterator is O(n). c. Accessing an element in the linked list using an iterator is O(n). d. Adding an element to the end of the linked list is O(1). 15. Assume that the linked list implementation includes a reference to the last node as well as to the first node. Which of the following statements about the efficiency of a singly linked list is NOT correct? a. Adding an element to the middle of a linked list using an iterator is O(1). b. Removing the last element from a linked list using an iterator is O(1). c. Accessing an element in a linked list using an iterator is O(n). d. Adding an element to the end of a linked list is O(1). 16. Which of the following operations is least efficient in a LinkedList? a. Adding an element in a position that has already been located b. Linear traversal step c. Removing an element when the element's position has already been located d. Random access of an element 17. Which of the following algorithms would be efficiently executed on a LinkedList? a. Tracking paths in a maze b. Binary search c. Remove first n / 2 elements from a list of n elements d. Read n / 2 elements in random order from a list of n elements 18. What type of access does the use of an iterator with a LinkedList provide for its elements? a. Sequential b. Semi-random c. Random d. Sorted 19. Adding or removing an element at an arbitrary iterator position in a singly linked list of length n takes ____ time. Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch16 a. O(n) b. O(log n) c. O(1) d. O(n2) 20. If we want a create a doubly-linked list data structure so that we can move from a node to the next node as well as to a previous node, we need to add a previous reference to the Node class. Each such DNode (doubly-linked Node) will have a data portion and two DNode references, next and previous. How many references need to be updated when we remove a node from the middle of such a list? Consider the neighboring nodes. a. 1 b. 2 c. 3 d. 4 21. If we want a create a doubly-linked list data structure so that we can move from a node to the next node as well as to a previous node we need to add a previous reference to the Node class. Each such DNode (doubly-linked Node) will have a data portion and two DNode references, next and previous. How many references need to be updated when we remove a node from the beginning of a list with many nodes? Consider the first reference and neighboring node(s). a. 1 b. 2 c. 3 d. 4 22. In a linked list data structure, when does the reference to the first node need to be updated? I inserting into an empty list II deleting from a list with one node III deleting an inner node a. I b. II c. I and II d. III 23. Suppose we maintain a linked list of length n in sorted order. What would be the big-Oh notation for the add operation? a. O(1) b. O(n) c. O(n log n) d. O(n2) 24. Suppose we maintain two linked lists of length n in sorted order. What would be the big-Oh notation for the creating a third list, which included only elements common to both lists? a. O(1) b. O(n) c. O(n log n) Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch16 d. O(n2) 25. Suppose we maintain two linked lists of length n in random element order. What would be the big-Oh notation for the creating a third list that includes only elements common to both lists, without sorting the first two lists? a. O(1) b. O(n) c. O(n log n) d. O(n2) 26. Suppose we maintain a linked list of length n in random element order. What would be the big-Oh notation for an algorithm that prints each list element and the number of times it occurs in the list (without sorting the list)? a. O(1) b. O(n) c. O(n log n) d. O(n2) 27. Suppose we maintain a linked list of length n in random element order. What would be the big-Oh notation for printing out those elements which occur exactly once in the list (without sorting the list)? a. O(1) b. O(n) c. O(n log n) d. O(n2) 28. Suppose we maintain a linked list of length n in sorted order. What would be the big-Oh notation for printing out those elements that occur exactly once in the list? a. O(1) b. O(n) c. O(n log n) d. O(n2) 29. A doubly-linked list requires that each node maintain two references, one to the next node and one to the previous node. Which of the following statements about a doubly-linked list is NOT correct? a. If a node's next reference is null, it is at the end of the list. b. To remove a node in the middle of the list, the previous node's next reference must be updated. c. To add a node in the middle of the list, you must update the next reference of the node after which the new node will be added. d. To remove a node in the middle of the list, the previous node's previous reference must be updated. 30. Which of the following actions must be taken to remove a node X from the middle of a doubly-linked list? I Update the next reference in the node before X II Update the previous reference in the node after X III Update the list's first reference a. I b. II Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch16 c. I and II d. II and III 31. Which of the following actions must be taken to add a node X at the end of a doubly-linked list? I Update the next reference in the node before the position where X will be placed II Update the previous reference in the node before the position where X will be placed III Update the list's last reference a. I b. II c. I and II d. I and III 32. Using the textbook's implementation of a linked list, what is the purpose of declaring the Node class to be a static inner class? a. To create an outer-class reference. b. To create a this reference to itself. c. To prevent storage of an outer-class reference that is not needed. d. To create an outer-class reference that is needed. 33. Using the textbook's implementation of a linked list, why is the LinkedListIterator inner class NOT declared as an inner static class? a. Because the LinkedList class must have access to the instance variables of the LinkedListIterator class. b. Because the Node class must have access to the instance variables of the LinkedListIterator class. c. Because the LinkedListIterator class must have access to Node class instance variables. d. Because the LinkedListIterator class must have access to LinkedList class instance variables. 34. What is never present in a static inner class? a. an outer-class reference. b. the this reference to itself. c. static properties. d. static methods. 35. Given the partial LinkedList class declaration below, select a statement to complete the printFirst method, which is designed to display the contents of the first list element.

public class LinkedList { class Node { public Object data; public Node next; } private Node first; . . . Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch16

public void printFirst() { _____________________________ } } a. System.out.println(first); b. System.out.println(first.data); c. System.out.println(first.next); d. System.out.println(Node.data); 36. Given the partial LinkedList class declaration below, select an expression to complete the empty method, which is designed to return true if the list contains no elements.

public class LinkedList { class Node { public Object data; public Node next; } private Node first; . . . public boolean empty() { return ________________________ ; } } a. first != null b. first == null c. first.data == null d. first.next == null 37. Given the partial LinkedList class declaration below, select a statement to complete the size method, which is designed to return the number of list elements.

public class LinkedList { class Node { public Object data; public Node next; } private Node first; Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch16

. . . public int size() { int count = 0; Node temp = first; while (temp != null) { count++; _____________________ } return count; } } a. temp = temp.next; b. temp = first.next; c. first = temp.next; d. first = first.next 38. Given the partial LinkedList and LinkedListIterator class declarations below, select an expression to complete the get(index) method of the LinkedList class, which returns the element at the position indicated by index. You can assume that the method is only called when the index is less than the size of the linked list.

public class LinkedList { . . . public ListIterator listIterator() { return new LinkedListIterator(); } class LinkedListIterator implements ListIterator { private Node position; private Node previous; private boolean isAfterNext; public LinkedListIterator() { . . . } public Object next() { . . . } public boolean hasNext() Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch16

{ . . . } } public Object get(int index) { ListIterator it = listIterator(); for (int i = 0; i < index; ++i) { it.next(); } return ________________________ ; } } a. it.next() b. it.previous c. it.position d. it.next().data 39. What is a difference between a singly-linked list and a doubly-linked list? a. A singly linked list node has a reference to the previous node. b. A doubly linked list node has a reference to the previous node. c. A singly linked list node has a reference to the next node. d. A doubly linked list node has a reference to the next node. 40. Which of the following statements are true about the Node class? I The instance variables are private II It holds a reference first to the first node III It is a private inner class of the LinkedList class a. I b. II c. III d. All of the above 41. In the textbook implementation of the LinkedListIterator class, when updating the position, what happens if the iterator tries to point before the first element of the list? a. The position is set to position.next b. The position is set to null c. The position is set to first d. The position is set to previous 42. Using the textbook's implementation of a linked list, which of the following statements about adding a node to the middle of a linked list is correct? a. The new node will be added before the last visited node. Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch16 b. The position.next reference will be updated to point to the new node. c. The remove method can be called immediately before or after adding the new node. d. The previous reference must be updated when adding the new node. 43. Using the textbook's implementation of a linked list, which of the following statements about managing nodes within a linked list using an iterator is correct? a. The node that will be removed is the node pointed to by the position.next reference. b. The set method can be called immediately after adding a new node using the add method. c. The set method can be called immediately after removing an existing node using the remove method. d. The position reference must be updated when a new node is added. 44. Given the partial ArrayList class declaration below, select an expression to complete the empty method, which is designed to return true if the list contains no elements.

public class ArrayList { private Object[] elements; private int currentSize; public ArrayList() { final int INITIAL_SIZE = 10; elements = new Object[INITIAL_SIZE]; currentSize = 0; } public boolean empty() { return ________________________ ; } } a. elements.length == 0 b. elements.currentSize == 0 c. elements[0] == null d. currentSize == 0 45. Given the partial ArrayList class declaration below, select an expression to complete the contains method, which is designed to return true if the element is contained within the list.

public class ArrayList { private Object[] elements; private int currentSize; public ArrayList() { Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch16

final int INITIAL_SIZE = 10; elements = new Object[INITIAL_SIZE]; currentSize = 0; } public boolean contains(Object item) { for (int i = 0; ________________ ; i++) { if (elements[i].equals(item)) { return true; } } return false; } ... } a. i < currentSize b. i <= currentSize c. i < elements.length d. i <= elements.length 46. An array list maintains a reference to an array of elements called a ____. a. buffer b. tree map c. hash table d. bucket 47. Reading or writing an array list element at an arbitrary index takes ____ time. a. O(log (n)) b. O(n) c. O(n2) d. O(1) 48. Suppose we maintain an array A of n int values as follows:

A[0] < A[1] < . . . < A[i] > A[i + 1] > A[i + 2] > . . . > A[n - 1] The ith element is the maximum in the array. What would be the lowest big-Oh notation for finding that element? Consider a variation of the binary search. a. O(1) b. O(log n) c. O(n) d. O(n2) Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch16 49. What feature of the ArrayList class makes it much better for a binary search than the LinkedList class? a. indexing b. has no link references c. it is a generic class d. it is an abstract class 50. Array lists and linked lists both have the same ____. a. add/remove efficiency b. concrete implementations c. random element access efficiency d. linear traversal step efficiency 51. Adding or removing an arbitrary element in the middle of an array list takes ____ time. a. O(n) b. O(1) c. O(log(n)) d. O(n2) 52. On average, how many elements of an array list of size n need to be moved when an element is added? a. n b. n2 c. 2n d. n / 2 53. If the current size of an array list is less than the length of the buffer, adding an element at the end of an array list takes ____ time. a. O(n) b. O(1) c. O(log(n)) d. O(n2) 54. When the buffer for an array list must be grown, a single reallocation operation takes ____ time. a. O(n) b. O(1) c. O(log(n)) d. O(n2) 55. When considering the reallocation operation for a list whose buffer is full, on average it will take ____ time. a. O(n) b. O(1) c. O(1)+ d. O(n2) Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch16 56. Which of the following statements about array list and doubly-linked list operations is correct? a. It is more efficient to add an element in the middle of an array list than a doubly-linked list. b. It is more efficient to add an element to the beginning of an array list than a doubly-linked list. c. It is more efficient to remove an element in the middle of an array list than a doubly-linked list. d. It is more efficient to retrieve an element in the middle of an array list than a doubly-linked list. 57. An iterator is currently pointing to the correct location for insertion or removal of a doubly-linked list. Which of the following statements about doubly-linked list operations is correct? a. The most expensive operation of a doubly-linked is to add an element at the end. b. The most expensive operation of a doubly-linked is to remove an element at the end. c. The most expensive operation of a doubly-linked is to add an element in the middle. d. The most expensive operation of a doubly-linked is to add an element at the front. 58. Linked list operations that were studied included adding/removing an element at the end or in the middle, and retrieving the kth element. If the iterator is currently pointing to the correct location for insertion or removal, which of the following statements about these doubly-linked list operations is correct? a. The most expensive operation of a doubly-linked list is to add an element at the end. b. The most expensive operation of a doubly-linked list is to remove an element at the end. c. The most expensive operation of a doubly-linked list is to add an element in the middle. d. The most expensive operation of a doubly-linked list is to retrieve an arbitrary element. 59. Linked list operations that were studied included adding/removing an element at the end or in the middle, and retrieving the kth element. If the iterator is currently pointing to the correct location for insertion or removal, which of the following statements about these doubly-linked list operations is correct? a. The least expensive operation of a doubly-linked list is to iterate over the list. b. The least expensive operation of a doubly-linked list is to retrieve an arbitrary element. c. The least expensive operation of a doubly-linked list is to add an element in the middle. d. All of these operations have the same time cost. 60. Which of the following is true about the efficiency of inserting an element into an array list? a. It always has O(n) efficiency b. When the insertion happens before the last element, it is O(1) c. When the insertion happens on the last element, it is O(n) d. When the insertion happens after the last element, it is O(1) 61. How do you symbolize amortized big-Oh time? a. O() b. O()+ c. O()* d. O()" 62. Which operations from the array list data structure could be used in the implementation of the push and pop operations of a stack data structure? I addLast II addFirst Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch16 III removeFirst a. I and III b. I and II c. II and III d. None of the above 63. Which of the following operations from the array list data structure could be used in the implementation of the push and pop operations of a stack data structure? I addLast II addFirst III removeLast a. I b. II c. I and III d. II and III 64. Complete the following code, which is intended to add an element to the top of a stack implemented as a linked list.

Node newNode = new Node(); newNode.data = element; _________________ _________________ a. first = newNode;

newNode.next = first; b. newNode.next = first; first = newNode; c. newNode.previous = first; first.next = newNode; d. first = newNode; newNode.previous = first;

65. A stack can be implemented as a sequence of nodes in a linked list or an array list. Which of the following statements about this is correct? a. If implementing the stack as a linked list, the least expensive approach is to add and remove elements at the end. b. If implementing the stack as an array list, the least expensive approach is to add and remove elements at the end. c. If implementing the stack as an array list, there is no cost difference whether adding and removing elements at the beginning or the end. d. If implementing the stack as a linked list, there is no cost difference whether adding and removing elements at the beginning or the end. 66. A stack can be implemented as a sequence of nodes in a linked list or an array list. Which of the following statements about this is correct? a. If implementing the stack as a linked list, it is more expensive to add and remove elements at the end than at the beginning. b. If implementing the stack as an array list, it is more expensive to add and remove elements at the end than at Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch16 the beginning. c. If implementing the stack as an array list, there is no cost difference whether adding and removing elements at the beginning or the end. d. If implementing the stack as a linked list, there is no cost difference whether adding and removing elements at the beginning or the end. 67. When implementing a queue as a singly-linked list, which of these statements is correct? a. For better efficiency, nodes should be added at the back and removed at the front. b. For better efficiency, nodes should be added at the front and removed at the back. c. There is no difference in efficiency whether nodes are added at the front and removed at the back, or added at the back and removed at the front. d. You cannot effectively implement a queue as a singly-linked list. 68. You have implemented a queue as a singly-linked list, adding elements at the end and removing elements at the front. What is the cost of the add operation? a. O(log n) b. O(n) c. O(n2) d. O(1) 69. You have implemented a queue as a singly-linked list, adding elements at the end and removing elements at the front. What is the cost of the remove operation? a. O(log(n)) b. O(n) c. O(n2) d. O(1) 70. Given the ArrayStack class implementation discussed in section 16.3 (partially shown below), select the statements needed to complete the push method.

public class ArrayStack { private Object[] elements; private int currentSize; public ArrayStack() { final int INITIAL_SIZE = 10; elements = new Object[INITIAL_SIZE]; currentSize = 0; } public void push(Object element) { growIfNecessary(); ________________ Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch16

________________ } } a. elements[currentSize] = element;

currentSize++; b. currentSize++; elements[currentSize] = element; c. elements[currentSize - 1] = element; currentSize++; d. elements[currentSize + 1] = element; currentSize++;

71. Given the LinkedListStack class implementation discussed in section 16.3 (partially shown below), select the statement(s) to complete the peek method.

public class LinkedListStack { private Node first; public LinkedListStack() { first = null; } public Object peek() { if (empty()) { throw new NoSuchElementException(); } _____________________________ } ... } a. Object value = first.data; first = first.next; return value; b. first = first.next; return first.data; c. return first;

d. return first.data; 72. Given the LinkedListQueue class implementation discussed in section 16.3 (partially shown below), select the appropriate statements to complete the add method.

public class LinkedListQueue { Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch16

private Node first; private Node last; public LinkedListQueue() { first = null; last = null; } public void add(Object newElement) { Node newNode = new Node(); newNode.data = newElement; newNode.next = null; if (last == null) { first = newNode; last = newNode; } else { _____________________ _____________________ } } ... } a. last.next = newNode.next; last = newNode; b. last.next = newNode; last = newNode; c. last = newNode; last.next = newNode; d. last = newNode; last.next = newNode.next;

73. Given the HashSet class implementation discussed in section 16.4 (partially shown below), select the statement needed to complete the clear method, which is designed to remove all elements from the set.

public class HashSet { private Node[] buckets; private int currentSize; public HashSet(int bucketsLength) { buckets = new Node[bucketsLength]; currentSize = 0; Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch16

} public void clear() { for (int j = 0; j < buckets.length; ++j) { ___________________________ } currentSize = 0; } ... } a. buckets[j] = 0; b. buckets[j] = new Node(); c. buckets[j] = null; d. buckets[j] = new LinkedList(); 74. Elements in a hash table are said to ____ when they have the same hash code value. a. be equivalent b. compress c. collide d. buffer well 75. A hash function is considered good if it ____. a. does not require compression. b. detects duplicate elements. c. results in low integer values. d. minimizes collisions. 76. Which of the following statements about hash tables is correct? a. The hash code is used to determine where to store each element. b. Elements in the hash table are sorted in hash code order. c. A hash table allows duplicate elements. d. No two elements of a hash table can have the same hash code. 77. Assume that you have a hash table in which there are few or no collisions. What is the time required to locate an element in this hash table? a. O(log n) b. O(n) c. O(n2) d. O(1) 78. In the separate chaining technique for handling collisions in a hash table, ____. a. colliding elements are stored in a nested hash table. Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch16 b. colliding elements are placed in empty locations in the hash table. c. colliding elements are stored in linked lists associated with the hash code. d. the hash code is compressed to obtain unique hash codes. 79. In the open addressing technique for handling collisions in a hash table, ____. a. colliding elements are stored in a nested hash table. b. colliding elements are placed in empty locations in the hash table. c. colliding elements are stored in linked lists associated with the hash code. d. the hash code is compressed to obtain unique hash codes. 80. Complete the following code snippet, which is intended to compress a hash code for an element x to become a valid array index:

int h = x.hashCode(); if (h < 0) { h = -h; } _______________ a. position = arrayLength % h; b. position = arrayLength / h; c. position = h / arrayLength; d. position = h % arrayLength; 81. Complete the following code snippet, which is intended to compress a hash code for an element x to become a valid array index:

_____________________ if (h < 0) { h = -h; } position = h % arrayLength; a. double h = x.hashCode(); b. double h = x.getHashCode(); c. int h = x.hashCode(); d. int h = x.getHashCode(); 82. Why is it not typical to use the hashCode method result directly as an index for array storage? I because the hashcode method returns a double II the values are potentially very large III the values are not type int a. I b. I and II c. I and III d. II 83. Consider the following code snippet, which computes h, the array index for storing x in a hash table.

int h = x.hashCode(); Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch16

if (h < 0) { h = -h; } h = h % size; What does size correspond to? a. The size of the hash table. b. The number of elements to be stored. c. The number of collisions. d. The index of an empty hash table slot. 84. What technique is used to store elements that hash to the same location? a. colliding b. bucketing c. deletion d. sharing 85. Assume that you have a hash table in which there are few or no collisions. What is the time required to remove an element from this hash table? a. O(n) b. O(n2) c. O(1) d. O(log (n)) 86. Which of the following statements about adding an element to a hash table is NOT correct? a. Add the new element at the beginning of the node sequence in the bucket referenced by the hash code. b. Check the elements in the bucket to determine if the new element already exists. c. If the element matches another element in the bucket referenced by the hash code, add the new element to that bucket. d. To add an element, its compressed hash code must be computed. 87. If your hashCode function returns a number anywhere in the hash table with equal probability, what is the likely result? a. Some objects will be impossible to find. b. The number of collisions will be high. c. The get method will run at O(n) complexity. d. The get method will run at O(1) complexity. 88. Which hash table method(s) will make use of the equals method? I put II get III contains a. I b. I and II c. III d. I, II and III Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch16 89. Which of the following statements about using iterators with hash tables is NOT correct? a. The iterator must track its position within a node chain in a bucket. b. The iterator must skip over empty buckets. c. Two iterators are required: one to traverse the buckets, and another to traverse the nodes within a bucket. d. The iterator must track the bucket number. 90. What is the time required to iterate over all elements in a hash table of size n? a. O(log(n)) b. O(n) c. O(n2) d. O(1) 91. Assume that you have a hash table in which there are an average number of collisions. What is the time required to remove an element from this hash table? a. O(n) b. O(n2) c. O(1) d. O(1)+ 92. Assume that you have a hash table in which there are an average number of collisions. What is the time required to find an element in this hash table? a. O(n) b. O(n2) c. O(1) d. O(1)+ 93. Assume that you have a hash table in which there are an average number of collisions. What is the time required to add an element to this hash table? a. O(n) b. O(n2) c. O(1) d. O(1)+ 94. Complete the following code, which is intended to add an element to a hash table. Assume that the computed and compressed hash code is stored in the variable h.

Node newNode = new Node(); newNode.data = x; _________________ _________________ a. newNode.next = buckets[h + 1]; buckets[h] = newNode; b. newNode.next = buckets[h]; buckets[h + 1] = newNode; Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch16 c. newNode.next = buckets[h]; buckets[h - 1] = newNode; d. newNode.next = buckets[h]; buckets[h] = newNode;

95. What type of access does the use of an iterator provide for the elements of a bucket in a hash table? a. sequential b. semi-random c. random d. sorted 96. The advantage of using the open addressing technique over the separate chaining technique for handling collisions in a hash table is that open addressing ____. a. allows for faster addition of elements b. allows for faster retrieval of elements c. is simpler in implementation d. requires less memory storage for the hash table 97. The ___ technique for handling collisions in a hash table with open addressing attempts to place colliding elements at the next available location in the hash table. a. sequential placement b. sequential probing c. linear placement d. linear probing 98. Which statement about handling collisions in a hash table using the open addressing technique is correct? a. A colliding element will always be contiguous to the location in which it would normally be placed. b. To find an element, you must search from the hash code location until a match or an element with a different hash code is found. c. To remove an element, you simply empty the slot at which you find it. d. There may be some elements with different hash codes that lie on the same probing sequence. 99. Which of the following statements about handling collisions in a hash table using the sequential chaining and open addressing techniques is NOT correct? a. The implementation of sequential chaining technique is simpler than the implementation of the open addressing technique. b. The sequential chaining technique is simpler to understand than the open addressing technique. c. The sequential chaining technique requires the storage of links while open addressing does not. d. The sequential chaining technique requires less memory use than open addressing. 100. Which statement about handling collisions in a hash table using the open addressing technique is NOT correct? a. A colliding element may not be contiguous to the location in which it would normally be placed. b. To find an element, you must search from the hash code location until a match or an empty slot is found. c. To remove an element, you simply empty the slot at which you find it. d. There may be some elements with different hash codes that lie on the same probing sequence. Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch16 101. What are Collisions in computer science? a. Identical hash codes for different objects b. Attempting to assign a list as a map c. When an iterator points into the middle of a node chain d. A NullPointerException 102. Why must compression be applied to hash code? a. There is no hash code without compression b. The array is too large to hold all possible integer index positions c. There is no collision without compression d. To increase likelihood of data being put in a bucket 103. One way to handle collisions in a hash table is a method called separate chaining. What does separate chaining do? a. Colliding elements are collected in a list of elements with the same position value b. A "bucket" is used to hold the collided hash codes and redistribute new hash codes c. Colliding elements are place in empty locations of the hash table d. When two elements collide, only the most recently inserted element is kept

Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch16 Answer Key 1. d 2. c 3. b 4. b 5. a 6. d 7. c 8. d 9. c 10. a 11. a 12. c 13. a 14. d 15. b 16. d 17. c 18. a 19. c 20. b 21. b 22. c 23. b 24. b 25. d Powered by Cognero

Page 25


Name:

Class:

Date:

testbank-bj-7-ch16 26. d 27. d 28. b 29. d 30. c 31. d 32. c 33. d 34. a 35. b 36. b 37. a 38. a 39. b 40. c 41. c 42. b 43. d 44. d 45. a 46. a 47. d 48. b 49. a 50. d 51. a Powered by Cognero

Page 26


Name:

Class:

Date:

testbank-bj-7-ch16 52. d 53. b 54. a 55. c 56. d 57. c 58. d 59. c 60. d 61. b 62. c 63. c 64. b 65. b 66. a 67. a 68. d 69. d 70. a 71. d 72. b 73. c 74. c 75. d 76. a Powered by Cognero

Page 27


Name:

Class:

Date:

testbank-bj-7-ch16 77. d 78. c 79. b 80. d 81. c 82. d 83. a 84. b 85. c 86. c 87. d 88. d 89. c 90. b 91. d 92. c 93. d 94. d 95. a 96. d 97. d 98. d 99. d 100. c 101. a 102. b Powered by Cognero

Page 28


Name:

Class:

Date:

testbank-bj-7-ch16 103. a

Powered by Cognero

Page 29


Name:

Class:

Date:

testbank-bj-7-ch17

Indicate the answer choice that best completes the statement or answers the question. 1. Which of the following statements about trees is NOT correct? a. The root of the tree does not have a parent. b. A tree is composed of nodes. c. A node can have multiple parents. d. A node can have multiple child nodes. 2. Consider the following tree diagram: a. H and M b. D and B c. D and U d. L and T 3. Consider the following tree diagram: a. C b. C and P c. C and X d. P and X 4. Consider the following tree diagram: a. C b. B c. B and H d. H 5. Consider the following tree diagram: a. R b. P c. C d. R and P 6. Consider the following tree diagram: a. R b. N c. M d. B 7. Consider the following tree diagram: a. C, N, and P b. B c. C and P d. N 8. Consider the following tree diagram: Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch17 a. P, L, T b. P, K, D c. P d. P, B 9. Consider the following tree diagram: a. R, H, X b. K, D, P c. C, R, N, X d. T, L, P, C 10. Consider the following tree diagram: a. H is a descendant of M b. N is a descendant of C c. L is a descendant of C d. N is a descendant of R 11. Consider the following tree diagram: a. C is an ancestor of N b. R is an ancestor of N c. D is an ancestor of P d. H is an ancestor of M 12. Consider the following tree diagram: a. Nodes H, M, and X form a subtree b. Nodes D and K form a subtree c. Nodes R and N form a subtree d. Nodes L and T form a subtree 13. Consider the following tree diagram: a. 7 b. 3 c. 6 d. 4 14. Consider the following tree diagram: a. 5 b. 7 c. 3 d. 4 15. Which of the following statements about trees is NOT correct? a. The height of a tree is based on the longest path from the root to a leaf. b. Many tree properties are computed with recursive methods. Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch17 c. A simple implementation of a Tree class uses an instance variable for the root node and a nested Node class, which stores the node's data and its children. d. A subtree rooted at node n is the tree formed by taking n as the root node and including all of its ancestors. 16. Consider the following tree diagram: a. 5 b. 6 c. 4 d. 13 17. Consider the following tree diagram: a. 3 b. 2 c. 4 d. 6 18. Consider the following tree diagram: a. 2 b. 4 c. 3 d. 6 19. Given the Node class (partially shown below), select an expression to complete the isLeaf method, which is designed to return true if the node is a leaf, false otherwise.

class Node { public Object data; public List<Node> children; . . . public boolean isLeaf() { return _______________; } } a. children.size() == 0 b. children.get(0) == null c. data == null d. root == null 20. Given the Node class (partially shown below), select a statement to complete the recursive method descendants, which is designed to return the number of descendants of a node.

class Node Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch17

{ public Object data; public List<Node> children; . . . public int descendants() { int num = 0; for (Node child : children) { _____________________________ } return num; } } a. num = num + child.descendants(); b. num = num + child.descendants() + 1; c. num = child.descendants(); d. num = num + child.children.size(); 21. The height of a tree can be obtained by recursively computing the heights of its subtrees, while keeping track of the height of the deepest subtree. Given the Node class (partially shown below), select an expression to complete the recursive method height, which is designed to return the height of the tree rooted at a node.

class Node { public Object data; public List<Node> children; . . . public int height() { int maxChildHeight = 0; for (Node child : children) { int childHeight = child.height(); if (childHeight > maxChildHeight) maxChildHeight = childHeight; } return _________________; } } a. maxChildHeight + 1 b. maxChildHeight + 2 c. maxChildHeight d. maxChildHeight + height() Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch17 22. Which of the following statements about binary trees is correct? a. Each node in a binary tree has at most two child nodes. b. If divided down the middle from top to bottom, a binary tree must be symmetrical. c. Each node in a binary tree has at least two child nodes. d. The number of child nodes for each node in a binary tree is any power of two. 23. Consider the following tree diagrams: a. Neither I nor II b. II only c. I only d. Both I and II 24. Which of the following is NOT an example of a binary tree? a. A decision tree where each interior node contains a question and the two subtrees correspond to a yes or no answer. b. An expression tree that shows the order of evaluation in an arithmetic expression. c. The family tree of a person, which includes all descendants of a person. d. A Huffman tree where the left and right turns on the paths to the leaves describe binary encodings. 25. Consider the following Huffman encoding tree: a. 010 b. 001 c. 011 d. 000 26. Consider the following Huffman encoding tree: a. 10 b. 001 c. 010 d. 100 27. Consider the following tree diagram: a. 2 * 3 + 5 + 4 * 6 – 1 b. 2 * (3 + 5 + 4) * (6 – 1) c. [(2 * 3) + 5 + 4] * (6 – 1) d. 2 * 3 + 5 + 4 – 6 – 1 28. Consider the following tree diagram: a. (2 + 3) + (5 * 4) * 6 * (– 1) b. [(2 + 3) + (5 * 4)] * (6 – 1) c. 2 + 3 + 5 * 4 – 6 – 1 d. (2 + 3) * (5 * 4) * (6 – 1) 29. Consider the following tree diagrams: a. I only Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch17 b. Both I and II c. Neither I nor II d. II only 30. Consider the following tree diagrams: a. Neither I nor II b. Both I and II c. II only d. I only 31. Consider the following tree diagrams: a. Both I and II b. I only c. Neither I nor II d. II only 32. You are using a tree to show the evaluation order of arithmetic expressions. Which of the following statements is NOT correct? a. Every level of the tree must contain an operator. b. Leaves contain numbers. c. The root contains an operator. d. Interior nodes contain operators. 33. Which of the following statements about balanced trees is NOT correct? a. For a given height, a balanced tree can hold more nodes than an unbalanced tree. b. In a balanced binary tree, each subtree has approximately the same number of nodes. c. In a balanced tree, all paths from the root to the leaves have approximately the same length. d. The efficiency of algorithms for balanced trees is better expressed using the size of the tree than the height of the tree. 34. Consider the following tree diagrams: a. II and III only b. I only c. I and II only d. I and III only 35. Consider the following tree diagrams: a. II only b. III only c. II and III only d. I only 36. A binary tree of height h can have up to ____ nodes. a. 2h + 1 Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch17 b. 2h + 1 c. 2h - 1 d. 2h- 1 37. The height h of a completely filled binary tree with n nodes is ____. a. h= log2(n + 1) b. h = log2(n) + 1 c. h = log2(n) - 1 d. h = log2(n – 1) 38. Consider a balanced binary tree with 520 nodes. The average length of all paths from the root to the leaves is approximately ____. a. 10 b. 12 c. 9 d. 13 39. A balanced binary tree with 260 nodes has a height of approximately ____. a. 13 b. 8 c. 12 d. 10 40. A completely filled binary tree with a height of 3 has ____ nodes. a. 12 b. 6 c. 7 d. 8 41. A completely filled binary tree with a height of 4 has ____ nodes. a. 16 b. 12 c. 8 d. 15 42. If the child references of a binary tree node are both null, the node is ____. a. a parent node b. a leaf node c. an interior node d. a root node 43. If both of the child references of a binary tree node are non-null, it follows that the node must be ____. a. a child node Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch17 b. the root node c. a leaf node d. an interior node 44. Given the BinaryTree class (partially shown below), select an expression to complete the static recursive helper method rightMostValue, which is designed to return the data value in the rightmost node of the tree rooted at node n.

public class BinaryTree { private Node root; public BinaryTree() { root = null; } public BinaryTree(Object rootData, BinaryTree left, BinaryTree right) { root = new Node(); root.data = rootData; root.left = left.root; root.right = right.root; } class Node { public Object data; public Node left; public Node right; } public Object rightMostValue() { if (root == null) { return null; } else { return rightMostValue(root); } } public static Object rightMostValue(Node n) { if (n.right == null) { return n.data; Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch17

} else { return ______________________; } } } a. rightMostValue(n.left) b. rightMostValue(root.right) c. rightMostValue(n) d. rightMostValue(n.right) 45. Given the BinaryTree class (partially shown below), select an expression to complete the static recursive helper method countLeaves, which returns the number of leaf nodes in the binary tree rooted at node n.

public class BinaryTree { private Node root; public BinaryTree() { root = null; } public BinaryTree(Object rootData, BinaryTree left, BinaryTree right) { root = new Node(); root.data = rootData; root.left = left.root; root.right = right.root; } class Node { public Object data; public Node left; public Node right; } public int countLeaves() { return countLeaves(root); } public static int countLeaves (Node n) { if (n == null) Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch17

{ return 0; } else if (_____________________) { return 1; } else { return countLeaves(n.left) + countLeaves(n.right); } } } a. n.right == null b. n.left == null || n.right == null c. n.left == null d. n.left == null && n.right == null 46. In a binary search tree, where the root node data value = 45, what do we know about the data values of all the descendants in the left subtree of the root? a. all will be < 45 b. some values will be < 45, but there may be a few values > 45 c. approximately half the values are < 45, the other half are > 45 d. the root’s left child value < 45, but the right child of the root’s left child value is > 45 47. In a binary search tree, where the root node data value = 45, what do we know about the values of all the descendants in the right subtree of the root? a. some values will be > 45, but there may be a few values < 45 b. all will be > 45 c. the root’s right child value > 45, but the left child of the root’s right child key is < 45 d. approximately half the values are < 45, the other half are > 45 48. Consider the following tree diagrams: a. Neither I nor II b. I only c. Both I and II d. II only 49. Consider the following tree diagrams: a. Neither I nor II b. I only c. II only d. Both I and II 50. Consider the following binary search tree diagram: Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch17 a. H, D, and A b. H and D only c. H only d. H, D, and F 51. Consider the following binary search tree diagram: a. H only b. H and D only c. H, D, and A d. H, D, and F 52. Consider the following binary search tree diagram: a. III b. IV c. II d. I 53. Consider the following binary search tree diagram: a. II b. I c. IV d. III 54. Consider the following addNode method for inserting a newNode into a binary search tree:

public void addNode(Node newNode) { int comp = newnode.data.compareTo(data); if (comp < 0) { if (left == null) {left = newNode;} else { left.addNode(newNode); } } else { if (right == null) {right = newNode;} else { right.addNode(newNode); } } } Which of the following sequences of insertions will result in a balanced tree? In each sequence, the first node inserted becomes the root of the tree on which the addNode method is called for the subsequent insertions. I 12, 7, 25, 6, 9, 13, 44 II 12, 7, 25, 44, 13, 6, 9 III 12, 25, 44, 13, 6, 9, 7 a. I and II only Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch17 b. I only c. II only d. I and III only 55. Consider the following binary search tree diagram: a. X b. N c. M d. L 56. Consider the following binary search tree diagram: a. Replace M with L. b. Replace M with N. c. Replace M with X. d. Replace M with F. 57. Consider the following binary search tree diagram: a. Modify D to have a null right reference. b. Move C into the right subtree of D. c. Replace F with D’s value and replace D with C’s value. d. Move C into the left subtree of A. 58. Consider the following binary search tree diagram: a. Modify V’s right reference to point to X. b. Modify V to have a null right pointer. c. Modify V’s left reference to point to X. d. Swap the values in V and X, and modify X’s right reference to point to V. 59. Consider the following binary search tree diagram: a. Swap the values in C and D so that C has A as its left child, then remove the new D node. b. Modify K to point to A as its left child, and modify A to point to F as its right child. c. Modify K to make its left child null. d. Modify K to point to F as its left child and modify F to point to A as its left child. 60. Which of the following statements about a binary search tree is correct? a. You can specify an insert position for inserting a node in the tree. b. Locating an element in a balanced binary search tree takes O(n) time. c. The speed of inserting or removing a node is dependent on the shape of the tree. d. Adding elements that are already sorted will result in a balanced binary search tree. 61. Locating an element in a balanced binary search tree takes ____ time. a. O(1) b. O(log(n)) c. O(n2) Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch17 d. O(n) 62. Adding an element to a balanced binary search tree takes ____ time. a. O(log (n)) b. O(1) c. O(n2) d. O(n) 63. Removing an element from a balanced binary search tree takes ____ time. a. O(1) b. O(log (n)) c. O(n2) d. O(n) 64. Locating an element in an unbalanced binary search tree takes ____ time. a. O(n) b. O(n2) c. O(1) d. O(log (n)) 65. Adding an element to an unbalanced binary search tree takes ____ time. a. O(n) b. O(1) c. O(log (n)) d. O(n2) 66. Removing an element from an unbalanced binary search tree takes ____ time. a. O(log (n)) b. O(n) c. O(1) d. O(n2) 67. Assuming that the variable t is instantiated to an empty BinarySearchTree, select a statement to complete the following code segment, so that the resulting binary search tree has a height of 4.

t.add("a"); t.add("day"); t.add("in"); __________________ t.add("life"); a. t.add("your"); b. t.add("the"); Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch17 c. t.add("his"); d. t.add("my"); 68. Given the BinarySearchTree and Node classes (partially shown below), select an expression to complete the recursive method smallest in the Node class. The method returns the smallest data value in the binary search tree rooted at a node.

public class BinarySearchTree { private Node root; public BinarySearchTree() {...} public void add(Comparable obj) {...} public Comparable smallest() { if (root == null) throw new NoSuchElementException(); else return root.smallest(); } class Node { public Comparable data; public Node left; public Node right; public Comparable smallest() { if (left == null) return data; else return _______________; } } } a. right.smallest() b. left.smallest() c. Math.min(left.smallest(), right.smallest()) d. data.smallest() 69. You wish to traverse a binary search tree in sorted order. Arrange the following actions in the correct order to accomplish this. I Print the right subtree recursively II Print the root Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch17 III Print the left subtree recursively a. I, II, III b. II, III, I c. III, I, II d. III, II, I 70. You wish to traverse a binary search tree using preorder traversal. Arrange the following actions in the correct order to accomplish this. I Print the right subtree recursively II Print the root III Print the left subtree recursively a. II, III, I b. II, I, III c. I, II, III d. III, I, II 71. You wish to traverse a binary search tree using postorder traversal. Arrange the following actions in the correct order to accomplish this. I Print the right subtree recursively II Print the root III Print the left subtree recursively a. III, II, I b. I, III, II c. III, I, II d. I, II, III 72. Which of the following statements about the three tree traversal schemes studied is correct? a. Inorder traversal is used for copying file directories. b. Postorder traversal is used for copying file directories. c. Postorder traversal is used for removing file directories by removing subdirectories first. d. Inorder traversal is used for evaluating arithmetic expression trees on a stack-based calculator. 73. Which of the following statements about the three tree traversal schemes studied is correct? a. Preorder traversal is used for evaluating arithmetic expression trees on a stack-based calculator. b. Postorder traversal is used for evaluating arithmetic expression trees on a stack-based calculator. c. Preorder traversal is used for removing file directories by removing subdirectories first. d. Postorder traversal is used for copying file directories. 74. Consider the following binary search tree: a. A, C, H, G, E, N, P, M, J b. J, E, M, C, G, P, A, H, N c. A, C, E, G, H, J, M, N, P d. J, E, C, A, G, H, M, P, N 75. Consider the following binary search tree: Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch17 a. J, E, M, C, G, P, A, H, N b. J, E, C, A, G, H, M, P, N c. A, C, H, G, E, N, P, M, J d. A, C, E, G, H, J, M, N, P 76. Consider the following binary search tree: a. J, E, C, A, G, H, M, P, N b. J, E, M, C, G, P, A, H, N c. A, C, E, G, H, J, M, N, P d. A, C, H, G, E, N, P, M, J 77. What are the differences between preorder, postorder, and inorder traversals? a. Postorder only visits the right subtree. b. The order of the root visit. c. Preorder only visits the left subtree. d. The order in which we visit the left and right subtrees. 78. If the postorder traversal of an expression tree is 8, 2, +, 5, /, what is the numeric result of that Reverse Polish Notation expression? a. 8 b. 2 c. 7 d. 15 79. If the postorder traversal of an expression tree is 8, 2, +, 5, /, what is the preorder traversal? a. /, +, 2, 8, 5 b. 8, +, 2, /, 5 c. /, +, 8, 2, 5 d. +, /, 8, 2, 5 80. If the postorder traversal of an expression tree is, 8, 2, +, 5, /, what is the result of an inorder traversal? a. +, /, 8, 2, 5 b. 8, +, 2, /, 5 c. /, +, 2, 8, 5 d. /, +, 8, 2, 5 81. Given the Visitor interface discussed in section 17.4 (shown below), select a statement to complete the class CodeFinder. The class is to be used when traversing a binary tree while displaying every data value that contains the code "007".

public interface Visitor { void visit(Object data); } Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch17

class CodeFinder implements Visitor { public void visit(Object data) { if (______________________________) { System.out.println(data); } } } a. data.toString().indexOf("007") > 0 b. data.equals("007") c. data.toString().indexOf("007") >= 0 d. data.contains("007") 82. Which of the following statements about breadth-first and depth-first traversal is NOT correct? a. Depth-first search goes deeply into the tree and then backtracks when it reaches the leaves. b. Breadth-first and depth-first search only work on a binary tree. c. Breadth-first search first visits all nodes on the same level before visiting the children. d. Depth-first search uses a stack to track the nodes that it visits. 83. Consider the following binary search tree: a. A, C, H, G, E, N, P, M, J b. A, C, E, G, H, J, M, N, P c. J, E, M, C, G, P, A, H, N d. J, E, C, A, G, H, M, P, N 84. Consider the following binary search tree: a. A, C, E, G, H, J, M, N, P b. A, C, H, G, E, N, P, M, J c. J, E, M, C, G, P, A, H, N d. J, E, C, A, G, H, M, P, N 85. Insert the missing code in the following code fragment. This fragment is intended to create an iterator and access the first element in a tree.

TreeSet<String> aTree = new TreeSet<>(); __________________________ String first = iter.next(); a. Iterator<String> iter = aTree.iterator(); b. Iterator<String> iter = aTree.iterator<String>(); c. Iterator<String> iter = String.iterator(); d. Iterator<TreeSet> iter = aTree.iterator(); Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch17 86. Which of the following is a correct statement about red-black trees? a. It is a balanced binary search tree that rebalances itself after each insertion or removal. b. The root is red. c. All child nodes of a black node must be red. d. All paths from root to null have the name number of red nodes. 87. Which of the following is NOT a property of a red-black tree? a. All paths from root to null have the name number of nodes. b. The root is black. c. All child nodes of a red node must be black. d. All nodes must be red or black. 88. Which of the following statements about inserting a node into a red-black tree is correct? a. If it is the first node, it must be red. b. If the parent of the new node is red, no other actions are required. c. Color the new node black. d. If a double-red situation results, you must correct this. 89. Which of the following statements about removing a node from a red-black tree is correct? a. Before removing a node in a red-black tree, turn it red and fix any double-black and double-red violations. b. If the node to be removed has a child, the child must be black. c. If the parent of the removed node is red, no other actions are required. d. If the node to be removed is a black leaf, just remove it. 90. What is the efficiency of locating an element in a red-black tree? a. O(n) b. O(n2) c. O(1) d. O(log (n)) 91. What is the efficiency of adding an element to a red-black tree? a. O(n2) b. O(n) c. O(log (n)) d. O(1) 92. What is the efficiency of removing an element from a red-black tree? a. O(log (n)) b. O(n2) c. O(1) d. O(n) 93. Which of the following statements about a heap is NOT correct? a. A heap is a form of binary tree. Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch17 b. The shape of a heap is very regular. c. A heap is always completely filled at all levels. d. In a heap, both the right and left subtrees of any node store elements that are at least as large as the node value. 94. A min-heap is a binary tree structure in which missing nodes may only occur where? a. bottom level, left side b. left child of the root c. bottom level, right side d. anywhere in the bottom two levels 95. If a min-heap has 15 nodes, what is known for certain? I every level of the tree is fully occupied II at least one level is missing a node III the root contains the smallest element a. I and III only b. II only c. II and III only d. I only 96. If a min-heap has 14 nodes, what is known for certain when we add a new node? I every level of the tree will be fully occupied II the tree does not grow a new level III the root contains the smallest element a. I only b. I and III only c. I and II only d. I, II and III 97. If a min-heap has 1024 nodes, what is its height? a. 10 b. 12 c. impossible to determine d. 11 98. When we map a min-heap with n elements to an array with n + 1 elements, we ignore array element 0, and place the root value at which array index? a. 2 b. n+1 c. n d. 1 99. When we map a min-heap with n elements to an array with n + 1 elements, the right child of the root is stored at which array index? a. 2 b. 1 Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch17 c. 3 d. 4 100. What is the complexity of adding an element to a heap? a. O(1) b. O(n2) c. O(log (n)) d. O(n log (n)) 101. What is the complexity of removing an element from a heap? a. O(n2) b. O(log(n)) c. O(n log (n)) d. O(1) 102. Which of the following statements about a heap is correct? a. A heap is a form of a binary search tree. b. When you traverse a heap in preorder, the nodes are in sorted order. c. The shape of a heap is irregular. d. The regular layout of a heap makes it possible to store heap nodes efficiently in an array. 103. Which of the following statements about the heapsort algorithm is correct? a. The heapsort sorts an array that is already sorted in O(n). b. The heapsort algorithm is based on inserting elements into a heap and removing them in sorted order. c. Each insertion and removal is O(n log(n)). d. The heapsort algorithm requires more space than the mergesort. 104. What is the efficiency of the heapsort algorithm? a. O(1) b. O(n2) c. O(n log (n)) d. O(log (n))

Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch17 Answer Key 1. c 2. b 3. d 4. b 5. c 6. a 7. c 8. b 9. a 10. a 11. c 12. c 13. d 14. a 15. d 16. d 17. a 18. d 19. a 20. b 21. a 22. a 23. b 24. c 25. b Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch17 26. a 27. c 28. b 29. a 30. a 31. d 32. a 33. d 34. c 35. b 36. d 37. a 38. c 39. b 40. c 41. d 42. b 43. d 44. d 45. d 46. a 47. b 48. b 49. d 50. a 51. d Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch17 52. d 53. a 54. a 55. c 56. b 57. a 58. a 59. d 60. c 61. b 62. a 63. b 64. a 65. a 66. b 67. c 68. b 69. d 70. a 71. c 72. c 73. b 74. c 75. b 76. d Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch17 77. b 78. b 79. c 80. b 81. c 82. b 83. c 84. d 85. a 86. a 87. a 88. d 89. a 90. d 91. c 92. a 93. c 94. c 95. a 96. d 97. d 98. d 99. c 100. c 101. b 102. d Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch17 103. b 104. c

Powered by Cognero

Page 25


Name:

Class:

Date:

testbank-bj-7-ch18

Indicate the answer choice that best completes the statement or answers the question. 1. Which of the following statements about generic programming is NOT correct? a. Generic programming can be achieved by using type parameters. b. Generic classes use type parameters to achieve genericity. c. To achieve genericity through inheritance, you must include type parameters to specify the type of object to be processed. d. Generic programming can be achieved by using inheritance. 2. Which of the following statements about generic programming is NOT correct? a. Type parameters can be instantiated with wrapper class types. b. Type parameters can be instantiated with class types. c. Type parameters can be instantiated with primitive data types. d. Type parameters can be instantiated with interface types. 3. Consider the following code snippet:

ArrayList<Coin> coins1 = new ArrayList<>(); //Line 1 LinkedList coins2 = new LinkedList(); //Line 2 coins1.add("my penny"); //Line 3 coins2.addFirst("my penny"); //Line 4 Which of the above lines will cause a compile-time error? a. Line 2 b. Line 3 c. Line 4 d. Line 1 4. Which of the following statements about using generic programming is NOT correct? a. Using type parameters will potentially avoid some class cast exceptions that may occur when using collections without type parameters. b. Using type parameters makes generic code easier to read and understand. c. Type parameters cannot be used with interfaces. d. Using type parameters makes generic code safer. 5. Consider the following code snippet:

ArrayList<Double> arr = new ArrayList<>(); String element = arr.get(0); Is there an error in this code? a. No run-time error or compile-time errors will occur. b. Yes, a compile-time error will occur because you cannot create an ArrayList of type Double. c. Yes, a run-time error will occur because a Double value cannot be cast to a String value. d. Yes, a compile-time error will occur because you cannot assign a Double value to a String variable. Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch18 6. Which Java technique(s) allows generic programming? I type variables II primitive types III inheritance a. I only b. I and III only c. III only d. II only 7. Which Java generic programming technique(s) requires the programmer to use casting to access variables stored as Object types? I type variables II primitive types III inheritance a. I and III only b. III only c. I only d. II only 8. Which is the purpose of the <E> element in the class declaration below?

public class Thing<E> { public Thing() { . . . } } a. declares that only instances of E class can be stored b. it is a type parameter c. it is a cast d. it is an instance variable 9. Consider the following code snippet:

public class Box<E> { private E data; public Box() { . . . } } Which of the following choices is a specific type of the generic Box class? a. Box<E> b. Box<int> c. Box<Double> d. Box 10. Consider the following code snippet: Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch18

public class Box<E> { private E data; public Box(){ . . . } } Which of the following is a valid Box<E> object instantiation? a. Box<E> box = new Box(); b. Box<Double> box = new Box<>(); c. Box<int> box = new Box<>; d. Box box = new Box<>(); 11. Consider the following code snippet:

public class Box<E> { private E data; public Box(){ . . . } public void insert(E value) { . . . } } Which of the following is a valid Box<E> object instantiation? I Box<Object> box = new Box<>(); II Box<Boolean> box = new Box<>(); III Box<double> box = new Box<>(); a. II and III only b. I and II only c. I and III only d. I only 12. Consider the following code snippet:

public class Box<E> { private E data; public Box() { . . . } public void insert(E value) { . . . } } What will result from executing the following code?

Box<Boolean> box = new Box<>(); box.insert("blue Box"); a. compile-time warning b. run-time error Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch18 c. compile-time error d. correct generic assignment 13. Consider the following code snippet:

public class Box<E> { private E data; public Box() { . . . } public void insert(E value) { . . . } public E getData() { . . . } } What will result from executing the following code?

Box<Boolean> box = new Box<>(); Box b = (Box) box.getData(); a. correct generic assignment b. run-time error c. compile-time warning d. compile-time error 14. Consider the following code snippet:

public class Box<E> { private E data; public Box(){ . . . } public void insert(E value) { . . . } public E getData() { . . . } } What will result from executing the following code?

Box<String> box = new Box<>(); . . . box.insert("blue Box"); String b = (String) box.getData(); a. correct, with necessary cast b. run-time error c. compiler error d. correct, but unnecessary cast 15. Consider the following code snippet: Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch18

public class Box<E> { private E data; public Box(){ . . . } public void insert(E value) { . . . } public E getData(){ . . . } } What will result from executing the following code?

Box<String> box = new Box<>(); . . . box.insert("blue Box"); String b = (Object) box.getData(); a. correct, with necessary cast b. compiler error c. correct, but unnecessary cast d. run-time error 16. Consider the following code snippet:

public class Box<E> { private E data; public Box() { . . . } public void insert(E value) { . . . } public E getData(){ . . . } } What will result from executing the following code?

Box<String> box = new Box<>(); . . . box.insert("blue Box"); String b = box.getData(); a. no error b. compiler warning c. run-time error d. compiler error 17. Consider the following code snippet:

public class Box<E> Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch18

{ private E data; public Box() { . . . } public void insert(E value) { . . . } public E getData(){ . . . } } What will result from the following code?

Box<String> box = new Box<>(); . . . box.insert("blue Box"); Double myDouble = (Double) box.getData(); a. compiler error b. correct, but unnecessary cast c. correct, with necessary cast d. run-time error 18. Consider the following code snippet:

public class Box<E> { private E data; public Box(){ . . . } public void insert(E value) { . . . } public E getData(){ . . . } } What specific exception will be thrown when the following code executes?

Box<String> box = new Box<>(); . . . box.insert("blue Box"); Double myDouble = (Double) box.getData();

a. ClassCastException b. Exception c. IndexOutOfBoundsException d. NoSuchElementException 19. Which of these Java library classes are implemented using type variables? I HashMap II LinkedList III ArrayList a. I, II and III Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch18 b. II and III only c. I and III only d. I and II only 20. In Java, generic programming can be achieved with ____. a. polymorphism b. arrays c. encapsulation d. inheritance 21. What is the best technique for overcoming the restriction for the use of primitives, such as int, in generic classes and methods? a. do not use generic methods when using primitives b. use String and decode values with a method such as Integer.parseInt c. use of wrapper classes d. use of the Object type 22. The type variables in HashMap<K, V> in the standard library mnemonically represent ____. a. kernel and vector b. String and Vector c. kind and variable d. key and value 23. Consider the following declaration:

LinkedList<String> list = new LinkedList<>(); This declaration implies that the LinkedList class could begin with which of the following code statements? I public class LinkedList<String> { . . . } II public class LinkedList<S> { . . . } III public class LinkedList<Element> { . . . } a. II only b. I only c. III only d. II and III only 24. Determine the correctness of the MyLinkedList generic class code below.

public class MyLinkedList<E> { private MyNode first; public E getFirst() { return first.data; } private class MyNode { Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch18

private E data; private MyNode next; } } a. the inner class MyNode cannot be private b. MyNode cannot refer to type variable E c. first.data will cause a compiler error d. the code is correct 25. Determine the output of the MyLinkedList generic class code below when the main method executes.

public class MyLinkedList<E> { private MyNode first; public MyLinkedList(E e) { first = new MyNode(); first.data = e; first.next = null; } public E getFirst() { return first.data; } private class MyNode { private E data; private MyNode next; } public static void main(String[] args) { MyLinkedList<String> list = new MyLinkedList<>("Hello"); System.out.println("List first element = " + list.getFirst()); } } a. compiler error is generated by first = new MyNode(); b. no output c. List first element = Hello d. List first element = null 26. An inner helper class, such as a TreeNode inside the generic BinaryTree class, must meet which of the following criteria? I be public II be private III be declared as generic Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch18 a. I and III only b. I, II and III c. II and III only d. none are necessary 27. Which of the following statements about generic methods is correct? a. The generic type parameter of a generic method designates the method's return type. b. A generic method must have a generic type parameter. c. When calling a generic method, you need to instantiate the type parameters. d. A generic method must reside in a generic class. 28. Which of the following statements about generic methods is NOT correct? a. Supply the type parameters of a generic method between the modifiers and the method return type. b. Generic methods can be static methods. c. You need not instantiate the type parameter when calling a generic method. d. You can replace type parameters with primitive types. 29. Select the correct header for this generic print method.

public static void print(E[] a) { for (int i = 0; i < a.length; i++) { System.out.println(a[i] + " "); } } a. The header is correct b. public void print(E [] a) c. public static <E> void print(E a) d. public static <E> void print(E[] a) 30. Consider the following code snippet:

public static <E> void print(E [] a) { for (int i = 0; i < a.length; i++) { System.out.println(a[i] + " "); } } int[] a = {3,6,5,7,8,9,2,3}; String[] s = {"happy","cat","silly","dog"}; Boolean[] b = {true, true, false}; Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch18 Which of the following are correct calls to this generic print method? I print(a); II print(s); III print(b); a. II and III only b. I and II only c. I, II and III d. I only 31. Consider the following code snippet:

public static <E> void print(E[] a) { for (int i = 0; i < a.length; i++) { System.out.println(a[i] + " "); } } int[] a = {3,6,5,7,8,9,2,3}; print(makeArray(a)); Assume that the method call to print(makeArray(a)) works correctly by printing the int array a. Which of the following headers for the makeArray method will make this possible? I public static Integer[] makeArray(int[] a) II public static E[] makeArray(int[] a) III public static Integer[] makeArray(E[] a) a. II and III only b. I and III only c. I and II only d. I only 32. Which argument type cannot be passed to generic methods? I Object II GUI components III primitive a. III only b. I only c. II only d. I and III only 33. Which of the following statements regarding restrictions for generic methods are true? I Generic methods must be declared inside a generic class. II Generic methods must be static. III Generic methods may only have one generic parameter. a. none are restrictions b. II and III only Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch18 c. I and II only d. I only 34. Consider our own generic class MyLinkedList shown below. It has a private Node class, and it implements the standard Java ListIterator generic interface.

public class MyLinkedList<E> { private MyNode first; . . . private class MyNode { private E data; private MyNode next; } private class MyIterator implements ListIterator<E> { . . . } } Which of the following statements apply? I the code is correct II change to private class MyIterator implements ListIterator III change to private class MyNode<E> a. II and III only b. II only c. III only d. I only 35. Which of the following headers for a generic method myMethod allows the actionPerformed method from the ActionListener class to be called? I public static <E extends ActionListener> E myMethod(E e) II public static <E implements ActionListener> E myMethod(E e) III public <E extends ActionListener> E myMethod(E e) a. I only b. I and III only c. III only d. II only 36. What is known for certain about a type parameter when a method constrains it as follows?

<E extends MouseListener & MouseMotionListener> a. it implements MouseListener and MouseMotionListener b. it is of type MouseEvent Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch18 c. the code is illegal; the & symbol should read and d. it is either a MouseListener or MouseMotionListener implementer 37. What is known for certain about Visualizer when a method constrains its type parameter as follows?

<E extends Visualizer> a. Visualizer can refer to either an interface or a class b. Visualizer must refer to a class c. Visualizer must refer to an interface d. Visualizer is another generic type 38. Consider the following code snippet that declares the GraduateStudent class:

public GraduateStudent extends Student { . .

.}

Which of these statements are false? I GraduateStudent is a subclass of Student II Stack<GraduateStudent> is a subclass of Stack<Student> III Stack<Student> is a subclass of Stack<GraduateStudent> a. I only b. III only c. II only d. II and III only 39. Given the following generic method, which of the following is a possible return type?

public static <E extends Comparable<E>> E max(E[] a) { . . . } I String II Object III Double a. I only b. I and III only c. II only d. I and II only 40. Given the following generic method, which of the following CANNOT be the return type?

public static <E extends Comparable<E>> E max(E[] a) { . . .} I String II Integer III double a. I only b. I and III only Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch18 c. III only d. II only 41. What does the following code snippet mean:

<E extends Comparable<E> & Measurable> a. The class represented by E extends Comparable and Measurable. b. The class represented by E implements Comparable and extends Measurable. c. The class represented by E extends Comparable and implements Measurable. d. The class represented by E implements Comparable and Measurable. 42. Consider the following code snippet:

public static <E extends Comparable<E>> E min(ArrayList<E> objects) What can we conclude about the return type of this method? a. The return type is a subclass of the ArrayList class. b. The return type is a class that implements Comparable. c. The return type is a class that extends Comparable. d. The return type is an array list of generic objects. 43. Consider the following class declaration:

public class SavingsAccount extends BankAccount { . . . } Which of the following statements about these classes is correct? a. ArrayList<BankAccount> is a subclass of ArrayList<SavingsAccount>. b. ArrayList<SavingsAccount> is a subclass of ArrayList<BankAccount>. c. There is no relationship between ArrayList<BankAccount> and ArrayList<SavingsAccount> d. ArrayList<SavingsAccount> extends ArrayList<BankAccount>. 44. Consider the following code snippet:

public class SavingsAccount extends BankAccount { . . . } public class CheckingAccount extends BankAccount { . . . } . . . SavingsAccount[] savingsAccounts = new SavingsAccount[100]; //Line 1 BankAccount[] bankAccounts = savingsAccounts; //Line 2 BankAccount myAccount = new CheckingAccount(); //Line 3 bankAccounts[0] = myAccount; //Line 4 Which of the following statements regarding this code is correct? a. Line 2 will cause a run-time error. b. Line 4 will cause a compile-time error. Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch18 c. Line 4 will cause a run-time error. d. Line 2 will cause a compile-time error. 45. Suppose a linked-list class called MyLinkedList with a generic E type has been instantiated with a java.awt.Component type variable. Consider its instance method locate with the following header:

public void locate(MyLinkedList<? extends E>) { . . . } Which type cannot be passed to method locate? I MyLinkedList<JButton> II MyLinkedList<Component> III MyLinkedList<JTextField> a. I only b. I and II only c. II and III only d. I, II, and III 46. Which code is the equivalent of the following method header? public static <E> void abc(Stack<E> stack) { . . . } I public static void abc(Stack<?> stack) { . . . } II public static <Object> void abc (Stack<Object> stack) { . . . } III public static void abc(Stack stack) { . . . } a. II only b. I only c. III only d. I and III only 47. Which of the following is not a wildcard type? a. ? sub B b. ? extends B c. ? super B d. ? 48. Which of the following satisfies the wildcard ? super Object? a. JComponent b. None satisfy this wildcard. c. Scanner d. String 49. Which of the following satisfies the wildcard ? extends Object? I String II JComponent III Scanner a. I and II only b. I only Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch18 c. II only d. I, II and III 50. Which of the following satisfies the wildcard ? extends Component? a. Scanner b. Color c. String d. JButton 51. What does it mean when the syntax ? extends D is used? a. Any subclass of D may be used. b. Any superclass of D may be used. c. This indicates a wildcard with an upper bound. d. Any subclass or superclass of D may be used. 52. What does it mean when the syntax ? super D is used? a. Any superclass of D may be used. b. This indicates a wildcard with a lower bound. c. Any subclass or superclass of D may be used. d. Any subclass of D may be used. 53. Consider the following code snippet in the LinkedList<E> class:

public void addAll(LinkedList<? extends E> other) { ListIterator<E> iter = other.listIterator(); while (iter.hasNext()) { add(iter.next()); } } Which of the following statements about this code is correct? a. For the element type of other, you must supply a type that is a subtype of E. b. For the element type of other, you must supply a type that is either a subtype or a supertype of E. c. You must supply a specific type for the element type of other. d. For the element type of other, you must supply a type that is a supertype of E. 54. Consider the following code snippet:

public static void reverse(List<?> list)

{ . . . }

Which of the following statements about this code is correct? a. This code is illegal. b. This is an example of a wildcard with an upper bound. Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch18 c. This is an example of a wildcard with a lower bound. d. This is an example of an unbounded wildcard. 55. Consider the following code snippet:

public static void reverse(List<? extends E> list)

{ . . . }

Which of the following statements about this code is correct? a. This code is illegal. b. This is an example of an unbounded wildcard. c. This is an example of a wildcard with an upper bound. d. This is an example of a wildcard with a lower bound. 56. Consider the following code snippet:

public static void reverse(List<? super E> list)

{ . . . }

Which of the following statements about this code is correct? a. This is an example of an unbounded wildcard. b. This is an example of a wildcard with a lower bound. c. This is an example of a wildcard with an upper bound. d. This code is illegal. 57. Consider the following code snippet:

public static void reverse(List<?> list)

{ . . . }

This method declaration is equivalent to which of the following declarations? a. public static <List> void reverse(List list) { . . . } b. public static void reverse(List<? extends E> list) { . . . } c. public static <D> void reverse(List<D> list) { . . . } d. public static void reverse(List<? super E> list) { . . . } 58. Which of the following statements about the Java virtual machine is correct? a. The Java virtual machine always replaces type parameters with their lower bounds. b. The Java virtual machine always replaces type parameters with their upper bounds. c. The Java virtual machine replaces type parameters with their bounds or with type Object. d. The Java virtual machine always replaces type parameters with type Object. 59. To maintain compatibility with pre-generic Java, type parameters are replaced by ordinary types called ____. a. raw types b. primitives c. generics d. Object 60. Erasure of types limits Java code somewhat with generics. Which of the following are limitations of generic code? Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch18 I cannot instantiate a type variable II cannot return a type variable III cannot pass a type variable a. I only b. II only c. II and III only d. III only 61. Consider the following code snippet:

public static <T> void fun(T[] t) { . . . } Erasure by the compiler of method fun will generate which result? a. public static void fun(Object[] t) { . . . } b. public static <T> void fun(Object[] t) { . . . } c. public static void fun(Object t) { . . . } d. public static <Object> void fun(Object t) { . . . } 62. Generics limit Java code somewhat. Which of the following are considered limitations of generic code? I cannot have an array of a generic type II cannot have primitive type variables III cannot construct an object of a generic type a. I only b. I, II and III c. II only d. III only 63. Which of the following necessitates the type erasure process? I The Java virtual machine does not work with generic types II To maintain backward compatibility to older versions of Java III Generics do not work with primitives a. II only b. I and III only c. I and II only d. I only 64. Suppose a generic method accepts a generic unconstrained argument p. What restrictions are placed on p by the compiler? a. There are no restrictions. b. Can only execute methods from its own class. c. Can only execute Object class methods. d. Can not execute any methods. 65. Which of the following are restrictions of Java generic programming? I You cannot use the assignment operator = to assign one generic object to another. II You cannot use the == operator to compare two generic objects. Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch18 III You cannot construct arrays of generic types. a. II only b. III only c. I only d. I and III only 66. Given the following declaration, what is the type parameter in Stack<E> replaced with?

private Stack myStack = new Stack(); a. String b. Object c. it is a compiler error d. int 67. Given the following declaration, what is the type parameter in Stack<E> replaced with?

private Stack<String> myStack = new Stack<>(); a. Object b. String c. Stack<String> d. int 68. Consider the following code snippet:

public interface MyInterface<E>

{ . . . }

public interface YourInterface<E, T> extends MyInterface<E> { . . . } Which of these are legal class declarations? I public class SomeClass implements YourInterface<String, Double> { . . . } II public class SomeClass implements YourInterface { . . . } III public class SomeClass implements YourInterface<String> { . . . } a. I and III only b. III only c. I only d. I and II only 69. If a class requires two generic type variables, how many can you legally provide in Java? I 0 II 1 III 2 a. I and II only b. I and III only c. I only Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch18 d. II only 70. Consider the following code snippet:

public static <E extends Measurable> E min(E[] objects) Which of the following represents the result of type erasure on this code? a. public static <Measurable E> E min(Measurable E[] objects) b. public static Measurable min(Measurable[] objects) c. This code is illegal and type erasure will not occur. d. public static Measurable E min(Measurable E[] objects) 71. Generics limit Java code somewhat. Which of the following are limitations of generic code? I cannot declare static variables of a generic type II cannot declare static methods of a generic type III cannot declare static inner classes of a generic type a. II only b. I only c. I and II only d. I, II, and III 72. Consider the following code snippet:

public class LinkedList<E> { private E defaultValue; public void add(E value, int n) { . . . } private static class Node { public E data; public Node next; } . . . } What is wrong with this code? a. Cannot declare the variable defaultValue as a generic type. b. Cannot pass a generic type as an argument to a method. c. Cannot have a static method in a generic class as shown. d. Cannot have a static inner class in a generic class as shown. 73. Consider the following code snippet:

public class LinkedList<E> { private static E defaultValue; public void add(E value, int n) { . . . } private class Node { public String data; public Node next;} . . . } Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch18 What is wrong with this code? a. Cannot pass a generic type as an argument to a method as shown. b. Cannot have an inner class in a generic class as shown. c. Cannot declare the variable defaultValue as a generic data type. d. Cannot declare the variable defaultValue as static. 74. Consider the following code snippet:

public class LinkedList<E> { private E defaultValue; public static List<E> replicate(E value, int n) { . . . } private class Node { public String data; public Node next;) . . . } What is wrong with this code? a. Cannot pass a generic type as an argument to a method. b. Cannot have a static method in a generic class as shown. c. Cannot have an inner class in a generic class. d. Cannot declare the variable defaultValue as a generic type. 75. Given an object myObject, which of the following represents the correct code to make a new instance of an object having the same class, assuming that the class has a constructor with no arguments? a. Object newObject = myObject.newInstance(); b. Object newObject = myObject.newInstance().getClass(); c. Object newObject = myObject.getClass(); d. Object newObject = myObject.getClass().newInstance(); 76. Given an array myArray, which of the following represents an expression to determine the type of the elements of the array? a. myArray.getClass().getComponentType() b. myArray.getComponentType().getClass() c. myArray.getClass().getElementType() d. myArray[0].getClass()

Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch18 Answer Key 1. c 2. c 3. b 4. c 5. d 6. b 7. b 8. b 9. c 10. b 11. b 12. c 13. d 14. d 15. b 16. a 17. d 18. a 19. a 20. d 21. c 22. d 23. d 24. d 25. c Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch18 26. d 27. b 28. d 29. d 30. a 31. d 32. a 33. a 34. d 35. b 36. a 37. a 38. d 39. b 40. c 41. d 42. b 43. c 44. c 45. d 46. b 47. a 48. b 49. d 50. d 51. a Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch18 52. a 53. a 54. d 55. d 56. c 57. c 58. c 59. a 60. a 61. a 62. b 63. c 64. c 65. b 66. b 67. b 68. d 69. b 70. b 71. d 72. d 73. d 74. b 75. d 76. a Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch18

Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch19

Indicate the answer choice that best completes the statement or answers the question. 1. Which statement about streams and stream processing is NOT correct? a. A stream stores its data values. b. A stream is an immutable sequence of values. c. Lambda expressions are often used in stream processing. d. A stream's values are processed lazily. 2. Complete the blanks in the following definition: A stream is a(n) __________ sequence of values that are processed _________. a. immutable ... eagerly b. mutable ... eagerly c. mutable ... lazily d. immutable ... lazily 3. You want to create a stream from an explicit specification of elements. Which method should you use? a. Collections.stream b. Stream.of c. Collections.of d. Stream.generate 4. Which statement creates a stream from an explicit specification of words? a. Stream<String> words = Stream.of("The","quick","brown","fox","jumped","over","the","lazy","dog"); b. Stream<String> words = Stream.of({"The","quick","brown","fox","jumped","over","the","lazy","dog"}); c. Stream<String> words = Stream.stream("The","quick","brown","fox","jumped","over","the","lazy","dog" ); d. Stream<String> words = Stream.of{"The","quick","brown","fox","jumped","over","the","lazy","dog"}; 5. Which statement creates a stream from an explicit specification of integers? a. Stream<Integer> myStream = Stream.of({0, 1, 1, 2, 3, 5, 8, 13, 21, 34}); b. Stream<int> myStream = Stream.of(0, 1, 1, 2, 3, 5, 8, 13, 21, 34); c. Stream<Integer> myStream = Stream.of(0, 1, 1, 2, 3, 5, 8, 13, 21, 34); d. Stream<Integer> myStream = Stream.stream({0, 1, 1, 2, 3, 5, 8, 13, 21, 34}); 6. Which statement creates a stream from an array of integers defined as shown: Integer[] myArray = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34}; a. Stream<Integer> myStream = Stream.of(myArray); b. Stream<Integer> myStream = myArray.stream(); c. Stream<int> myStream = myArray.stream(); d. Stream<int> myStream = Stream.of(myArray); Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch19 7. You want to create a stream from a list, set, or other collection in Java. Which method should you use? a. iterate b. of c. generate d. stream 8. Assuming that the variable myStringArrayList has been populated to contain a collection of String objects, which expression finds the number of elements in a stream created from the myStringArrayList collection? a. myStringArrayList.of().count() b. myStringArrayList.stream().count() c. myStringArrayList.stream().size() d. myStringArrayList.stream().length() 9. Which method causes stream operations to be distributed over multiple available processors? a. generate b. parallel c. distribute d. iterate 10. You want to create a stream of the lines in a file with a given path. Which method should you use? a. Paths.lines b. Stream.of c. Files.lines d. Files.stream 11. Which code fragment creates a stream of lines from a file named "data.txt"? a. try(Stream<String> linesData = Files.lines(Paths.get("data.txt"))) { ... }; b. try(Stream linesData = Files.lines(Paths.get("data.txt"))) { ... }; c. try(Stream<String> linesData = Files.lines("data.txt")) { ... }; d. try(Stream<String> linesData = Paths.get(Files.lines("data.txt"))) { ... }; 12. You want to save stream values in an array. Which method of the Stream class should you use? a. toArray b. save c. collect d. values 13. Which statement creates an array from a stream of Student objects, given by the variable studentStream? a. Student[] students = studentStream.collect(Collectors.toArray()); b. Student[] students = studentStream.toArray(Student[]::new); c. Student[] students = studentStream.toArray(new Student[]); d. Student[] students = studentStream.toArray(new::Student[]); Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch19 14. You want to save stream values in a list. Which method of the Stream class should you use? a. collect b. toArray c. toList d. save 15. Which statement creates a list from a stream of Student objects, given by the variable studentStream? a. List<Student> students = studentStream.collect(Collectors.toList()); b. List<Student> students = studentStream.toList(Student::new); c. List<Student> students = studentStream.collect(Student[]::new); d. List<Student> students = studentStream.toList(); 16. You want to save stream values in a set. Which method of the Stream class should you use? a. collect b. toArray c. save d. toSet 17. Which statement creates a set of majors from a stream of String objects, given by the variable majorsStream, representing the majors of students? a. Set<String> majors = majorsStream .toSet()); b. Set<String> majors = majorsStream .Collectors.toSet(); c. Set<String> majors = majorsStream .collect.toSet(); Set<String> majors = majorsStream d. .collect(Collectors.toSet());

18. You want to save a stream of String values as one long string. Which method of the Stream class should you use? a. save b. joining c. toString d. collect 19. Which statement creates one comma-separated String from a stream called orderedHonorMajors, which is a stream of alphabetically ordered String objects representing unique majors of honors students? a. String result = orderedHonorMajors .collect(Collectors.joining(", ")); b. String result = orderedHonorMajors .collect.joining(", "); c. String result = orderedHonorMajors .joining(Collectors.collect(", ")); String result = orderedHonorMajors d. .joining(", ");

20. Which of the following can NOT be used as an argument to the collect method of the Stream class. Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch19 a. Collectors.toArray() b. Collectors.joining() c. Collectors.toList() d. Collectors.toSet() 21. Which method of the Stream class can be used to create infinite streams? I generate II iterate III random a. II only b. I, II, and III c. I only d. I and II only 22. Which statement creates an infinite stream of lottery numbers in the range of 1 to 50? a. Stream<Integer> lotteryNumbers = Stream.iterate(() -> 1 + (int)(50 * Math.random())); b. Stream<Integer> lotteryNumbers = Stream.generator(() -> 1 + (int)(50 * Math.random())); c. Stream<Integer> lotteryNumbers = Stream.range(() -> 1 + (int)(50 * Math.random())); d. Stream<Integer> lotteryNumbers = Stream.generate(() -> 1 + (int)(50 * Math.random())); 23. Which statement creates an infinite stream of even numbers? a. Stream<Integer> evens = Stream.iterate(2, n -> n + 2); b. Stream<Integer> evens = Stream.range(n -> n + 2); c. Stream<Integer> evens = Stream.generate(n -> n + 2); d. Stream<Integer> evens = Stream.generator(2, n -> n + 2); 24. Which method applies a function to all elements of a stream, yielding another stream? a. filter b. skip c. map d. limit 25. Complete the following code snippet that returns a stream of String objects representing the majors of the students in the honors college, assuming that honorsStream is a stream of Student objects and the method getMajor returns a String.

Stream<String> honorsMajors = honorsStream ________________________________; a. .map(getMajor()) b. .filter(s -> s.getMajor()) c. .filter(getMajor()) Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch19 d. .map(s -> s.getMajor()) 26. Which method yields a stream of all elements fulfilling a condition? a. filter b. limit c. map d. skip 27. Complete the following code snippet that returns a stream of Student objects, representing students who have a grade point average (gpa) of at least 3.8. Assume that studentStream is a stream of Student objects and the getGpa method returns a double representing the student's gpa.

Stream<Student> highHonors = studentStream ________________________________; a. .map(getGpa() >= 3.8) b. .filter(getGpa() >= 3.8) c. .map(s -> s.getGpa() >= 3.8) d. .filter(s -> s.getGpa() >= 3.8) 28. Which method yields a stream restricted to a number of elements in the beginning of the stream? a. filter b. skip c. distinct d. limit 29. Complete the following code snippet that returns a list of the first ten prime numbers, assuming that primes is an infinite Integer stream of prime numbers.

List<Integer> first10primes = primes ________________________________ .collect(Collectors.toList()); a. .limit(10) b. .count(10) c. .skip(10) d. .filter(10) 30. Which method yields a stream obtained by dropping a number of elements from the beginning of the stream? a. limit b. distinct c. skip d. filter 31. Complete the following code snippet that counts the number of data lines in the students.csv file, ignoring the first line that contains the field headers. Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch19

try (Stream<String> lineStream = Files.lines(Paths.get("students.csv"))) { long dataCount = lineStream _____________________ .count(); } a. .take(1) b. .filter(1) c. .skip(1) d. .limit(1) 32. Which method yields a stream obtained by dropping duplicate elements? a. skip b. limit c. filter d. distinct 33. Complete the following code snippet that removes the duplicates from the honorsMajors stream of String objects representing the majors of the students in the honors college.

Stream<String> honorsUniqueMajors = honorsMajors ________________________________; a. .distinct() b. .skip() c. .filter() d. .unique() 34. Which method yields a new stream with the elements reordered by its corresponding Comparable interface implementation? a. orderby b. sort c. order d. sorted 35. Complete the following code snippet that alphabetically orders the honorsUniqueMajors stream of String objects representing the unique majors of the students in the honors college.

Stream<String> orderedHonorsMajors = honorsUniqueMajors ________________________________; a. .sort() b. .order() c. .sorted() Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch19 d. .orderby() 36. Which statement creates a stream of String objects representing the unique majors of students in alphabetical order? Assume that studentStream is a stream of Student objects and the getMajor method returns a String representing the student's major. a. Stream<String> uniqueMajors = studentStream .map(s -> s.getMajor()) .distinct() .sorted(); b. Stream<String> uniqueMajors = studentStream .distinct() .map(s -> s.getMajor()) .sorted(); c. Stream<String> uniqueMajors = studentStream .sorted() .map(s -> s.getMajor()) .distinct(); Stream<String> uniqueMajors = studentStream d. .filter(s -> s.getMajor()) .distinct() .sorted();

37. Which statement creates a list of names in alphabetical order of Computer Science majors? Assume that studentStream is a stream of Student objects and the getMajor and getName methods return a String representing the student's major and name, respectively. a. List<String> csMajors = studentStream .filter(s -> s.getMajor().equals("Computer Science")) .map(c -> c.getName()) .sorted() .collect(Collectors.toList()); b. List<String> csMajors = studentStream .filter(s -> s.getMajor().equals("Computer Science")) .sorted() .map(c -> c.getName()) .collect(Collectors.toList()); c. List<String> csMajors = studentStream .sorted() .filter(s -> s.getMajor().equals("Computer Science")) .map(c -> c.getName()) .collect(Collectors.toList()); d. List<String> csMajors = studentStream .map(c -> c.getName()) .filter(s -> s.getMajor().equals("Computer Science")) .sorted() .collect(Collectors.toList());

38. Which statement creates a list of the names of the top 3 Computer Science majors based on gpa? Assume that studentStream is a stream of Student objects and the getMajor and getName methods return a String representing the student's major and name, respectively. Also assume that the getGpa method returns a double representing the student's gpa. a. List<String> topCSmajors = studentStream .filter(s -> s.getMajor().equals("Computer Science")) .map(c -> c.getName())

Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch19 .sorted( (v,w) -> w.getGpa().compareTo(v.getGpa()) ) .limit(3) .collect(Collectors.toList()); b. List<String> topCSmajors = studentStream .map(c -> c.getName()) .filter(s -> s.getMajor().equals("Computer Science")) .sorted( (v,w) -> w.getGpa().compareTo(v.getGpa()) ) .limit(3) .collect(Collectors.toList()); c. List<String> topCSmajors = studentStream .filter(s -> s.getMajor().equals("Computer Science")) .sorted( (v,w) -> w.getGpa().compareTo(v.getGpa()) ) .limit(3) .map(c -> c.getName()) .collect(Collectors.toList()); d. List<String> topCSmajors = studentStream .limit(3) .filter(s -> s.getMajor().equals("Computer Science")) .sorted( (v,w) -> w.getGpa().compareTo(v.getGpa()) ) .map(c -> c.getName()) .collect(Collectors.toList());

39. Which statement about lambda expressions is NOT correct? a. The body of a lambda expression must consist of a single expression. b. A lambda expression can have an optional parameter type. c. A lambda expression can be converted to an instance of a functional interface, which is an interface with a single abstract method. d. A lambda expression can have multiple parameters. 40. What does the following lambda expression do, assuming the variable s is of type double?

s -> s + .10 * s a. This is not a valid lambda expression. b. Returns 10% of the value. c. Returns .10% of the value. d. Returns the value increased by 10%. 41. What does the following lambda expression do, assuming the variable p is of type double and the variable q is of type int?

(p, q) -> p * q a. Returns the quotient of p and q. b. Returns the value of p multiplied by q. c. This is not a valid lambda expression. d. Returns the average of p and q. 42. Which lambda expression represents a function that computes a 10% raise to an employee's salary? Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch19 a. s -> 1 + .10 * s b. s -> s + .01 * s c. s -> s * .10 d. s -> s + .10 * s 43. Which lambda expression represents a function that given the price and quantity of an item to purchase computes the cost of the quantity of that item on the invoice? a. p, q -> p * q b. (p, q) -> p + q c. (p, q) -> p * q d. p, q -> p + q 44. The method reference System.out::println is a shorthand for which expression? a. () -> System.out.println(n) b. () -> System.out.println() c. n -> System.out.println(n) d. System.out.println() 45. The constructor reference Student[]::new is a shorthand for which expression? a. n -> new Student[] b. n -> new Student[n] c. () -> new Student[] d. () -> new Student() 46. Which statement about higher-order functions is NOT correct? a. A higher-order function is a function that consumes functions. b. filter is considered to be a higher-order function. c. Implementing a higher-order function in Java uses a functional interface, which is an interface with a single abstract method. d. A higher-order function cannot return a function. 47. Which Java interface is NOT a functional interface? a. Predicate<T> b. Comparator<T> c. Collection<T> d. ActionListener 48. Complete the code to sort the employees collection by salary using a Comparator. Assume the method getSalary that returns an employee's salary as an integer.

Collections.sort(employees, _____________________________________); a. Comparator.comparing(Employee::getSalary) b. Comparator.comparing(Employee::getSalary()) c. Comparator.thenComparing(Employee::getSalary) Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch19 d. Comparator.comparing(e -> e.getSalary) 49. Complete the code to sort the employees collection by title and within title by salary using a Comparator. Assume the method getSalary that returns an employee's salary as an integer and the method getTitle that returns an employee's title as a String.

Collections.sort(employees, Comparator___________________________); a. .comparing(Employee::getSalary).thenComparing(Employee::getTitle) b. .comparing(Employee::getTitle).thenComparing(Employee::getSalary) c. .thenComparing(Employee::getSalary).comparing(Employee::getTitle) d. .thenComparing(Employee::getTitle).comparing(Employee::getSalary) 50. Which of the following statements related to the Optional type is NOT correct? a. The Optional.orElse method obtains the value of an Optional or, if no value is present, the value given by its parameter. b. The findFirst method on a stream returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. c. The Optional.of method creates a stream of Optional objects provided as an explicit parameter. d. The Optional class is a wrapper for objects that may or may not be present, which is typically used in results for stream processing. 51. Which of the following is NOT a method for the Optional class? a. present b. empty c. of d. orElse 52. Complete the following code snippet that returns the name of an employee who is a Database Administrator or "None" if there are no such titled employees.

String dbaResult = employeeStream .filter(e -> e.getTitle().equals("Database Administrator")) .map(d -> d.getName()) _____________________ // 1 or 2 lines a. .findFirst(); b. .findAny(); c. .findFirst()

.get(); d. .findFirst() .orElse("None");

53. Complete the following code snippet that checks a log for any error message and sends an alert with the message found using the alert method.

public void checkForErrors(Stream<String> log) Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch19

{ log .filter(m -> m.contains("ERROR")) .findFirst() _____________________ } a. .ifPresent(alert()); b. .isPresent(alert()); c. .isPresent(a -> alert(a)); d. .ifPresent(a -> alert(a)); 54. Complete the following code snippet, assuming that method findEmployeeByID takes an employee id as input and returns a result of type Optional<Employee> and method displayEmployee takes an Employee object as input and displays the employee's information.

Optional<Employee> empSearch = findEmployeeByID("123456789"); if (empSearch.isPresent()) { _____________________________ } else { System.out.println("Employee does not exist"); } a. displayEmployee(get(empSearch); b. displayEmployee(empSearch.get()); c. displayEmployee(empSearch); d. displayEmployee(empSearch.of()); 55. Complete the following code snippet that displays a student's major, assuming that the method findStudentByID takes a student id as input and returns a result of type Optional<Student>. Also, assume the getMajor method returns a String representing the student's major.

Optional<Student> studentSearch = findStudentByID("123456789"); if (____________________) { System.out.println(studentSearch.get().getMajor()); } else { System.out.println("Student does not exist"); } a. studentSearch != null b. studentSearch != Optional.empty() Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch19 c. studentSearch.isPresent() d. studentSearch.ifPresent() 56. Which of the following statements does NOT return a value of type Optional, assuming that the variable result is of type Optional<String>? a. return result.orElse("None"); b. return Optional.empty(); c. return result; d. return Optional.of("None"); 57. Consider the following pseudocode that returns an Optional value from a method:

if there is a result // line 1 return the result // line 2 else return an empty result // line 3 Assume that the variable result represents an object reference to the result to be returned as Optional. Replace line 1 with the Java code to determine whether there is a result. a. if (result.ifPresent()) b. if (result == null) c. if (result != null) d. if (result.isPresent()) 58. Consider the following pseudocode that returns an Optional value from a method:

if there is a result // line 1 return the result // line 2 else return an empty result // line 3 Assume that the variable result represents an object reference to the result to be returned as Optional. Replace line 2 with the Java code to return the result. a. return result.get(); b. return Optional.empty(); c. return Optional<result>; d. return Optional.of(result); 59. Consider the following pseudocode that returns an Optional value from a method:

if there is a result // line 1 return the result // line 2 else Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch19

return an empty result // line 3 Assume that the variable result represents an object reference to the result to be returned as Optional. Replace line 3 with the Java code to return an empty result. a. return Optional.empty(); b. return Optional.empty(result); c. return result.empty(); d. return null; 60. A __________ operation triggers the lazy operations on a stream and yields a non-stream value. a. parallel b. terminal c. non-terminal d. distributed 61. Which of the following is NOT a terminal operation? a. count b. distinct c. allMatch d. collect 62. Which of the following terminal operations on a generic Stream does NOT return an Optional? a. anyMatch b. max c. findAny d. findFirst 63. Which of the following terminal operations does NOT return a boolean? a. anyMatch b. noneMatch c. allMatch d. findAny 64. Which of the following terminal operations does NOT return a result? a. toArray b. collect c. forEach d. allMatch 65. Complete the following code snippet to display the orderedHonorsMajors stream of alphabetically ordered String objects, representing the unique majors of the students in the honors college.

orderedHonorsMajors ________________________________; Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch19 a. .forEach(m -> System.out.println(m)) b. .each(m -> System.out.println(m)) c. .foreach(m -> System.out.println(m)) d. .for(m -> System.out.println(m)) 66. Complete the following code snippet to determine whether all honors students included in the honorsMajors stream of Student objects have a grade point average of at least 3.0, assuming the method getGpa returns the student's gpa as a double.

boolean honorsBorBetter = honorsMajors ________________________________; a. .anyMatch(s -> s.getGpa() >= 3.0) b. .allMatch(s -> s.getGpa() >= 3.0) c. .forall(s -> s.getGpa() >= 3.0) d. .noneMatch(s -> s.getGpa() >= 3.0) 67. Complete the following code snippet to find the highest paid Database Administrator. Assume that employeeStream is a stream of Employee objects and the getTitle method returns a String representing the employee's title. Also assume the getSalary method returns an employee's salary as an integer.

Optional<Employee> maxPaidDBA = employeeStream .filter(e -> e.getTitle().equals("Database Administrator")) ___________________________________________; a. .forall((c,d) -> c.getSalary() > d.getSalary()) b. .max((c,d) -> c.getSalary() - d.getSalary()) c. .anyMatch((c,d) -> c.getSalary() - d.getSalary()) d. .allMatch((c,d) -> c.getSalary() > d.getSalary()) 68. Complete the following code snippet that determines whether there is a Computer Science major with a 4.0 gpa. Assume that studentStream is a stream of Student objects and the getMajor and getName methods return a String representing the student's major and name, respectively. Also assume that the getGpa method returns a double representing the student's gpa.

String csStudentWith4gpa = studentStream .filter(c -> c.getMajor().contains("Computer Science")) .filter(g -> g.getGpa() == 4.0) .map(s -> s.getName()) ___________________________ .orElse("None"); a. .findAny() b. .anyMatch() c. .find() d. .any() Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch19 69. Complete the following code snippet that determines whether there is a Computer Science major with a 4.0 gpa. Assume that studentStream is a stream of Student objects and the getMajor and getName methods return a String representing the student's major and name, respectively. Also assume that the getGpa method returns a double representing the student's gpa.

boolean csStudentWith4gpa = studentStream .filter(c -> c.getMajor().equals("Computer Science")) _________________________________________________________; a. .any(g -> g.getGpa() == 4.0) b. .findAny(g -> g.getGpa() == 4.0) c. .filter(g -> g.getGpa() == 4.0) d. .anyMatch(g -> g.getGpa() == 4.0) 70. Complete the following code snippet that determines whether all Managers earn more than 100,000. Assume that employeeStream is a stream of Employee objects and the getTitle method returns a String representing the employee's title. Also assume the getSalary method returns an employee's salary as an integer.

boolean allManagers100K = employeeStream .filter(e -> e.getTitle().equals("Manager")) _________________________________________________________; a. .noneMatch(m -> m.getSalary() < 100000) b. .anyMatch(m -> m.getSalary() < 100000) c. .allMatch(m -> m.getSalary() < 100000) d. .findAny(m -> m.getSalary() < 100000) 71. Which of the following is NOT a primitive-type stream? a. IntStream b. DoubleStream c. LongStream d. FloatStream 72. Which of the following is NOT a correct statement about primitive-type streams? a. An IntStream is a stream of Integer objects. b. The methods for streams are also applicable to a primitive-type stream. c. An IntStream is more efficient than Stream<Integer>. d. A primitive-type stream has a sum method. 73. Which of the following expressions returns an IntStream, assuming that generator is an instance of type Random? a. generator.int(1,7) b. generator.nextInts() c. "Hello World".codePoints() d. Stream.of(1,3,5,7,9) Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch19 74. Complete the following statement that uses streams to display the names of employees in an ArrayList called employees of Employee objects that have a getName method to return the employee's name as a String.

_________________________________________ .forEach(i -> System.out.println(employees.get(i).getName())); a. IntStream.range(0, employees.size()-1) b. IntStream.range(1, employees.size()-1) c. IntStream.range(1, employees.size()) d. IntStream.range(0, employees.size()) 75. Complete the following statement that uses streams to create test data by appending a number to a string.

List<String> testData = IntStream.range(1,50) ____________________________________ .collect(Collectors.toList()); a. .mapToObject(i -> "Test" + i) b. .toObject(i -> "Test" + i) c. .mapToObj(i -> "Test" + i) d. .map(i -> "Test" + i) 76. Complete the following statement that uses streams to find the length of the longest employee name. Assume that employeeStream is a stream of Employee objects and the getName method returns a String representing the employee's name.

int longestNameLength = employeeStream .mapToInt(e -> e.getName().length()) ___________________________ // 1 or 2 lines a. .max((v,w) -> v - w); b. .max(); c. .max((v,w) -> v - w) .orElse(0); d. .max() .orElse(0);

77. Complete the following statement that finds the average salary of employees. Assume that employeeStream is a stream of Employee objects and the getSalary method returns the employee's salary as an integer.

double avgEmpSal = employeeStream ________________ .average() .orElse(0); a. .filter(e -> e.getSalary()) Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch19 b. .map(e -> e.getSalary()) c. .mapToObj(e -> e.getSalary()) d. .mapToInt(e -> e.getSalary()) 78. Complete the following statement that finds the average salary of employees who are Database Administrators. Assume that employeeStream is a stream of Employee objects and the getSalary method returns the employee's salary as an integer. Also, assume the getTitle method returns a String representing the employee's title.

_________________ avgDBAsalary = employeeStream .filter(e -> e.getTitle().equals("Database Administrator")) .mapToInt(e -> e.getSalary()) .average(); a. Optional<Double> b. OptionalDouble c. double d. Double 79. Complete the following statement that finds the minimum salary of employees who are Managers. Assume that employeeStream is a stream of Employee objects and the getSalary method returns the employee's salary as an integer. Also, assume the getTitle method returns a String representing the employee's title.

_________________ minMgrSalary = employeeStream .filter(e -> e.getTitle().equals("Manager")) .mapToInt(e -> e.getSalary()) .min(); a. OptionalInt b. int c. Optional<Integer> d. Integer 80. Complete the following statement that finds the total cost of raising all employee salaries by 10%. Assume that employeeStream is a stream of Employee objects and the getSalary method returns the employee's salary as an integer.

double raiseCost = employeeStream ________________ ________________; a. .mapToDouble(e -> e.getSalary()*.10) .sum(); b. .mapToDouble(e -> e.getSalary()*.10) .summingDouble(); c. .mapToDouble(e -> e.getSalary()) .summingInt(); d. .mapToInt(e -> e.getSalary()*.10) .sum(); Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch19 81. Which statement about grouping results is NOT correct? a. The groupingBy collector collects the stream into a map. b. A grouping collector can apply another collector to each group. c. Using grouping collectors, you can group together elements with the same key. d. The default type of each created group is a stream. 82. What is the type returned by the groupingBy operator on a stream of Student where students are grouped by major? a. Map<String, Set<Student>> b. Map<String, List<Student>> c. Map<String, Student> d. <String, List<Student>> 83. Complete the following statement that creates a group of students by major. Assume that studentStream is a stream of Student objects and the getMajor method returns a String representing the student's major.

Map<String, List<Student>> studentsByMajor = studentStream _____________________________________; a. .collect(Collectors.groupingBy(s -> s.getMajor())) b. .collect(Collections.groupingBy(s -> s.getMajor())) c. .collect(Collectors.groupBy(s -> s.getMajor())) d. .collect(Collections.groupBy(s -> s.getMajor())) 84. Complete the following statement that finds the number of students by major. Assume that studentStream is a stream of Student objects and the getMajor method returns a String representing the student's major.

____________________________ countStudentsByMajor = studentStream .collect(Collectors.groupingBy(s -> s.getMajor(), Collectors.counting())); a. Map<String, Long> b. Map<String, List<Student>> c. Map<String, List<Long>> d. Map<String, Set<Student>> 85. Complete the following statement that finds the number of employees per title. Assume that employeeStream is a stream of Employee objects and the getTitle method returns a String representing the employee's title.

Map<String, Long> empCountByTitle = employeeStream .collect(Collectors.groupingBy(___________________________)); a. e -> e.getTitle(), Collectors.counting() b. e -> e.getTitle(), Collectors.count() c. e -> e.getTitle(), count() d. Collectors.counting(), e -> e.getTitle() Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch19 86. Complete the following statement that finds the average salary of employees per title. Assume that employeeStream is a stream of Employee objects and the getTitle method returns a String representing the employee's title. Also assume that the getSalary method returns the employee's salary as an integer.

Map<String, Double> avgSalaryByTitle = employeeStream .collect(Collectors.groupingBy(___________________________)); a. e -> e.getTitle(), Collectors.averageDouble(e -> e.getSalary()) b. e -> e.getTitle(), Collectors.averagingInt(e -> e.getSalary()) c. e -> e.getTitle(), Collectors.average(e -> e.getSalary()) d. e -> e.getTitle(), Collectors.averaging(e -> e.getSalary()) 87. Complete the following statement that maps a set of employees that have similar salaries, based on thousands paid. Assume that employeeStream is a stream of Employee objects and the getSalary method returns the employee's salary as an integer.

Map<Integer, Set<Employee>> empsBySalary = employeeStream .collect(Collectors.groupingBy(e -> e.getSalary() / 1000,___________________________)); a. Collectors.set() b. Collectors.toSet() c. Collectors.toSet(e -> e.getSalary()) d. Collectors.set(e -> e.getSalary()) 88. Complete the following statement that finds the total salary cost of employees per title. Assume that employeeStream is a stream of Employee objects and the getTitle method returns a String representing the employee's title. Also assume that the getSalary method returns the employee's salary as an integer.

Map<String, Integer> salaryCostByTitle = employeeStream .collect(Collectors.groupingBy(___________________________)); a. e -> e.getTitle(), Collectors.sumDouble(e -> e.getSalary()) b. e -> e.getTitle(), Collectors.sum(e -> e.getSalary()) c. e -> e.getTitle(), Collectors.summing(e -> e.getSalary()) d. e -> e.getTitle(), Collectors.summingInt(e -> e.getSalary()) 89. Complete the following statement that finds the minimum salaried employee per title. Assume that employeeStream is a stream of Employee objects and the getTitle method returns a String representing the employee's title. Also assume that the getSalary method returns the employee's salary as an integer.

Map<String, Optional<Employee>> minSalaryByTitle = employeeStream .collect(Collectors.groupingBy(e -> e.getTitle(),___________________________)); a. Collectors.minBy((v,w) -> v.getSalary() - w.getSalary())) Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch19 b. Collectors.min() c. Collectors.minBy() d. Collectors.min((v,w) -> v.getSalary() - w.getSalary())) 90. Complete the following statement that finds the maximum salaried employee per title. Assume that employeeStream is a stream of Employee objects and the getTitle method returns a String representing the employee's title. Also assume that the getSalary method returns the employee's salary as an integer.

___________________________________ maxSalaryByTitle = employeeStream .collect(Collectors.groupingBy(e -> e.getTitle(),Collectors.maxBy((v,w) -> v.getSalary() - w.getSalary() ))); a. Map<Integer, Optional<Employee>> b. Map<String, Employee> c. Map<String, Optional<Employee>> d. Map<String, List<Employee>> 91. Which statement fills an array with ten die tosses using streams? a. int[] dieTosses = IntegerStream.range(0,10) .map(i -> (int) (6 * Math.random() + 1)) .toArray(); int[] dieTosses = IntStream.range(0,9) b. .map(i -> (int) (6 * Math.random() + 1)) .toArray(); int[] dieTosses = IntegerStream.range(0,9) c. .map(i -> (int) (6 * Math.random() + 1)) .toArray(); d. int[] dieTosses = IntStream.range(0,10) .map(i -> (int) (6 * Math.random() + 1)) .toArray();

92. Which statement finds the highest salary for all employees using streams? Assume that employees is a collection of Employee objects and the getSalary method returns the employee's salary as an integer. a. int maxEmpSal = employees .stream() .mapToInt(e -> e.getSalary()) .max() .orElse(0); b. int maxEmpSal = employees .stream() .mapToInt(e -> e.getSalary()) .max(); c. int maxEmpSal = employees .stream() .mapToInt(e -> e.getSalary()) .maxBy((v,w) -> v.getSalary() - w.getSalary()) .orElse(0); d. int maxEmpSal = employees .stream() .map(e -> e.getSalary()) .max()

Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch19 .orElse(0);

93. Which statement finds the lowest salary for all managers using streams? Assume that employees is a collection of Employee objects, the getSalary method returns the employee's salary as an integer and the getTitle method returns a String representing the employee's title. a. int minMgrSal = employees .stream() .mapToInt(m -> m.getSalary()) .filter(e -> e.getTitle().equals("Manager")) .min(); b. int minMgrSal = employees .stream() .filter(e -> e.getTitle().equals("Manager")) .map(m -> m.getSalary()) .min() .orElse(0); int minMgrSal = employees c. .stream() .filter(e -> e.getTitle().equals("Manager")) .mapToInt(m -> m.getSalary()) .min() .orElse(0); int minMgrSal = employees d. .stream() .mapToInt(m -> m.getSalary()) .filter(e -> e.getTitle().equals("Manager")) .minBy((v,w) -> v.getSalary() - w.getSalary()) .orElse(0);

94. Which statement finds the average Database Administrator salary using streams? Assume that employees is a collection of Employee objects, the getSalary method returns the employee's salary as an integer and the getTitle method returns a String representing the employee's title. a. double avgDBAsal = employees .stream() .mapToInt(m -> m.getSalary()) .filter(e -> e.getTitle().equals("Database Administrator")) .average(); double avgDBAsal = employees b. .stream() .filter(e -> e.getTitle().equals("Database Administrator")) .mapToInt(m -> m.getSalary()) .average() .orElse(0); c. double avgDBAsal = employees .stream() .filter(e -> e.getTitle().equals("Database Administrator")) .map(m -> m.getSalary()) .average() .orElse(0); d. double avgDBAsal = employees .stream() .mapToInt(m -> m.getSalary()) .filter(e -> e.getTitle().equals("Database Administrator")) .average()

Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch19 .orElse(0);

95. Which statement finds the total salary cost of employees having the title System Architect? Assume that employees is a collection of Employee objects, the getSalary method returns the employee's salary as an integer and the getTitle method returns a String representing the employee's title. a. int salaryCostSystemArchitect = employees .stream() .filter(e -> e.getTitle().equals("System Architect")) .map(m -> m.getSalary()) .sum() .orElse(0); b. int salaryCostSystemArchitect = employees .stream() .filter(e -> e.getTitle().equals("System Architect")) .mapToInt(m -> m.getSalary()) .sum(); int salaryCostSystemArchitect = employees c. .stream() .mapToInt(m -> m.getSalary()) .filter(e -> e.getTitle().equals("System Architect")) .sum(); int salaryCostSystemArchitect = employees d. .stream() .mapToInt(m -> m.getSalary()) .filter(e -> e.getTitle().equals("System Architect")) .sum() .orElse(0);

96. Which statement finds the number of employees using streams who are a type of Software Engineer? Assume that employees is a collection of Employee objects and the getTitle method returns a String representing the employee's title. a. long numberSoftwareEngineers = employees .stream() .filter(e -> e.getTitle().contains("Software Engineer")) .counting(); long numberSoftwareEngineers = employees b. .stream() .filter(e -> e.getTitle().contains("Software Engineer")) .count(); long numberSoftwareEngineers = employees c. .filter(e -> e.getTitle().contains("Software Engineer")) .stream() .count(); long numberSoftwareEngineers = employees d. .stream() .filter(e -> e.getTitle().contains("Software Engineer")) .summing();

97. Which statement uses streams to display the names of students who are Computer Science majors with a 4.0 gpa where the names are separated by a semi-colon? Assume that students is a collection of Student objects and the getMajor and getName methods return a String representing the student's major and name, respectively. Also assume that the getGpa method returns a double representing the student's gpa. a. String csMajors4 = students Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch19 .stream() .filter(s -> s.getMajor().equals("Computer Science")) .filter(s -> s.getGpa() == 4.0) .collect(Collectors.joining("; ")); b. String csMajors4 = students .stream() .filter(s -> s.getMajor().equals("Computer Science")) .filter(s -> s.getGpa() == 4.0) .map(s -> s.getName()) .collect(Collectors.joining("; ")); c. String csMajors4 = students .stream() .filter(s -> s.getMajor().equals("Computer Science")) .filter(s -> s.getGpa() == 4.0) .map(s -> s.getName()) .collect(Collectors.join("; ")); String csMajors4 = students d. .stream() .filter(s -> s.getMajor().equals("Computer Science")) .map(s -> s.getName()) .filter(s -> s.getGpa() == 4.0) .collect(Collectors.joining("; "));

98. Complete the following statement that performs a linear search on an array of Student objects, named studentsArray, returning the index position at which it finds a student having a gpa of 4.0 or -1 if the value is not found. Assume that the getGpa method returns a double representing the student's gpa.

int position = IntStream.range(0, studentsArray.length) ______________________________________________ .findFirst() .orElse(-1); a. .filter(i -> studentsArray[i].getGpa() == 4.0) b. .map(i -> studentsArray[i].getGpa()) c. .filter(studentsArray[i].getGpa() == 4.0) d. .filter(s -> s.getGpa() == 4.0) 99. Consider the following code snippet that displays the name of students in a collection of Student objects named students. Assume that the getName method returns a String representing the student's name.

for (Student s: students) { System.out.println(s.getName()); } Which statement provides a stream-based alternative to this algorithm? a. students .stream() .for(s -> System.out.println(s.getName())); b. students .stream()

Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch19 .forEach(s -> System.out.println(s.getName())); students c. .forEach(s -> System.out.println(s.getName())); d. students .stream() .foreach(s -> System.out.println(s.getName()));

100. Which statement about the applicability of stream processing to common algorithms is NOT correct? a. Streams are easily applicable to algorithms that compare adjacent elements of a sequence. b. Streams provide a straightforward way to generate the index values for iterating through an array or collection. c. Streams are easily applicable to algorithms that perform aggregate functions, such as count, average, sum, minimum, and maximum. d. Streams provide a straightforward mechanism for displaying a sequence with element separators.

Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch19 Answer Key 1. a 2. d 3. b 4. a 5. c 6. a 7. d 8. b 9. b 10. c 11. a 12. a 13. b 14. a 15. a 16. a 17. d 18. d 19. a 20. a 21. d 22. d 23. a 24. c 25. d Powered by Cognero

Page 25


Name:

Class:

Date:

testbank-bj-7-ch19 26. a 27. d 28. d 29. a 30. c 31. c 32. d 33. a 34. d 35. c 36. a 37. a 38. c 39. a 40. d 41. b 42. d 43. c 44. c 45. b 46. d 47. c 48. a 49. b 50. c 51. a Powered by Cognero

Page 26


Name:

Class:

Date:

testbank-bj-7-ch19 52. d 53. d 54. b 55. c 56. a 57. c 58. d 59. a 60. b 61. b 62. a 63. d 64. c 65. a 66. b 67. b 68. a 69. d 70. a 71. d 72. a 73. c 74. d 75. c 76. d Powered by Cognero

Page 27


Name:

Class:

Date:

testbank-bj-7-ch19 77. d 78. b 79. a 80. a 81. d 82. b 83. a 84. a 85. a 86. b 87. b 88. d 89. a 90. c 91. d 92. a 93. c 94. b 95. b 96. b 97. b 98. a 99. b 100. a

Powered by Cognero

Page 28


Name:

Class:

Date:

testbank-bj-7-ch20

Indicate the answer choice that best completes the statement or answers the question. 1. What is the default layout manager of JPanel? a. FlowLayout b. GridLayout c. BoxLayout d. GridBagLayout 2. What is the default layout manager of the content pane of a JFrame? a. FlowLayout b. GridLayout c. BoxLayout d. BorderLayout 3. Which class has constants called NORTH and SOUTH? a. FlowLayout b. BorderLayout c. BoxLayout d. GridLayout 4. Which layout manager places objects left-to-right, and creates a new row only if when the current row cannot accommodate another object? a. FlowLayout b. BorderLayout c. BoxLayout d. GridLayout 5. Which layout manager places objects left-to-right, row by row into a fixed set of rows and columns? a. FlowLayout b. BorderLayout c. BoxLayout d. GridLayout 6. Which layout manager allows you to add components in different orders, with the result being the same GUI appearance? I FlowLayout II BorderLayout III GridLayout a. Only I b. Only II c. I and III d. II and III 7. Which layout manager uses a grid so that each component will always be placed into an area of the same size? I GridBagLayout Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch20 II BorderLayout III GridLayout a. Only I b. Only II c. Only III d. I and III 8. Which layout manager uses a grid, but allows selected grid locations to span multiple rows or columns? I GridBagLayout II BorderLayout III GridLayout a. Only I b. Only II c. Only III d. I and III 9. Which layout manager allows you to add components to it by invoking the container’s add method with the component as the only argument to add. I FlowLayout II BorderLayout III GridLayout a. Only I b. Only II c. Only III d. I and III 10. What is the easiest way to create complex-looking GUI layouts? I use the GridBagLayout manager II nest panels, each with its own layout manager III use multiple layout managers in the same container a. Only I b. Only II c. Only III d. I and III 11. The JFrame has a content pane with a default BorderLayout manager. Which method allows changing it to a FlowLayout manager? a. setLayout b. setFlowLayout c. assignLayout d. changeLayout 12. Which layout manager constructor call would be best-suited to create a telephone keypad GUI which has three rows of three keys that are labeled 1,2,3; 4,5,6; and 7,8,9; respectively, as well as a fourth row of three keys labeled *, 0, #? a. new GridLayout(3, 4) Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch20 b. new GridLayout(4, 3) c. new FlowLayout(4, 3) d. new BorderLayout(3, 4) 13. Which layout manger would be best suited to create a simple navigation GUI with directional arrows for left, right, up, down and enter? a. GridLayout b. BorderLayout c. FlowLayout d. GridBagLayout 14. To create a _____ layout, you supply the number of rows and columns in the constructor, then add the components, row by row, left to right. a. border b. grid c. grid bag d. boxed 15. When adding a component to a container with the ____ layout, specify the NORTH, EAST, SOUTH, WEST, or CENTER position. a. border b. grid c. grid bag d. flow 16. In Java, each container has its own ____________________, which determines how the components are laid out. a. container b. layout manager c. Swing component d. frame manager 17. How do you add two buttons to the south area of a frame using the BorderLayout? a. Add them to a panel, then add the panel to the SOUTH b. Add one to the SOUTH, then add the second one to the SOUTH c. Add one to the SOUTH, then add the second one to the CENTER d. Add one to the CENTER, then add the second one to the SOUTH 18. A complex GUI can be created with a set of nested panels. What should determine the components that go into a single panel? a. the type of components b. the size of the components c. the adjacency of the components d. the names of the components 19. What is the best first step in picking the layout managers for a set of nested panels? Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch20 a. use a single panel with a GridBagLayout manager b. construct a set of JPanel objects c. make a sketch of the layout d. use multiple panels with FlowLayout managers 20. If a JPanel with a BorderLayout manager contains a single component that was added to the CENTER, which parts of the JPanel does the component fill? I North II South III Center IV West V East a. I, II and III b. II, IV and V c. III, IV and V d. I, II, III, IV and V 21. Suppose a JPanel with a BorderLayout manager contains two components: component1, which was added to the CENTER, and component2, which was added to the SOUTH. Which parts of the JPanel will appear? I North II South III Center IV West V East a. I and II b. I, II, and III c. III, IV, and V d. II and III 22. Suppose a JPanel with a BorderLayout manager contains two components: component1, which was added to the EAST, and component2, which was added to the WEST. Which parts of the JPanel appear? I North II South III Center IV West V East a. I and II b. I, II, and III c. III, IV, and V d. IV and V 23. Which of the following is true about a border layout? a. It groups components into three areas: center, north, and south b. It is the default manager for JPanel c. Each area can hold a single component, or it can be empty d. Components do not expand to fill in the space of the border layout Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch20 24. Which of the following is false about achieving complex layouts? a. By giving each panel an appropriate layout manager, the panels can be nested b. There are more complex layout managers such as the grid bag layout and group layout c. You can use as many panels as you need to organize your components d. The order of the nested panel does not matter 25. In an online job application, applicants have to submit a cover letter by typing it into a given text box. Which java class would be most appropriate for this text box? a. JTextArea b. JTextField c. JLabel d. JTextComponent 26. Insert the missing code in the following segment. The code intends to get the newly selected item from the combo box.

JComboBox facenameCombo = new JComboBox(); String selectedString = __________________________; a. (String) facenameCombo.getSelected(); b. (String) facenameCombo.getSelectedItem(); c. (String) selectedString.getSelected(); d. (String) selectedString.getSelectedItem(); 27. A(n) ____ is used when you have a large set of choices. a. combo box b. radio button c. check box d. action event 28. A ____ is a combination of a list and a text field. a. radio button b. combo box c. check box d. scroll bar 29. Which GUI element allows text entry from the program user? a. ButtonGroup b. JComboBox c. JSlider d. JPanel 30. A ________ is a user-interface component with two states: checked and unchecked. Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch20 a. radio button b. check box c. menu item d. submenu item 31. When using a combo box, the _______ displays the name of the current selection. a. text field b. text area c. menu item d. submenu item 32. The statement that would add smallButton to the button group in the following code is _________.

JRadioButton smallButton = new JRadioButton("Small"); ButtonGroup group = new ButtonGroup(); a. group.add(new smallButton); b. group.add(smallButton); c. smallButton.add(); d. You cannot add smallButton to the button group. 33. Which of the following is not a visual component? a. JRadioButton b. JButton c. ButtonGroup d. JCheckBox 34. Which of the following classes has a Boolean state that can be set or unset through the GUI? a. JCheckBox b. JButton c. ButtonGroup d. JMenuItem 35. Which of the following classes have a user-editable area? a. JCheckBox b. JComboBox c. ButtonGroup d. JRadioButton 36. Which of the following methods returns the object that was selected in the JComboBox? a. getSelected b. getItem c. getChoice d. getSelectedItem Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch20 37. What type does the method getSelectedItem in the JComboBox classreturn? a. Object b. String c. JRadioButton d. JLabel 38. What type of object can be added into a JComboBox by the addItem method? a. Object b. String c. JRadioButton d. any non-primitive type 39. Which method can a program use to set the selected choice in a JComboBox? a. select b. setChoice c. setSelectedItem d. The selection can only be set through the GUI by the user. 40. Which method can a program use to set the selected choice in a JRadioButton? a. set b. setChoice c. setSelectedItem d. setSelected 41. Which of the following GUI objects generate(s) action events? I JComboBox II JRadioButton III JButton a. Only I b. I and II c. I and III d. I, II and III 42. You can add a(n) _________ to a panel to make it visible. a. component b. JFrame c. border d. another panel 43. Which of the following adds a border to the following panel?

JPanel panel = new JPanel(); a. panel.addEtchedBorder(); b. panel.addBorder(new EtchedBorder()); Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch20 c. panel.add(new EtchedBorder()); d. panel.setBorder(new EtchedBorder()); 44. Given four JRadioButton objects in a ButtonGroup, how many radio buttons can be selected at the same time? a. 1 b. 2 c. 4 d. 3 45. What is the most time-effective way to build a GUI quickly and concentrate on coding the logic of the program? a. use the GridBagLayout manager b. use a GUI builder, such as NetBeans c. use nested panels d. use menus 46. What features do GUI builders have to speed the development of the graphical user interface of the program? I setting properties of dialog boxes II automated event-handling code generation III drag and drop of visual components a. I b. II c. II and III d. I, II and III 47. Based on the statement below, which of the following adds a title to the border?

JPanel panel = new JPanel(); a. panel.setBorder(new TitledBorder()); b. panel.setBorder(new TitledBorder(new EtchedBorder(), "Size")); c. panel.setBorder(new TitledBorder(new EtchedBorder())); d. panel.setTitle("Size"); 48. Which elements of creating a graphical user interface are made easier by a GUI builder? I creating event handlers II configuring component properties III adding components a. Only II b. I and II c. I and III d. I, II, and III 49. Which of the following would be an appropriate use of radio buttons when ordering a pizza? a. Topping choices b. Customer's name Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch20 c. Pick-up/Delivery d. Types of sides 50. Which of the following defines the job of a ButtonGroup? a. Places the buttons close to each other in the container b. Assures only one button in the group is selected at a time c. Arranges the group of buttons solely for presentation purposes d. Groups checkboxes together to allow multiple choices 51. Which of the following generate action events? a. Buttons b. Menu items c. Combo box d. All of the above 52. When the user selects a menu item, the menu item sends a(n) ___________________. a. ActionEvent b. ChangeEvent c. ItemEvent d. MouseEvent 53. What is the container for top-level menu items? a. menu bar b. menu item c. menu GUI d. top level menus don’t use containers 54. Which component can be added to a menu? I JMenuBar II JMenu III JMenuItem a. Only I b. I and II c. II and III d. I, II and III 55. What can be determined about obj from the code below?

JMenuItem menuItem = new JMenuItem("Exit"); menuItem.addActionListener(obj); a. The class of obj implements ActionListener b. menuItem implements ActionListener c. obj is of type MenuListener d. obj is an object of an inner class Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch20 56. Examine the code below. What type of class is MyMenuListener?

public JMenuItem makeMenuItem(String menuLabel) { JMenuItem mini = new JMenuItem(menuLabel); class MyMenuListener implements ActionListener { public void actionPerformed(ActionEvent e) { doSomething(); } } mini.addActionListener(new MyMenuListener()); return mi; } a. It is an anonymous class b. It is an inner class c. It is a JMenuItem subclass d. It is a JMenu class 57. If the method makeMenuItem is called four times, how many MyMenuListener objects will be created?

public JMenuItem makeMenuItem(String menuLabel) { JMenuItem mi = new JMenuItem(menuLabel); class MyMenuListener implements ActionListener { public void actionPerformed(ActionEvent e) { doSomething(); } } mi.addActionListener(new MyMenuListener()); return mi; } a. 1 b. 2 c. 3 d. 4 58. If the makeMenuItem method is called four times, at most how many different actions can be performed by these four newly created MenuItem objects when the doSomethingElse method is called?

public JMenuItem makeMenuItem(String menuLabel) Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch20

{ JMenuItem mi = new JMenuItem(menuLabel); class MyMenuListener implements ActionListener { public void actionPerformed(ActionEvent e) { doSomethingElse(e); } } mi.addActionListener(new MyMenuListener()); return mi; } a. 1 b. 2 c. 3 d. 4 59. When a menu item is selected, what type of event does it send? a. ActionEvent b. ChangeEvent c. ItemEvent d. SelectionEvent 60. What is wrong with the following code?

class ExitListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.exit(0); } } ActionListener exitListener = new ExitListener(); JMenu exitMenu = new JMenu("Exit"); exitMenu.addActionListener(exitListener); JMenuBar menuBar = new JMenuBar(); menuBar.add(exitMenu); a. The ExitListener class is not public b. You cannot attach a listener to a menu, only to a menu item c. You cannot add a menu to the menu bar, only a menu item d. You need to use a menu listener, not an action listener 61. What is known for certain from this correct code excerpt? Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch20

ActionListener openListener = new FileOpenListener(); JMenuItem fileOpen = new JMenuItem("Open File"); fileOpen.addActionListener(openListener); a. fileOpen will open a file dialog when clicked b. The fileOpen menu item will be visible c. The FileOpenListener class implements the ActionListener interface d. The openListener object will only listen to the fileOpen object 62. The code below will not compile successfully unless the argument to the makeMenuItem method is final. Why not?

public JMenuItem makeMenuItem(final String menuLabel) { JMenuItem mi = new JMenuItem(menuLabel); class MyMenuListener implements ActionListener { public void actionPerformed(ActionEvent e) { doSomethingElse(); System.out.println(menuLabel); } } mi.addActionListener(new MyMenuListener()); return mi; } a. JMenuItem labels must be final b. This prevents the menuLabel argument from being modified c. Because a local variable is being accessed from an inner classes d. Because the String class is final 63. When method makeMenuItem is called, how many objects are being created?

public JMenuItem makeMenuItem(final String menuLabel) { JMenuItem mi = new JMenuItem(menuLabel); class MyMenuListener implements ActionListener { public void actionPerformed(ActionEvent e) { doSomethingElse(); System.out.println(menuLabel); } } mi.addActionListener(new MyMenuListener()); Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch20

return mi; } a. 1 b. 2 c. 3 d. 4 64. Consider the scope of the three objects menuLabel, mi, and the anonymous object new MyMenuListener() within the JmenuItem class. How do thier lifetimes compare?

public JMenuItem makeMenuItem(final String menuLabel) { JMenuItem mi = new JMenuItem(menuLabel); class MyMenuListener implements ActionListener { public void actionPerformed(ActionEvent e) { doSomethingElse(); System.out.println(menuLabel); } } mi.addActionListener(new MyMenuListener()); return mi; } a. all have the same lifetimes b. menuLabel and new MyMenuListener() are the same and both longer than mi c. mi and new MyMenuListener() are the same and both longer than menuLabel d. from shortest to longest:menuLabel, new MyMenuListener(), mi 65. What is the general order of a pull-down menu (from top-level going downwards)? a. Frame, menu bar, menus, submenus, menu items b. Menus, menu bar, submenus, frame, menu items c. Menu bar, frame, menus, submenus, menu items d. Submenus, menus, frame, menu bar, menu items 66. What can you add action listeners to? a. Menu items b. Menus c. Menu bar d. Submenu 67. The event that is generated by a slider when its value changes is of type _____. a. ActionEvent b. ChangeEvent Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch20 c. ItemEvent d. MouseEvent 68. The _______ interface toolkit has a large set of user-interface components. a. GUI Builder b. graphical user c. Swing d. JMenu 69. For a new programmer using the Swing JSlider component for the first time, which of these is the least important thing to know? a. A basic way to construct a JSlider b. What type of events it generates c. How to write the BoundedRangeModel constructor d. Its value when an event occurs 70. What type of event does the JSlider class generate? a. ChangeEvent b. ActionEvent c. ItemEvent d. SliderEvent 71. What method is required by the ChangeListener interface? a. changeOccured b. actionPerformed c. stateChanged d. sliderMoved 72. Which code will create a JSlider with a range from 0 to 100, with an initial value of 50? I new JSlider() II new JSlider(0, 100, 50) III new JSlider(50, 0, 100) a. Only I b. Only II c. Only III d. I and II 73. The ChangeEvent class defines no methods. What makes it possible to call the getSource method on a ChangeEvent object? a. The method is inherited from the Object class. b. You have to code that method yourself. c. The method is inherited from the EventObject class. d. ChangeEvent implements the Event interface Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch20 74. If one ChangeListener is listening for three different JSlider objects, how can we determine which of the three sliders caused the event when the code enters the stateChanged method? a. It is not possible. b. We can compare the sliders using the getSource method. c. We can call the getValueIsAdjusting method. d. We can compare the sliders using the getSliderSource method. 75. Which of the following statements is correct? a. new JSlider() creates a horizontal slider with the range 0 to 200 and an initial value of 100. b. new JSlider() creates a horizontal slider with the range 0 to 10 and an initial value of 5. c. new JSlider() creates a horizontal slider with the range 0 to 100 and an initial value of 50. d. new JSlider() creates a horizontal slider with the range 0 to 150 and an initial value of 100. 76. What code would be the most appropriate assist in getting notified when a user interacts with a JSlider? a. public JSlider(BoundedRangeModel brm) b. public void addChangeListener(ChangeListener l) c. JSlider() d. public JSlider(int min, int max, int value)

Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch20 Answer Key 1. a 2. d 3. b 4. a 5. d 6. b 7. c 8. a 9. d 10. b 11. a 12. b 13. b 14. b 15. a 16. b 17. a 18. c 19. c 20. d 21. d 22. c 23. c 24. d 25. a Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch20 26. b 27. a 28. b 29. b 30. b 31. a 32. b 33. c 34. a 35. b 36. d 37. a 38. d 39. c 40. d 41. d 42. c 43. d 44. a 45. b 46. d 47. b 48. d 49. c 50. b 51. d Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch20 52. a 53. a 54. c 55. a 56. b 57. d 58. d 59. a 60. b 61. c 62. c 63. d 64. a 65. a 66. a 67. b 68. c 69. c 70. a 71. c 72. d 73. c 74. b 75. c 76. b Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch20

Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch21

Indicate the answer choice that best completes the statement or answers the question. 1. Which file storage method is in human-readable form? a. byte b. text c. binary d. object 2. In text format, data items are represented in human-readable form, as a sequence of ____________________. a. integers b. strings c. bytes d. characters 3. Which file storage method stores data in bytes? a. binary b. byte c. text d. object 4. A byte is composed of ____ bits and can denote ____ values. a. 8, 256 b. 4, 256 c. 8, 1024 d. 2, 19 5. Which is an advantage of storing numbers in binary format? I fast access II less storage needed III easy to read in a text editor a. I and II only b. I only c. III only d. I and III only 6. Readers and writers access sequences of ____. a. bytes b. files c. streams d. characters 7. Streams access sequences of ____. a. bytes b. files c. characters Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch21 d. strings 8. Which class is used for input of text data? a. OutputStream b. Writer c. InputStream d. Reader 9. Which class is used for input of binary data? a. OutputStream b. Reader c. InputStream d. Writer 10. Which class is used for input of text data from a file? a. FileWriter b. RandomAccessFile c. FileInputStream d. Scanner 11. Which class is used for input of binary data from a file? a. FileInput b. FileInputStream c. Scanner d. Reader 12. Which class is used for output of text data? a. OutputStream b. Reader c. InputStream d. Writer 13. Which class is used for output of binary data? a. Reader b. Writer c. OutputStream d. InputStream 14. Which class is used for output of text data to a file? a. FileWriter b. FileOutputStream c. PrintWriter d. RandomAccessFile

Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch21 15. Which class is used for output of binary data to a file? a. Writer b. FileOutputStream c. FileOutput d. Scanner 16. Which of these classes access sequences of characters? I readers II writers III streams a. II and III only b. II only c. I only d. I and II only 17. If you store information in binary form, as a sequence of bytes, you will use the ____ class(es) and their subclasses. a. Reader and Writer b. PrintWriter c. Serializable d. InputStream and OutputStream 18. If you access and store information in binary form in files, you will use the ____ class(es). a. Scanner and PrintWriter b. PrintStream c. FileInputStream and FileOutputStream d. Reader and Writer 19. Fill in the blank in the following code snippet to create an object for reading binary data from a disk file, named input.bin?

try (______________________________) { Process input } a. FileReader in = new FileReader("input.bin"); b. FileWriter in = new FileWriter("input.bin"); c. PrintWriter in = new PrintWriter("input.bin"); d. FileInputStream in = new FileInputStream("input.bin"); 20. The ______ method returns an integer, either -1 (at the end of the file) or a byte between 0 and 255. a. InputStream.read b. OutputStream.write Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch21 c. Reader.length d. Scanner.next 21. Why does FileInputStream override the read method from its superclass InputStream? a. In order to read binary data. b. In order to return a char. c. To check for end of file. d. To read data from a file. 22. The read method of the FileInputStream class reads binary data. What type is actually returned from a call to read? a. int b. String c. byte d. char 23. What is returned by the read method when a FileInputStream has reached the end of the file? a. 0 b. -1 c. -2 d. '\n' 24. How many bytes does the read method in the FileInputStream class get from the file? a. 1 b. 8 c. 4 d. 2 25. Fill in the blank in the following code snippet to create an object for writing binary data to a disk file, named output.bin?

try (______________________________) { Process output } a. Writer out = new Writer("output.bin"); b. PrintWriter out = new PrintWriter("output.bin"); c. FileOutputStream out = new FileOutputStream("output.bin"); d. FileWriter out = new FileWriter("output.bin"); 26. Which class has a write method that writes a single byte? a. Stream Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch21 b. PrintWriter c. OutputStream d. Writer 27. Which statement is NOT correct about the OutputStream.write method? a. The method writes an int (4 bytes) to the output stream. b. The type of the parameter for the method is int. c. The FileOutputStream class overrides the method to write a single byte to a file. d. The value of the parameter must be between the values of 0 and 255. 28. You cannot read a ____________________ file with a text editor. a. serial b. binary c. random d. sequential 29. A Caesar cipher uses a shift of each character by a key with a value between 1 and 255. An a with a shift of 3 becomes a d. A z with a shift of 3 would become a c, wrapping around the alphabet. Which is the encryption of shadow for a key = 3? a. adowsha b. vkdgrz c. vjegrz d. ukdgry 30. A Caesar cipher uses a shift of each character by a key with a value between 1 and 255. An a with a shift of 3 becomes a d. A z with a shift of 3 would become a c, wrapping around the alphabet. Which is the encryption of picture for a key = 3? a. mfzqrob b. erutcip c. urepict d. ngahspc 31. A Caesar cipher uses a shift of each character by a key with a value between 1 and 255. An a with a shift of 3 becomes a d. A z with a shift of 3 would become a c, wrapping around the alphabet. Which key should you use to encrypt picture into mfzqrob? a. 19 b. -3 c. -19 d. 3 32. A Caesar cipher uses a shift of each character by a key with a value between 1 and 255. An a with a shift of 3 becomes a d. A z with a shift of 3 would become a c, wrapping around the alphabet. Which is the decryption of exmmv for a key = 3? a. bujjs b. atiir Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch21 c. cvkkt d. happy 33. You would need a Caesar cipher with a shift of __________ to decrypt the text T U V W X Y Z A B C D E F G H I J K L M N O P Q R S so that it reads A B C D E F G H I J K L M N O P Q R S T U V W X Y Z. a. 19 b. 7 c. -19 d. 20 34. A Caesar cipher uses a shift of each character by a key with a value between 1 and 255. An a with a shift of 3 becomes a d. For the encrypt method below, select the correct body. Assume the key shift property is accessible to the method.

public int encrypt(int b) { __________ } a. return (b + key) % 256); b. return (b + key % 26); c. return (b + key); d. return (b + 26 % key); 35. Caesar cipher uses a shift of each character by a key with a value between 1 and 255. An a with a shift equal to 3 becomes a d. For the decrypt method below, select the correct body. Assume the key shift property is accessible to the method.

public int decrypt(int b) { __________ } a. return (b - key); b. return (b + key); c. return (b - key % 26); d. return (b - key) % 256); 36. What is the highest value for a signed (negative and positive) byte? a. 256 b. 127 c. 128 d. 255 37. What is the lowest value for a signed (negative and positive) byte? a. -128 b. -256 Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch21 c. -255 d. -127 38. The values of the byte type range from ____ to ____. a. -128, 127 b. 0, 256 c. -128, 128 d. 0, 255 39. In Java, the byte type is a(n) ____ type. a. unsigned b. positive c. signed d. negative 40. In ____________ file access, the file is processed starting from the beginning. a. binary b. random c. parallel d. sequential 41. __________ access allows file access at arbitrary locations, without first reading the bytes preceding the access location. a. Sequential b. Serial c. Random d. Binary 42. A file pointer is a position in a random access file. Because files can be very large, the file pointer is of type _______. a. int b. double c. long d. byte 43. Which method moves the file pointer in a RandomAccessFile? a. close b. seek c. length d. getFilePointer 44. Which code moves the file pointer to the middle of a RandomAccessFile object, file? a. file.seek(file.getFilePointer() / 2) b. file.seek(file.length() / 2) c. file.seek(0L) Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch21 d. file.seek(file.length()) 45. In which of the following modes can a RandomAccessFile be opened? I r II rw III w a. I and III only b. I only c. I and II only d. II only 46. What do we call the measure in bytes of the file pointer from the beginning of a RandomAccessFile? a. size b. seek c. latency d. offset 47. Which is NOT a method in the RandomAccessFile class? a. seek b. length c. getFilePointer d. scan 48. Which method in the RandomAccessFile class provides for random access? a. goto b. offset c. seek d. move 49. Which of the following classes are used with data in binary form? I FileInputStream II FileReader III RandomAccessFile a. I and III only b. I and II only c. II and III only d. I only 50. Which is not a method available in the RandomAccessFile class? a. readDouble b. open c. readInt d. close 51. When storing numbers in a file with fixed record sizes, it is easier to store them in __________ format. Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch21 a. character b. binary c. serializable d. text 52. Based on the code below, the statement that would move the file pointer to byte n counted from the beginning of the file is ___________________.

RandomAccessFile test = new RandomAccessFile("record.bat", "r"); a. test.getFilePointer(n); b. test.length() – n; c. test.seek(n); d. test.getFilePointer(); 53. The readInt and writeInt methods of the RandomAccessFile class read and write integers as ____ quantities. a. two-byte b. four-byte c. eight-byte d. six-byte 54. The readDouble and writeDouble methods of the RandomAccessFile class, process double precision floating-point numbers as ____ quantities. a. ten-byte b. two-byte c. four-byte d. eight-byte 55. Given a RandomAccessFile that stores a set of records of class MyData, each needing MyData.RECORD_SIZE bytes for storage, which expression gets the offset to the beginning of the 25th record? a. MyData.RECORD_SIZE * 25 b. MyData.RECORD_SIZE + 25 c. MyData.RECORD_SIZE++ d. MyData.RECORD_SIZE * 24 56. Assume we have a RandomAccessFile object, file, which stores a set of records of class MyData, each needing MyData.RECORD_SIZE bytes for storage. If the file pointer is currently on the 24th record, which expression represents the offset to the beginning of the 25th record? a. MyData.RECORD_SIZE * 2 b. MyData.RECORD_SIZE + file.getFilePointer() c. MyData.RECORD_SIZE + 1 d. file.getFilePointer() 57. Assume we have a RandomAccessFile object, file, which stores a set of records of class MyData, each Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch21 needing MyData.RECORD_SIZE bytes for storage. Which expression calculates the number of records in the file? a. MyData.RECORD_SIZE * file.length() b. file.length() / MyData.RECORD_SIZE c. MyData.RECORD_SIZE + file.getFilePointer() d. file.seek(0L) / MyData.RECORD_SIZE 58. Assume we have a RandomAccessFile object, file, which stores a set of records of class MyData. The size of each record is MyData.RECORD_SIZE. Assume MyData has read and write methods, both of which take a RandomAccessFile as an argument. Method write writes the object at the current location. Method read reads the record from current location of the file into the object. If we are currently at the beginning of the 25th record, which code correctly modifies the 25th record by changing its color to Color.yellow through the setColor method? a. myData.read(file); myData.setColor(Color.yellow); file.seek(file.getFilePointer() + MyData.RECORD_SIZE); myData.write(file); b. myData.read(file); myData.setColor(Color.yellow); myData.write(file); c. myData.read(file); myData.setColor(Color.yellow); file.seek(file.getFilePointer()); myData.write(file); d. long loc = file.getFilePointer(); myData.read(file); myData.setColor(Color.yellow); file.seek(loc); myData.write(file);

59. Assume we have a RandomAccessFile object, file, that stores a set of records of class MyData. The size of each record is MyData.RECORD_SIZE. Assume MyData has read and write methods both of which take a RandomAccessFile as an argument. Method write writes the object at the current location. Method read reads the record from current location of the file into the object. If we are currently at the beginning of the 1st record, which code correctly modifies the 2nd record by changing its color to Color.red through the setColor method? a. myData.read(file); myData.read(file); myData.setColor(Color.red); myData.write(file); b. file.seek(MyData.RECORD_SIZE); myData.read(file); myData.setColor(Color.red); file.seek(MyData.RECORD_SIZE); myData.write(file); c. long loc = file.getFilePointer(); myData.read(file); myData.setColor(Color.red); file.seek(loc); myData.write(file); d. myData.read(file); myData.setColor(Color.red); file.seek(file.getFilePointer() + MyData.RECORD_SIZE); myData.write(file);

Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch21 60. Which statement about object streams is NOT correct? a. Use object input streams to load the saved objects. b. You must cast the returned result from the readObject method. c. Any object can be saved to an object output stream. d. Use object output streams to save all instance variables of an object automatically. 61. If you write a simple Student class, what must you do in order to write Student objects to an ObjectOutputStream? a. Make all class variables primitive. b. Implement Streamable. c. Code a write method. d. Implement Serializable. 62. Which of the following cannot be serialized? I ArrayList<String> II String III Integer a. I only b. III only c. II and III only d. All can be serialized 63. Objects are saved in ___________ format in object streams. a. integer b. binary c. stream d. character 64. The two IO classes used for serialization are _______ and ________. a. Reader, Writer b. ObjectInputStream, ObjectOutputStream c. FileReader, FileWriter d. Scanner, PrintWriter 65. Which methods are not in the Serializable interface? I readObject II writeObject III serializeObject a. II and III only b. I, II, and III c. I and II only d. I only 66. Which of the following classes are related through inheritance? Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch21 I InputStream II InputStreamReader III ObjectInputStream a. I, II and III b. I and III only c. II and III only d. I and II only 67. Which interface allows classes to be written to an ObjectOutputStream? a. Streaming b. Serializable c. Objectifiable d. Objective 68. How many methods are required to implement the Serializable interface? a. 3 b. 1 c. 0 d. 2 69. Every object is assigned a serial number on the stream. What might be the result if the same object is saved twice? a. A performance decrease. b. Running out of serial numbers. c. The object will have two serial numbers. d. Only the serial number is written out the second time. 70. If serializing object obj requires 12 bytes, how many bytes are required to serialize obj 3 times? a. 12 bytes plus 3 serial numbers of obj b. 36 bytes c. 12 bytes d. 12 bytes plus 2 serial numbers of obj 71. Objects saved to an object stream must belong to classes that ______________. a. implement the ObjectInputStream interface b. are RandomAccessFile objects c. implement the Serializable interface d. are abstract 72. What type is returned from a call to the ObjectInputStream.readObject method when reading a String from an object stream? a. String b. ObjectStream c. Object d. char Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch21 73. If we want to write objects to a file, what type of object should be passed to the ObjectOutputStream constructor? a. FileOutputStream b. ObjectStream c. ObjectInputStream d. FileStream 74. Which code stores an array studentArray of Student objects in a file named studentFile.bin? We ignore exceptions in this problem. a. try (ObjectOutputStream oos = new ObjectOutputStream("studentFile.bin")) {

oos.writeObject(studentArray); } b. try (ObjectStream oos = new ObjectStream(new FileOutputStream("studentFile.bin"))) { oos.writeObject(studentArray); } c. try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("studentFile.bin"))) { oos.writeObject(studentArray[0]); } d. try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("studentFile.bin"))) { oos.writeObject(studentArray); }

75. Which code reads an array of Student objects from a file named studentFile.bin? We ignore exceptions in this problem. a. try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("studentFile.bin"))) { Student[] studentArray = ois.readObject(); } b. try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("studentFile.bin"))) { Student[] studentArray = (Student[]) ois.read(); } c. try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("studentFile.bin"))) { Student[] studentArray = (Student[]) ois.readObject(); } d. try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("studentFile.bin"))) { Student[] studentArray = ois.read(); }

Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch21 76. What type of object describes the location of a file or directory? a. Path b. Paths c. Files d. Directories 77. Fill in the blank in the following code snippet.

______ myVariable = Paths.get("filename.txt"); a. FileReader b. File c. Path d. FileInputStream 78. Which of the following is NOT a method of the Path type? a. walk b. getParent c. resolve d. getFileName 79. In which package are the following types found: Path, Paths, Files? a. java.io.file b. java.nio c. java.nio.file d. java.io 80. Which expression returns a String representing the full path to the file filename.txt? a. Paths.get("filename.txt") b. Paths.get("filename.txt").toString() c. Paths.get("filename.txt").toAbsolutePath() d. Paths.get("filename.txt").toAbsolutePath().toString() 81. Which of the following is NOT a method of the Files class? a. createFile b. createTempDirectory c. createDirectory d. deleteFile 82. Which expression creates an empty file named filename.txt? a. Files.createFile("filename.txt") b. Files.createFile(Paths.get("filename.txt")) c. Files.createFile(new File("filename.txt")) d. Files.create(Paths.get("filename.txt")) Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch21 83. Which expression deletes the file named filename.txt? a. Files.delete(Paths.get("filename.txt")) b. Files.deleteFile(Paths.get("filename.txt")) c. Files.deleteFile("filename.txt") d. Files.delete("filename.txt") 84. Which of the following is NOT a method of the Files class? a. readAllBytes b. write c. readAllLines d. read 85. Which expression determines whether there is a configuration file named config.txt? a. Files.exists("config.txt") b. exists(Paths.get("config.txt")) c. exists(Files.get("config.txt")) d. Files.exists(Paths.get("config.txt")) 86. Which statement reads the configuration file named config.txt into a collection for later processing? a. List<String> configData = Files.read(Paths.get("config.txt")); b. List<Byte> configData = Files.readAllBytes(Paths.get("config.txt")); c. List<String> configData = Files.readAllLines("config.txt"); d. List<String> configData = Files.readAllLines(Paths.get("config.txt")); 87. Fill in the blank in the following code snippet that filters log warning messages to a file.

try(Stream<String> lines = Files.lines(Paths.get("messages.txt"))) { List<String> warnings = lines .filter(m -> m.contains("WARNING")) .collect(Collectors.toList()); ______________________________________ } a. Files.write("warnings.txt", warnings); b. Files.writeAllLines(Paths.get("warnings.txt"), warnings); c. Files.writeAllBytes(Paths.get("warnings.txt"), warnings.getBytes("UTF8")); d. Files.write(Paths.get("warnings.txt"), warnings); 88. Fill in the blank in the following code snippet that displays the java files in the current directory.

try(_______________________________________) { listing .map(p -> p.toString()) Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch21

.filter(s -> s.endsWith(".java")) .sorted() .forEach(j -> System.out.println(j)); } a. Stream<String> listing = Files.list(Paths.get("")) b. Stream<String> listing = Files.lines(Paths.get("")) c. Stream<Path> listing = Files.list(Paths.get("")) d. Stream<Path> listing = Files.list("") 89. Fill in the blank in the following code snippet that displays the names of directories in the current directory.

try(Stream<Path> listing = Files.list(Paths.get(""))) { listing .filter(p -> _________________) .map(d -> d.toString()) .forEach(s -> System.out.println(s)); } a. Files.isDirectory(p) b. isDirectory(p) c. p.isDirectory() d. Paths.isDirectory(p) 90. Fill in the blank in the following code snippet that displays the directory structure for the current directory, i.e., including the descendants of the current directory that are directories.

try(_______________________________) { listing .filter(p -> Files.isDirectory(p)) .map(d -> d.toString()) .forEach(s -> System.out.println(s)); } a. Stream<Path> listing = Files.list(Paths.get("")) b. Stream<Path> listing = Files.walk(Paths.get("")) c. Stream<String> listing = Files.walk(Paths.get("")) d. Stream<Path> listing = Files.walk("")

Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch21 Answer Key 1. b 2. d 3. a 4. a 5. a 6. d 7. a 8. d 9. c 10. d 11. b 12. d 13. c 14. c 15. b 16. d 17. d 18. c 19. d 20. a 21. d 22. a 23. b 24. a 25. c Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch21 26. c 27. a 28. b 29. b 30. a 31. b 32. a 33. c 34. a 35. d 36. b 37. a 38. a 39. c 40. d 41. c 42. c 43. b 44. b 45. c 46. d 47. d 48. c 49. a 50. b 51. b Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch21 52. c 53. b 54. d 55. d 56. b 57. b 58. d 59. b 60. c 61. d 62. d 63. b 64. b 65. b 66. b 67. b 68. c 69. d 70. d 71. c 72. c 73. a 74. d 75. c 76. a Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch21 77. c 78. a 79. c 80. d 81. d 82. b 83. a 84. d 85. d 86. d 87. d 88. c 89. a 90. b

Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch22

Indicate the answer choice that best completes the statement or answers the question. 1. Given a two-CPU machine and four threads, how many of the threads can execute in parallel? a. Only 1 can execute at a time. b. 2 can execute in parallel. c. 3 can execute in parallel. d. All 4 can execute in parallel. 2. The Runnable interface includes which method(s)? I public void run(Runnable runnable) II public void run() III public void start() a. Only I b. Only II c. I and II d. II and III 3. Which method(s) are part of the Thread class? I public void run(Runnable runnable) II public void start(Runnable runnable) III public void start() a. Only I b. Only II c. Only III d. II and III 4. Which of the following class declarations could run in a thread? I public interface MyRunnable extends Runnable { . . . } II public class MyRunnable extends Runnable { . . . } III public class MyRunnable implements Runnable { . . . } a. Only II b. Only III c. I and II d. II and III 5. Which of the following does not create an object that can run in a thread, assuming the following MyRunnable class declaration? public class MyRunnable implements Runnable { . . . } I Runnable runnable = new Runnable(); II Runnable runnable = new MyRunnable(); III MyRunnable runnable = new MyRunnable(); a. Only I b. Only III c. I and II d. II and III Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch22 6. In which method are the tasks that are performed by a thread coded? a. start b. main c. run d. init 7. Which method do you call to make a thread ineligible to run on the CPU for a set number of milliseconds? a. start b. wait c. await d. sleep 8. Which exception must be caught or declared when calling the sleep method? a. IOException b. IllegalStateMonitorException c. InterruptedException d. SleepException 9. Which constructor can be used to create a new thread associated with a Runnable object? a. public Thread(Runnable r) b. public Thread() c. public Runnable(Thread t) d. public Thread(String s) 10. For threads of equal priority, which is guaranteed by the thread scheduler that is part of the Java Virtual Machine? I All will get time on the CPU II All will get exactly equal time on the CPU III The order threads run in the CPU will always be the same a. Only I b. Only II c. I and III d. II and III 11. If you do not use the Runnable interface, what is necessary to create a new thread? I Implement the Threadable interface II Extend the Thread class and add a run() method to it III Add a run method to any class a. Only I b. Only II c. Only III d. I and III 12. Suppose run1 and run2 are objects of the class MyRunnable, which implements the Runnable interface. What is the result of the following calls? Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch22

run1.run(); run2.run(); a. run1 and run2 execute as independent threads. b. Syntax error c. Only run1 executes as an independent thread. d. run1 and run2 run sequentially, not as independent threads. 13. When a sleeping thread is interrupted, an InterruptedException is generated. Where do you catch that exception? a. in the start() method. b. in the sleep() method. c. in the run() method. d. in the interrupt() method. 14. The _____________ interface is designed to encapsulate the concept of a sequence of statements that can run in parallel with other tasks, without equating it with the concept of a thread, a potentially expensive resource that is managed by the operating system. a. Thread b. Runnable c. MyRunnable d. Threadable 15. The ________ method stops the current thread for a given number of milliseconds. a. run b. await c. sleep d. delay 16. When a thread is interrupted, the most common response is to terminate the ____________ method. a. run b. thread c. sleep d. await 17. When a sleeping thread is interrupted, a(n) ____________________ is generated. a. ThreadInterruptedException b. ThreadException c. ThreadSleepException d. InterruptedException 18. To start a thread, you should first construct an object from a class that implements the ____________ interface. a. Thread b. Threadable Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch22 c. Run d. Runnable 19. Insert the statement that would start the following thread.

Thread firstThread = new Thread(myRunnable); ____________________ a. firstThread.run(); b. firstThread.start(); c. run(); d. start(); 20. Each thread runs for a short amount of time, called a ____________________. a. thread allotment b. thread time slot c. time slice d. run time slice 21. A(n) ____ uses a small number of threads to execute a large number of runnables. a. embedded system b. condition object c. thread pool d. race condition 22. Which argument(s) present(s) the best case(s) for extending the Thread class rather than using the Runnable interface in conjunction with a thread pool? I Thread sub-classes will all execute independently II Runnable objects will waste more system resources III Thread sub-classes can execute faster on a single CPU than Runnable objects a. Only I b. Only II c. Only III d. II and III 23. What is likely to be true when thread one is downloading a 1MB file while thread two is downloading another 1MB file? a. The files download twice as fast as they would if one thread downloaded both files. b. The files download half as fast as they would if one thread downloaded both files. c. When thread one is half done, thread two is about half done. d. The faster thread will interrupt the other thread. 24. Suppose thread one is downloading a 800KB file while another thread is processing the same file on a single CPU machine. Suppose further that one time slice allows the first thread to download about 10KB and that the second thread can process 10KB of the file in one time slice. The second thread can process the file while it is incomplete. How many total time slices will it take for the first 10 KB to be downloaded and processed? Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch22 a. one b. two c. eight d. ten 25. Suppose thread one is downloading a 800KB file while another thread is processing the same file on a single CPU machine. Suppose further that one time slice allows the first thread to download about 10KB and that the second thread can process 10KB of the file in one time slice. The second thread can process the file while it is incomplete. How many total time slices will it take to process half the file? a. thirty b. forty c. eighty d. hundred 26. Suppose thread one is downloading a large file while another thread is processing the same file on a single CPU machine. The time required to download and process a portion of the file is the same. The second thread can process the file while it is incomplete. What is the main benefit of using two threads rather than using a single thread to do both parts of the job? a. accuracy of the results b. speed to compete entire job c. speed of availability of partial results d. less memory is used 27. Suppose thread one is downloading a 800KB file while another thread is processing the same file on a multi-CPU machine. Suppose further that one time slice allows the first thread to download about 10KB and that the second thread can process 10KB of the file in one time slice. The second thread can process the file while it is incomplete. What is the minimum number of CPUs that will allow the job to be completed in roughly half the time of a single-CPU machine? a. 1 b. 2 c. 3 d. 4 28. What happens if we try to start a thread with an instance of a Runnable class that did not override the run method? a. A compiler error. b. A checked exception is thrown. c. The inherited method runs and does nothing. d. The thread sleeps indefinitely. 29. Suppose that the class XYZ implements the interface Runnable. Which code creates a thread object and makes it available to the scheduler to be executed? a. Thread t = new Thread(new XYZ()); t.start(); b. XYZ t = new Thread(new XYZ()); t.start(); c. new XYZ().start();

d. Thread t = new XYZ(new Thread()); Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch22 t.start();

30. Given that a new thread named t has been constructed, how can you make multiple threads run parallel to each other? a. t.run() b. t.start() c. t.parallel() d. t.thread() 31. Which of the following is a characteristic of threads? a. The order of the execution of parallel threads is somewhat random b. When running multiple parallel threads, the threads are exactly interleaved c. The thread scheduler executes the threads in the same order as its call d. Parallel threads run exactly at the same time and in the same order 32. A program that creates a large number of short-lived threads can be inefficient in memory and time. Which of the following can reduce the cost of using threads? a. Thread pool b. runnable object c. await d. Long-lived threads 33. Which of the following definitely indicates that a thread has terminated? I The run method has completed II The method Thread.interrupted returns true III The run method catches an InterruptedException a. Only I b. Only II c. I and II d. II and III 34. Which of the following definitely indicates that a thread has been interrupted by another thread? I The run method has completed II The method Thread.interrupted returns true III The run method catches an InterruptedException a. Only I b. Only II c. I and II d. II and III 35. What should be done to get the attention of a thread? a. call the thread’s stop method b. call the thread’s run method c. call the thread’s interrupt method d. call the thread’s sleep method Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch22 36. The sleep method is terminated with a(n) __________ whenever a sleeping thread is interrupted. a. InterruptedException b. SleepException c. lock d. SignalException 37. In the initial release of the Java library, the Thread class had a stop method to terminate a thread. However, that method is now _______________ a. forbidden b. not recommended c. unwise d. deprecated 38. The ___________ method does not actually cause threads to terminate; it merely sets a Boolean field in the thread data structure. a. stop b. await c. sleep d. interrupt 39. The ____________ occurs when a thread that is not running is interrupted. a. InterruptException b. InterruptedException c. ThreadException d. ThreadTerminatedException 40. What is the difference between calling the sleep method versus the await method? a. sleep makes the current thread wait and allows another thread to acquire the lock object while the await pauses the current thread for a set time b. await makes the current thread wait and allows another thread to acquire the lock object while the sleep pauses the current thread for a set time c. sleep handles the current thread while the await handles the next thread d. sleep and await are the same 41. ____ occur(s) if the effect of multiple threads on shared data depends on the order in which the threads are scheduled. a. Pooling b. Interrupted exceptions c. Deadlocks d. Race conditions 42. Examine the SharedData class shown below. Suppose two threads are created so that each has access to the same SharedData object. Thread one calls setSharedData eight times with values 1...8 respectively, sleeping for 30 milliseconds between calls. Thread two calls getSharedData eight times, also sleeping for 30 milliseconds between calls. Suppose thread two receives values 1, 2, 3, 4, 5, 6, 7, 8 respectively on its calls. Should we expect the same values Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch22 for each program run?

public class SharedData { private int value; public void setSharedData(int n) { value = n; } public int getSharedData() { return value; } } a. Yes, because the sleep times are equal in between calls. b. Yes, because that’s the same order used by thread one to set the values. c. No, because thread one may not set the data as 1,2,3,4,5,6,7,8 respectively. d. No, because a race condition may result in a different order. 43. Examine the SharedData class shown below. Suppose two threads are created so that each has access to the same SharedData object. Thread one calls setSharedData eight times with values 1...8 respectively, sleeping for 30 milliseconds between calls. Thread two calls getSharedData eight times, also sleeping for 30 milliseconds between calls. Which of the following orders of values is not possible for thread two to receive?

public class SharedData { private int value; public void setSharedData(int n) { value = n; } public int getSharedData() { return value; } } a. 1,2,3,4,5,6,7,8 b. 1,2,2,4,5,6,7,8 c. 1,2,3,4,5,6,8,8 d. 1,2,3,4,5,6,8,7 44. Examine the SharedData class shown below. Suppose two threads are created so that each has access to the same SharedData object. Thread one calls setSharedData eight times with values 1...8 respectively, sleeping for 100 Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch22 milliseconds between calls. Thread two calls getSharedData eight times, also sleeping for 100 milliseconds between calls. Which of the following could be the last two values received by thread two?

public class SharedData { private int value; public void setSharedData(int n) { value = n; } public int getSharedData() { return value; } } a. 9, 10 b. 10, 9 c. 1, 2 d. 8, 7 45. Examine the SharedData class shown below. Suppose two threads are created so that each has access to the same SharedData object. Thread one calls setSharedData ten times with values 1...10 respectively, sleeping for a random number of milliseconds between calls. Thread two calls getSharedData eight times, also sleeping for a random number of milliseconds between calls. Which of the following could be the last two values received by thread two?

public class SharedData { private int value; public void setSharedData(int n) { value = n; } public int getSharedData() { return value; } } a. 8, 10 b. 10, 9 c. 10, 8 d. 8, 7

Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch22 46. Assume two threads share a BankAccount object with balance of zero (0), and that the BankAccount class provides deposit and withdraw methods as shown below. Thread one deposits $10 ten times and, concurrently, thread two withdraws $10 ten times. Suppose a race condition occurs, and the race is finished first by thread one. What would you expect balance to be after all thread calls?

public void deposit(int dollars) { int newBalance = balance + dollars; System.out.println("depositing"); balance = newBalance; } public void withdraw(int dollars) { int newBalance = balance - dollars; System.out.println("withdrawing"); balance = newBalance; } a. $10 b. $20 c. $0 d. a negative amount 47. Assume two threads share a BankAccount object with balance of zero (0), and that the BankAccount class provides deposit and withdraw methods as shown below. Thread one deposits $10 ten times and, concurrently, thread two withdraws $10 ten times. If the balance after all thread calls is 0, which statement is definitely true?

public void deposit(int dollars) { int newBalance = balance + dollars; System.out.println("depositing"); balance = newBalance; } public void withdraw(int dollars) { int newBalance = balance - dollars; System.out.println("withdrawing"); balance = newBalance; } a. The calls were interleaved: thread one, thread two, thread one, thread two, … b. The first call was to the deposit method. c. The last call was to the withdraw method. d. Each individual call to the deposit and withdraw methods ran to completion. Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch22 48. What is the condition called where the effect of multiple threads on shared data depends on the order in which the threads are scheduled? a. Lock condition b. Race condition c. Run condition d. Synchronizing access condition 49. Assume two threads share a BankAccount object with balance of zero (0), and that the BankAccount class provides deposit and withdraw methods and has a ReentrantLock named myLock, as shown below. Note that only the deposit method uses the lock. Thread one deposits $10 ten times and, concurrently, thread two withdraws $10 ten times. Which statement regarding the balance after all thread calls is definitely true?

public void deposit(int dollars) { myLock.lock() int newBalance = balance + dollars; System.out.println("depositing"); balance = newBalance; myLock.unlock() } public void withdraw(int dollars) { int newBalance = balance - dollars; System.out.println("withdrawing"); balance = newBalance; } a. The balance could be zero or positive. b. The balance is zero. c. The balance could be zero or negative. d. The balance is positive. 50. A(n) ____ object is used to control the threads that want to manipulate a shared resource. a. condition b. lock c. interrupt d. runnable 51. Consider the addFirst method of the LinkedList class in Chapter 16:

/** Adds an element to the front of the linked list. @param element the element to add */ public void addFirst(Object element) { Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch22

Node newNode = new Node(); newNode.data = element; newNode.next = first; first = newNode; } Three implementations have been proposed to make the addFirst method thread safe where listLock is an instance variable of type ReentrantLock. Which of them will work? I.

listLock.lock(); try { Node newNode = new Node(); newNode.data = element; newNode.next = first; } finally { listLock.unlock(); } first = newNode; II.

Node newNode = new Node(); newNode.data = element; newNode.next = first; listLock.lock(); try { first = newNode; } finally { listLock.unlock(); } III.

listLock.lock(); try { Node newNode = new Node(); newNode.data = element; newNode.next = first; first = newNode; } finally Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch22

{ listLock.unlock(); } a. Only I b. I and II c. Only III d. I and III 52. Which phrase best describes the purpose of a lock used in an object in one or more of its methods? a. increased sharing b. mutual exclusion c. speed increase d. privacy protection 53. The term "starvation" means a situation where when one thread runs continuously, while another thread never does. Consider the following three conditions (list I,II,III). Which set of these conditions is sufficient to cause starvation? I Thread one is in an infinite loop II Thread one possesses a lock and does not unlock it, but thread two requires the lock III Thread one requires a lock, but thread two possesses the lock a. Only I b. Only II c. I and II d. I and III 54. If a thread sleeps after acquiring a _________, it blocks all other threads that want to acquire it. a. condition b. signal c. lock d. thread 55. The ________ method is called by a thread that has just changed the state of some shared data in a way that may benefit waiting threads. a. run b. lock c. unlock d. signalAll 56. The thread that calls signalAll must own the lock that belongs to the condition object on which signalAll is called. Otherwise, a(n) _______ ________ is thrown. a. InterruptException b. IllegalMonitorStateException c. ThreadException d. ThreadTerminatedException

Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch22 57. The ____ method is useful only if you know that a waiting thread can actually proceed. a. run b. signal c. await d. interrupted 58. ____ allow a thread to temporarily release a lock, so that another thread can proceed, and to regain the lock at a later time. a. Condition objects b. Embedded systems c. Exceptions d. Race conditions 59. Which of the following statements is correct? a. If a thread sleeps after acquiring a lock, it blocks all other threads that want to use the same lock. b. When a thread calls await, it is simply deactivated in the same way as a thread that reaches the end of its time slice. c. A thread pool is designed to encapsulate the concept of a sequence of statements that can run in parallel with other tasks, without equating it with the concept of a thread, a potentially expensive resource that is managed by the operating system. d. Under no circumstances should you terminate a running thread. 60. Consider the following change to the deposit method in Section 22.4:

public void deposit(double amount) { balanceChangeLock.lock(); try { double newBalance = balance + amount; balance = newBalance; } finally { balanceChangeLock.unlock(); } System.out.println("Depositing " + amount + ", new balance is " + balance); } What is the consequence of this change? a. The bank account balances may no longer be correctly updated. b. The printouts may become intermingled. c. The printouts may no longer display the correct balances. d. All of the above.

Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch22 61. Calling the wait method in synchronized code is very similar to what action after locking with a ReentrantLock object? a. Calling notify. b. Locking a ReentrantLock object. c. Calling await on a condition object. d. Calling signalAll on a condition object. 62. Assume two threads share a BankAccount object with balance of zero (0), and that the BankAccount class provides synchronized deposit and withdraw methods. Thread one deposits $10 ten times and, concurrently, thread two withdraws $10 ten times. Which statement regarding the balance after all thread calls is definitely true?

public synchronized void deposit(int dollars) { int newBalance = balance + dollars; System.out.println("depositing"); balance = newBalance; } public synchronized void withdraw(int dollars) { int newBalance = balance - dollars; System.out.println("withdrawing"); balance = newBalance; } a. The balance could be zero or positive. b. The balance is zero. c. The balance could be zero or negative. d. The balance is positive. 63. What is the relationship between synchronized code and code that is locked using a ReentrantLock object? a. synchronized code stops the race condition, locks do not. b. synchronized is a single lock, but we may have many ReentrantLock objects. c. The two are exactly the same. d. The two concepts are not related. 64. Class MyClass has a single ReentrantLock object, myLock. Suppose thread one calls myLock.lock() as it enters methodX and immediately completes its CPU time slice. What will happen as thread two calls methodY and attempts to call myLock.lock()? a. Thread two will wait for the lock. b. Thread two will acquire the lock. c. Deadlock will occur. d. Thread two causes the IllegalStateMonitorException. 65. Class MyClass has two ReentrantLock objects, myLock1 and myLock2. Suppose thread one acquires myLock1 as it enters methodX and immediately completes its CPU time slice. After thread two enters methodY, it acquires myLock2 and tries to acquire myLock1. When thread one resumes, it tries to acquire myLock2. What will Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch22 happen next? a. Thread two will acquire myLock1 b. Thread one will acquire myLock2 c. Deadlock will occur d. Thread two will release myLock2 66. Under what conditions are locks unnecessary for multi-threaded programs? a. When the threads are all of the same class. b. When the threads are different classes. c. When the threads do not share data. d. When the shared data only has a single method. 67. Under what circumstances will a call to signalAll not release a blocked thread that has called await? a. When the thread is sleeping. b. When the thread called await on a different condition object. c. When two or more threads are waiting. d. When the thread called await on the same condition object. 68. Consider an old fashioned telephone booth that can be occupied by one person at a time. Suppose one person went in and dialed a part of her number, and had to leave the booth. A second person went in and dialed a part of his number, and before the number was fully dialed, a connection to some other phone was made. What Java threads analogy fits this scenario? I The two people are the threads II The shared data is the telephone III The state of the object is corrupt a. Only I b. I and II c. II and III d. I, II, and III 69. Consider an old fashioned telephone booth that can be occupied by one person at a time. Suppose one person went in and dialed a part of her number, and had to leave the booth. A second person went in and dialed a part of his number, and before the number was fully dialed, a connection to some other phone was made. What Java threads analogy would prevent this undesirable scenario? I Acquire the lock prior to entering the booth II Dial a complete number when inside the booth III Hang up the phone and release the lock upon exiting the booth a. Only I b. I and II c. I and III d. I, II, and III 70. The term "stale data" refers to a situation in multi-CPU machines when one thread modifies shared data and a second thread accesses that data later, but sees the data value before the change took place. What is required to guarantee that the second thread sees the updated data, not stale data? a. The second thread should not try to acquire the lock. Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch22 b. The first thread should not try to acquire the lock. c. Neither thread should use locks. d. The first thread should release the lock after changing the data. 71. Which of the following scenarios may not always cause a deadlock among two threads? I Thread one is in an infinite loop and has acquired a lock II Both threads are in an infinite loop, and one thread has acquired a lock III Both threads are in an infinite loop, and both threads have acquired locks a. Only I b. Only II c. Only III d. I, II, or III 72. The term "stale data" refers to a situation in multi-CPU machines when one thread modifies shared data and a second thread accesses that data later, but sees the data value before the change took place. What is required to guarantee that the second thread sees the updated data, not stale data when access to the shared data occurs in two different methods? a. One method needs to acquire then release the lock after modifying the data. b. Both methods need to acquire then release the lock after modifying or reading the data. c. Never change any shared object data in multi-CPU machines. d. Never use locks for any shared data in multi-CPU machines. 73. A GUI should be responsive to the user. If a GUI interaction starts a time-consuming task, the GUI may not be responsive to the user until the task completes. Which approach would make the GUI responsive under these circumstances? a. As you run the task, break and check for events. b. Ask the user if she is sure she wants to run the task. c. Run the task in a separate thread. d. Disable the GUI during the task. 74. When is it a good idea to call notifyAll in a synchronized method? a. Whenever you exit it. b. Upon exit, but only if threads before have called wait. c. Upon exit, but only if the thread has replenished a needed resource. d. Immediately upon entering the method. 75. Assume three threads share a BankAccount object with a balance initially zero (0), a ReentrantLock named myLock, and a condition object on myLock named insufficientFunds, as shown below. Thread one calls withdraw(30), then thread two calls withdraw(20) and thread three calls deposit(45). What is the balance after the three calls and after the waiting threads have had a chance to run?

public void deposit(int dollars) { myLock.lock(); int newBalance = balance + dollars; System.out.println("depositing"); balance = newBalance; Powered by Cognero

Page 17


Name:

Class:

Date:

testbank-bj-7-ch22

insufficientFunds.signalAll(); myLock.unlock(); } public void withdraw(int dollars) { myLock.lock(); while (balance < dollars) { insufficientFunds.await(); } int newBalance = balance - dollars; System.out.println("withdrawing"); balance = newBalance; myLock.unlock(); } a. 0 b. 15 or 25 c. 45 d. -5 76. Assume three threads share a BankAccount object with a balance initially zero (0), a ReentrantLock named myLock, and a condition object on myLock named insufficientFunds, as shown below. Thread one calls withdraw(30), then thread two calls withdraw(20) and thread three calls deposit(45). What is the balance after the three calls?

public void deposit(int dollars) { myLock.lock(); int newBalance = balance + dollars; System.out.println("depositing"); balance = newBalance; myLock.unlock(); } public void withdraw(int dollars) { myLock.lock(); while (balance < dollars) { insufficientFunds.await(); } int newBalance = balance - dollars; System.out.println("withdrawing"); balance = newBalance; myLock.unlock(); Powered by Cognero

Page 18


Name:

Class:

Date:

testbank-bj-7-ch22

} a. 0 b. 15 or 25 c. 45 d. -5 77. What happens when a thread calls the signalAll method of a Condition object connected to a lock, if no other thread had called await on that Condition object? a. A compiler error. b. A checked exception is thrown. c. The unlock method call will block. d. Nothing, the program executes normally. 78. Which are ways that a thread can be blocked? I when it is sleeping II waiting for a lock to be available III waiting after calling the await method a. Only I b. I and II c. I and III d. I, II, and III 79. lock objects ensure that shared data are in a consistent state when several threads access them. What is a deadlock? a. When multiple threads try to use the same shared data at the same time, and the threads become undone b. When multiple threads copy the same shared data in order to proceed, consequently leaving the original lock object useless c. When multiple threads intertwine multiple times and the lock object is lost, or unreachable d. When multiple threads are not proceeding because they are currently waiting to acquire the same lock 80. Calling signalAll without locking the object is a common error. What kind of exception would be thrown? a. IllegalArgumentException b. IllegalStateException c. IllegalMonitorStateException d. IllegalFormatException 81. Why does the textbook recommend signallAll over the signal method? a. The signalAll method is always more efficient b. signal can lead to deadlocks when not every waiting thread is able to proceed c. signalAll notifies the waiting threads that sufficient funds is absolutely available, while signal only notifies one at a time d. None of the above 82. In order to unblock a thread after the await call, another method that executes the signalAll method must ____________. Powered by Cognero

Page 19


Name:

Class:

Date:

testbank-bj-7-ch22 a. Be parallel to the current thread b. Be before the await call c. Be on different condition object d. Be on the same condition object

Powered by Cognero

Page 20


Name:

Class:

Date:

testbank-bj-7-ch22 Answer Key 1. b 2. b 3. c 4. b 5. a 6. c 7. d 8. c 9. a 10. a 11. b 12. d 13. c 14. b 15. c 16. a 17. d 18. d 19. b 20. c 21. c 22. a 23. c 24. b 25. c Powered by Cognero

Page 21


Name:

Class:

Date:

testbank-bj-7-ch22 26. c 27. b 28. c 29. a 30. b 31. a 32. a 33. a 34. d 35. c 36. a 37. d 38. d 39. b 40. b 41. d 42. d 43. d 44. c 45. a 46. d 47. d 48. b 49. c 50. b 51. c Powered by Cognero

Page 22


Name:

Class:

Date:

testbank-bj-7-ch22 52. b 53. c 54. c 55. d 56. b 57. b 58. a 59. a 60. c 61. c 62. b 63. b 64. a 65. c 66. c 67. b 68. d 69. c 70. d 71. d 72. b 73. c 74. c 75. b 76. c Powered by Cognero

Page 23


Name:

Class:

Date:

testbank-bj-7-ch22 77. d 78. d 79. d 80. c 81. b 82. d

Powered by Cognero

Page 24


Name:

Class:

Date:

testbank-bj-7-ch23

Indicate the answer choice that best completes the statement or answers the question. 1. Two kinds of data are transmitted between computers: ______________ refers to the data that one computer actually wants to send to another. Network protocol data are the data that describe how to reach the intended recipient and how to check for errors and data loss in the transmission. a. packets b. transmission data c. application data d. socket data 2. The term _____________ data refers to the data that describe how to reach the intended recipient and how to check for errors and data loss in the transmission. a. packet b. socket c. application data d. network protocol 3. The ____________ translates domain names into Internet addresses. a. DSN b. DNIP c. DNS d. TCP 4. IP breaks up large chunks of data into more manageable ____________________. a. packets b. sockets c. application data d. network protocol data 5. The ____________ has one function, to attempt to deliver data from one computer to another across the Internet. a. TCP/IP b. IP c. HTTP d. DNS 6. _____________ attempts reliable delivery of data, with retries if there are failures. It also notifies the sender whether or not the attempt succeeded. a. IP b. FTP c. HTTP d. TCP 7. _______ ________ was developed to enable different local area networks to communicate with each other and has become the basis for connecting computers around the world over the Internet. a. TCP Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch23 b. IP c. FTP d. HTTP 8. ____________________ has no provision for retrying an incomplete transmission. a. TCP b. IP c. FTP d. HTTP 9. Each IP ____ is delivered separately, and each one that is a part of the same transmission can take different routes through the Internet. a. packet b. socket c. address d. port number 10. The ____ is a complex collection of pathways on which a message can travel from one access point to another. a. IP b. HTTP protocol c. HTML d. Internet 11. If a computer wants to request information from gateway.com, it must first ask a(n) ____ server to translate the domain name into a numeric Internet address. a. DNS b. socket c. URL d. IP 12. If your data gets lost or garbled during transmission from one computer to another, what is responsible for ensuring that the recipient is aware of the unfortunate fact and does not rely on incomplete data? a. TCP b. IP c. HTTP d. DNS 13. ____ has built-in provisions for retrying incomplete transmissions. a. TCP b. IP c. DNS d. HTTP 14. What are among the most important pieces of information that must be included in an IP packet? I) The Internet address of the recipient Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch23 II) The URL of the recipient III) The Internet address of the sender IV) The port number of the sender a. Only I, III, and IV b. Only I, II, and III c. Only II, III, and IV d. I, II, III, and IV 15. What does the acronym POP stand for? a. Point to Point b. Post Office Point c. Protocol Of Point d. Post Office Protocol 16. __________________ is the protocol that defines communication between Web browsers and Web servers. a. TCP/IP b. Telnet c. HTTP d. IP 17. In a communication protocol, can the sender indicate how many bytes are contained in the request? a. Yes, the web server does that at the end of the GET request. b. Yes, the web browser does that in POST request. c. Yes, the web browser does that at the end of the HTTP header. d. No, the sender can't indicate how many bytes are contained in the request. 18. What service translates an IP address to a name that is easier to remember? a. Domain Name System b. Transmission Control Protocol c. Distinct Name Signifier d. Uniform Resource Locator 19. Which of the following is false about packets? a. They're one of the products of the IP which makes sending and receiving data more manageable b. They’re numbered and the recipient reassembles them in the correct order c. Each packet is delivered separately d. Different packets that are part of the same transmission must take the same routes through the internet 20. The first time you open a certain webpage, it takes a few seconds to load. Later in the day, you open the same webpage again and it was much quicker. What made this different? a. The server stored the route it took to the webpage the first time and the second time, it displayed another identical copy b. The server stored the page in a cache directory and redisplayed the cache copy c. The browser stored the page in a cache directory and redisplayed the cache copy d. The browser stored the route it took to the webpage the first time and the second time, it displayed another Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch23 identical copy 21. Which of the following protocols is used to send email messages? a. POP b. IP c. SMTP d. TCP 22. Which of the following HTTP commands supplies input to a server-side command and returns the result? a. CONNECT b. DELETE c. HEAD d. POST 23. Which of the following statements is correct? a. HTML is a protocol that describes the command set for web server requests. b. Web servers know how to display HTML documents. c. Web servers know how to issue HTTP commands. d. The Telnet program is not a browser and does not understand HTML tags. 24. Which of the following is not an HTTP command? a. HEAD b. BODY c. PUT d. OPTIONS 25. A(n) ____ is a pointer to an information resource on the World Wide Web. a. URL b. socket c. IP address d. domain name 26. The ____ program is a useful tool for establishing test connections with servers. a. DNS b. HTML c. Telnet d. TCP 27. What does the acronym SMTP stand for? a. Simple Mail Transfer Protocol b. Small Mail Transport Protocol c. Simple Mail Transport Protocol d. Small Mail Transfer Protocol

Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch23 28. The HTTP command HEAD ____________. a. stores the header information of an item on the server. b. deletes the header information of an item from the server. c. requests the header information of an item. d. traces the header information of an item. 29. The HTTP command POST ____________. a. returns the requested item. b. supplies input to a server-side command and returns the result. c. requests input from the server-side command. d. supplies input to a client-side command. 30. The HTTP command GET ____________. a. returns the requested item. b. supplies input to a server-side command. c. requests input from the server-side command. d. supplies input to a client-side command. 31. The HTTP command PUT ____________. a. returns the requested item. b. stores an item on the client. c. stores an item on the server. d. supplies input to a client-side command. 32. The HTTP command DELETE ____________. a. deletes two items, an item on the server and an item from the client. b. deletes an item from the client. c. deletes an item on the server. d. deletes input from a client-side command. 33. The HTTP command TRACE ____________. a. traces the requested item. b. traces an item from the client. c. traces an item on the server. d. traces the server communication. 34. The HTTP command OPTIONS ____________. a. requests the item's communication options. b. returns the item's options from the client. c. returns the item's option on the server. d. changes the options of the item. 35. Which type of protocol defines communication between the web browsers and web servers? a. World Wide Web Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch23 b. Hypertext Transfer Protocol c. Transmission Control Protocol d. Internet Protocol 36. Which of the following is true about web servers? a. Servers know how to display HTML documents b. Servers know nothing about HTML c. Servers know how to issue HTTP commands d. Servers describes the structure of a document 37. Suppose that sock refers to a TCP socket connected to another machine, and in is aScanner. Which code sends the string “Who is there?” to the other machine, receives the return answer, and then prints it? a. PrintWriter pw = new PrintWriter(sock.getOutputStream().println("Who is there?")); InputStream instream = sock.getInputStream(); Scanner in = new Scanner(instream); System.out.println(in.nextLine()); b. PrintWriter pw = new PrintWriter(sock.getInputStream()); pw.println("Who is there?"); pw.flush(); InputStream instream = sock.getInputStream(); Scanner in = new Scanner(instream); System.out.println(in.nextLine()); c. PrintWriter pw = new PrintWriter(sock.getOutputStream()); pw.flush("Who is there?"); InputStream instream = sock.getInputStream(); Scanner in = new Scanner(instream); System.out.println(in.nextLine()); d. PrintWriter pw = new PrintWriter(sock.getOutputStream()); pw.println("Who is there?"); pw.flush(); InputStream instream = sock.getInputStream(); Scanner in = new Scanner(instream); System.out.println(in.nextLine());

38. Write a code fragment that connects to a server running on gorge.divms.uiowa.edu at port 2345 and reads one line of text sent by the server. a. Socket sock = new Socket(gorge.divms.uiowa.edu, 2345); Scanner scan = new Scanner(sock.getOutputStream()); String line = scan.nextLine(); b. Socket sock = new Socket(gorge.divms.uiowa.edu, 2345); Scanner scan = new Scanner(sock.getInputStream()); String line = scan.nextLine(); c. Scanner scan = new Scanner(sock.getInputStream()); Socket sock = new Socket(gorge.divms.uiowa.edu, 2345); String line = scan.nextLine(); d. Socket sock = new Socket(2345, gorge.divms.uiowa.edu); Scanner scan = new Scanner(sock.getInputStream()); String line = scan.next();

39. A ______ is an object that encapsulates a TCP connection. Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch23 a. packet b. socket c. client d. server 40. To connect to the HTTP port (80) of the server yahoo.com, you use: a. Socket s = new Socket(80, yahoo.com); b. Socket s = connect("yahoo.com", 80); c. Socket s = new Socket("yahoo.com", 80); d. java yahoo.com 80 41. For test protocols, turn the socket streams into: a. scanners and readers. b. scanners and printers. c. scanners and writers. d. scanners and servers. 42. Buffering the characters means: a. characters are immediately sent to their destination. b. characters are not placed in an array. c. characters are not immediately sent to their destination. d. characters are being flushed. 43. A print writer buffers the characters that you send to it. To make sure that the server gets a complete request at a time, you need to ________ the buffer. a. print b. send c. scan d. flush 44. The ______ method empties the buffer and forwards all waiting characters to the destination. a. print b. send c. scan d. flush 45. The following command:

java pgmName hostname

/

lets you retrieve any item from a web server. The slash means: a. the port of the hostname. b. the root page of the web server. c. the character to end the command. d. the item name needs to be retrieved. Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch23 46. Which of the following is true about sockets? a. Sockets are needed in order to communicate with a web server b. When data is sent to outstream, the socket automatically forwards it to the server c. The socket closes when transmission over the socket is complete d. Sockets that are part of the same transmission can take different routes through the Internet 47. What are the steps involved in designing a client/server application? I) Design a communication protocol. II) Test the server with the Telnet program. III) Implement the server program. IV) Write a client program. a. Only I b. Only I and II c. Only I, II, and III d. I, II, III, and IV 48. _________ objects are used for communication (IO) between two computers (client and server). a. ServerSocket b. Socket c. ClientSocket d. Packet 49. Which code creates a server socket on port PORT_NUMBER and listens for a connection? a. ServerSocket ss = new ServerSocket(PORT_NUMBER); Socket sock = ss.accept(); b. Socket ss = new Server(PORT_NUMBER); ServerSocket sock = ss.accept(); c. ServerSocket ss = new ServerSocket(); Socket sock = ss.accept(); d. ServerSocket ss = new ServerSocket(PORT_NUMBER); Socket sock = new Socket(ss.accept());

50. Which code fragment creates a server running at port 6666 and sends one line of text, “Hello from earth” over and over to any machine that connects to the server? a. ServerSocket ss = new ServerSocket(6666); Socket sock = ss.accept(); while (true) { PrintWriter pw = new PrintWriter(sock.getOutputStream()); pw.println("Hello from earth"); pw.flush(); pw.close(); } b. ServerSocket ss = new ServerSocket(6666); while (true) { PrintWriter pw = new PrintWriter(sock.getOutputStream()); pw.println("Hello from earth");

Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch23 Socket sock = ss.accept(); } c. ServerSocket ss = new ServerSocket(6666); while (true) { Socket sock = ss.accept(); PrintWriter pw = new PrintWriter(sock.getOutputStream()); pw.println("Hello from earth"); pw.flush(); pw.close(); } d. Socket sock = ss.accept(); while (true) { ServerSocket ss = new ServerSocket(6666); PrintWriter pw = new PrintWriter(sock.getOutputStream()); pw.println("Hello from earth"); pw.flush(); pw.close(); }

51. The ______ method of the ServerSocket class waits for a client connection. a. wait() b. connect() c. accept() d. next() 52. For the server to execute the run method in a separate thread for each client, the application program needs to implement the _____ interface. a. Running b. Runtime c. Server d. Runnable 53. A thread dies ______________ a. when the client quits or disconnects. b. when the run method exits. c. when the client quits or disconnects and/or when the run method exits. d. the thread runs forever in the background. 54. To kill a server that was started in a shell window, ________. a. press Ctrl+C b. press Ctrl+Z c. call the kill method d. servers don’t stop. 55. Sending commands over a socket connection is ___________. a. a high-level approach. Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch23 b. a Medium-level approach. c. a low-level approach. d. a complex approach. 56. Which HTTP command supplies input to a server-side command and return the result? a. Get b. Options c. Put d. Post 57. Suppose you use the URLGet program in Section 23.5 to get a web page that does not exist on a server (which does exist). Assuming that the server is otherwise working properly, what will happen? a. The call to openConnection will throw an exception. b. The call to getResponseCode will return the error code 404. c. The call to getResponseMessage will return null. d. The call to getInputStream will throw an exception. 58. The Java library provides a _________ class that can take care of the socket connection to a web server. a. SocketConnection b. ServerConnection c. ClientConnection d. URLConnection 59. The _________ class makes it easy to fetch a file from a web server. a. FileConnection b. ServerConnection c. ClientConnection d. URLConnection 60. To retrieve the response code from a URLConnection object, you need __________________. a. to cast the HttpURLConnection object to the URLConnect subclass. b. to cast the URLConnection object to the HttpURLConnect subclass. c. to use the getInputStream() method. d. to use the getCodeResponse() method. 61. To retrieve the response code and message from an HttpURLConnection object, you need __________________. a. to use the getInputStream() method. b. to use the getURLConnection() method. c. to use the getResponseCode() and getResponseMessage() methods. d. to use the getCodeResponse() method. 62. The HTTP response code 404 means _______________. a. the response is successful. Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch23 b. the page is found successfully. c. the page was not found. d. the connection is lost. 63. The HTTP response code 200 means _______________. a. the response is successful. b. the page is found successfully. c. the page was not found. d. the connection is lost. 64. A successful response has status code _______________. a. 200 OK. b. 404 OK. c. 0 OK. d. 100 OK. 65. A page not found has status code _______________. a. 200 not found. b. 404 not found. c. 0 not found. d. 100 not found. 66. When you communicate with a web server to obtain data, you have two choices: I) You can make a socket connection and send GET and POST commands. II) You can make a server connection and send GET and POST commands. III) You can use the URLConnection class and have it issue the commands on your behalf. IV) You can use the URL class and have it issue the commands on your behalf. a. I and II b. II and III c. III and I d. IV and II 67. When you communicate with a mail server, you ___________, or you can learn how to use Java mail extensions. a. can write programs that send GET and POP commands. b. can write programs that send SMTP and POST commands. c. can write programs that send GET and POST commands d. can write programs that send SMTP and POP commands. 68. You should use a ______ to connect to a web server. a. Packet b. Socket c. URLConnection d. HttpURLConnection Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch23 69. What does TCP/IP stand for? a. Transmission Control and Internet Protocol. b. Transmission Control Protocol and Internet Protocol. c. Transmission Protocol and Internet Protocol. d. Transmission Control Protocol over Internet Protocol. 70. What does the following if statement do?

if (code == HttpURLConnetion.HTTP_OK) a. It checks if the code is 200. b. It checks if the code is 404. c. It checks if the connection is still connected. d. It checks if there is HTTP. 71. To open a connection, which of the following statements can you use? a. URL u = new URL("http://www.yahoo.com"); URLConnection conn = u.open(); b. URL u = new URL("http://www.yahoo.com"); URLConnection conn = new URLConnection(u); c. URL u = new URL("http://www.yahoo.com"); URLConnection conn = u.openURLConnection(); d. URL u = new URL("http://www.yahoo.com"); URLConnection conn = u.openConnection();

72. To close a connection, which of the following statements can you use? a. URL u = new URL("http://www.yahoo.com"); URLConnection conn = u.close(); b. URL u = new URL(str); URLConnection conn = new URLConnection(u); c. URL u = new URL(str); URLConnection conn = u.closeURLConnection();

d. There is no need to close the connection. 73. What would the getResponseCode return if the response was successful? a. 101 b. 404 c. 200 d. 201 74. Suppose you use the URLGet program in Section 23.5 to get a web page from a server that does not exist, such as http://wombat.java/index.html. What will happen? a. The call to the URL constructor will throw an exception. b. The call to getResponseCode will throw an exception. c. The call to getResponseCode will return the error code 404. d. The call to getInputStream will throw an exception. Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch23 Answer Key 1. c 2. d 3. c 4. a 5. b 6. d 7. b 8. b 9. a 10. d 11. a 12. b 13. a 14. a 15. d 16. c 17. b 18. a 19. d 20. c 21. c 22. d 23. d 24. b 25. a Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch23 26. c 27. a 28. c 29. b 30. a 31. c 32. c 33. d 34. a 35. b 36. b 37. d 38. b 39. b 40. c 41. c 42. c 43. d 44. d 45. b 46. b 47. d 48. b 49. a 50. c 51. c Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch23 52. d 53. c 54. a 55. c 56. d 57. b 58. d 59. d 60. b 61. c 62. c 63. a 64. a 65. b 66. c 67. d 68. c 69. d 70. a 71. d 72. d 73. c 74. b

Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch24

Indicate the answer choice that best completes the statement or answers the question. 1. Insert the statement that would remove the following table from the database.

CREATE TABLE Course ( Course_ID VARCHAR(11), Credits VARCHAR(4), Room_No INT(4) ) ____________________ a. DELETE TABLE Course b. TRUNCATE TABLE Course c. DROP Course d. DROP TABLE Course 2. A _____________ is a column (or set of columns) whose value uniquely specifies a table record. a. foreign key b. primary key c. column headers d. data type 3. A ____________ is a reference to a primary key in a linked table. a. foreign key b. primary key c. column headers d. data type 4. Complete the following statement, which inserts rows into the following Course table.

____________________ VALUES ('CS221', 'Data Structures', '4', 'J. Jones') Course table Course_ID CourseName CS605

Credits Professor

Introduction to Java Programming 3

A.Smith

a. INSERT INTO Course table b. INSERT FROM Course c. INSERT INTO Course d. INSERT INTO Table Course 5. In the table below, the ____ correspond(s) to the attributes of a customer in the database. Customer table Customer_Number FirstName LastName Address City State Zip Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch24 3175

Gregory

Adams

100 Main Street

Anytown

CA

98765

3176

Lincoln

Hall

1175 Liberty Ave Pleasantville MI

45066

a. foreign key b. primary key c. column headers d. data type 6. In database terminology, a column (or combination of columns) that uniquely identifies a row in a table is called a(n) ____. a. data type b. attribute c. primary key d. column header 7. Which of the following table attributes could be a unique identifier for a person? a. Name b. SocialSecurityNumber c. State d. Birthday 8. Which of the following statements is correct? a. SQL uses double quotes (") to delimit strings. b. The SQL command INSERT AT adds data to a database c. SQL is not case sensitive. d. SQL is a part of the Java API. 9. Based on the customer table below, which of the attributes do you think represents the primary key? Customer table Customer_Number Name Address City State Zip 3175

Sam's Small Appliances 100 Main Street Anytown

CA

98765

3176

Electronics Unlimited

175 Liberty Ave Pleasantville MI

45066

a. Address b. Name c. Customer_Number d. Zip 10. Which of the following would be a good primary key for a Course table designed to hold course information for a university? a. CourseName b. CourseID c. CourseCredit d. CoursePrerequisites

Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch24 11. How does a relational database store information? a. Arrays b. Linked Lists c. Tables d. Charts 12. SQL uses single quotes (‘) to delimit strings. What is the standard in order to include a single quote in a String? For example: ‘Joe’s Burgers’ a. Use double quotes (“) b. Use a normal single quote c. Use the single quote twice d. Escape with a (\’) as in Java 13. What is the purpose of a primary key? a. To establish a link from one table to another b. To be the first identifier, which does not need to be unique c. To use a row that uniquely identifies a column d. To link a column to another column 14. In SQL, the _____________ command is used to issue queries that do not modify the database. a. APPEND b. UPDATE c. MODIFY d. SELECT 15. The outcome of a SQL query is a ____________________. a. table b. a 2D array of objects c. list d. subquery 16. A ____________ is a set of rows and columns that provides a "window" through which you can see some of the database data. a. table b. view c. window d. subquery 17. Based on the following table, the query that gets the names and complete mailing addresses of all customers is ____________________. Customer table Customer_Number Name Address City State Zip 3175

Sam's Small Appliances 100 Main Street Anytown

3176

Electronics Unlimited

Powered by Cognero

CA

98765

175 Liberty Ave Pleasantville MI

45066 Page 3


Name:

Class:

Date:

testbank-bj-7-ch24 a. SELECT * FROM Customer b. SELECT Name, Address, City, State, Zip INTO Customer c. SELECT FROM Customer FIELDS Name, Address, City, State, Zip d. SELECT Name, Address, City, State, Zip FROM Customer 18. Based on the table below, the query that finds all customers who do not live in Pleasantville is _________________. Customer table Customer_Number Name Address City State Zip 3175

Sam's Small Appliances 100 Main Street Anytown

CA

98765

3176

Electronics Unlimited

175 Liberty Ave Pleasantville MI

45066

a. SELECT * FROM Customer WHERE City NOT 'Pleasantville' b. SELECT * FROM Customer WHERE NOT (City = 'Pleasantville') c. SELECT * FROM Customer WHERE City <> 'Pleasantville' d. SELECT * FROM Customer WHERE City != 'Pleasantville' 19. Based on the table below, the query that finds the names and zip codes of all customers is _____________________. Customer table Customer_Number Name Address City State Zip 3175

Sam's Small Appliances 100 Main Street Anytown

CA

98765

3176

Electronics Unlimited

175 Liberty Ave Pleasantville MI

45066

a. SELECT ALL Name, Zip FROM Customer b. SELECT Name, Zip c. SELECT * FROM Customer d. SELECT Name, Zip FROM Customer 20. Based on the table below, insert the statement that queries the database for the names of customers who live in the city of Pleasantville: ______________________ Customer table Customer_Number Name Address City State Zip 3175

Sam's Small Appliances 100 Main Street Anytown

CA

98765

3176

Electronics Unlimited

175 Liberty Ave Pleasantville MI

45066

a. SELECT Name FROM Customer WHERE City 'Pleasantville' b. SELECT Name FROM Customer WHERE City == 'Pleasantville' c. SELECT Name FROM Customer WHERE City >< 'Pleasantville' d. SELECT Name FROM Customer WHERE City = 'Pleasantville' 21. In SQL, ____ is used to test for equality. a. EQUAL b. == c. = d. EQUALS 22. Based on the table below, which of the following statements will return the number of customers in Michigan (MI)? Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch24 Customer table Customer_Number Name

Address

City

3175

Sam's Small Appliances 100 Main Street Anytown

3176 3177

State Zip CA

98765

Electronics Unlimited

175 Liberty Ave Pleasantville MI

45066

AB Limited

1034 Laurelton Clarkstown MI

45073

a. SELECT COUNT(*) FROM Customer WHERE State = 'MI' b. SELECT AVG(*) FROM Customer WHERE State = 'MI' c. SELECT MAX(*) FROM Customer WHERE State = 'MI' d. SELECT SUM(*) FROM Customer WHERE State = 'MI' 23. The outcome of a SELECT query is a _________ that you can view and analyze. a. table b. list c. result set d. subquery 24. Which SQL command(s) modify the data in a database? I SELECT II INSERT III DELETE IV UPDATE a. I, II, III b. Only II, III c. II, III, IV d. Only III, IV 25. Based on the table below, the SQL statement that changes the address and city of customer 3175, Gregory Adams, to 1337 Parkway Ave and Pembrook, SD, 57462, respectively, is _____________________. Customer table Customer_Number FirstName LastName Address City State Zip 3175

Gregory

Adams

100 Main Street

Anytown

CA

98765

3176

Lincoln

Hall

1175 Liberty Ave Pleasantville MI

45066

a. UPDATE Customer Address = '1337 Parkway Ave', City = 'Pembrook', State = 'SD',

Zip = '57462' WHERE FirstName = 'Gregory' AND LastName = 'Adams' AND Customer_Number = '3175' b. UPDATE Customer SET Address = '1337 Parkway Ave', City = 'Pembrook', State = 'SD', Zip = '57462' WHERE FirstName = 'Gregory' AND LastName = 'Adams' AND Customer_Number = '3175' c. UPDATE Customer SET Address = '1337 Parkway Ave', City = 'Pembrook', State = 'SD', Zip = '57462' WHERE Name = 'Gregory Adams' AND Customer_Number = '3175' d. UPDATE Customer SET Address = '1337 Parkway Ave', City = 'Pembrook', State = 'SD', Zip = '57462'

26. The ______ clause is used to select data that fulfill a condition. Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch24 a. SELECT b. FROM c. WHEN d. WHERE 27. Used with the LIKE operator, the ______ symbol matches exactly one character. a. _ b. % c. ? d. $ 28. What will the following expression match to?

Name LIKE 'e_%' a. all strings in the Name column that have at least 3 characters. b. all strings in the Name column whose first letter is an "e". c. all strings in the Name column that start with the letter "e" and end with underscore. d. all strings in the Name column whose second letter is any character. 29. What will the following expression match to?

Name LIKE '%e%' a. all strings in the Name column that end with "e". b. all strings in the Name column whose second to last letter is an "e". c. all strings in the Name column that contain the letter "e". d. all strings in the Name column whose second letter is an "e". 30. What is the purpose of the LIKE clause? a. Selects data that fulfills a numerical condition b. Finds the location of the initial starting point c. Matches all strings which contains certain characters d. Tests for equality in ASCII value 31. Which clause allows the joining of multiple tables in SQL? a. WHERE with multiple items b. JOIN with multiple items c. FROM with multiple items d. WITH with multiple items 32. An example of a lightweight database is: a. Oracle b. MS Access c. Apache Derby Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch24 d. MySQL 33. The acronym JDBC stands for ________: a. Joint Data Base Center b. Java Database Control c. Joint Database Connectivity d. Java Database Connectivity 34. All database URLs have the format: a. jdbc:subprotocol:driver-specific data b. jdbc/subprotocol/driver/data c. oracle.jdbc.driver.OracleDriver d. c:\jdk1.7.0\db\lib\driver.jar 35. What should the database.properties file contain so you can connect to a database? a. a database URL, user name, password b. a database URL, the program name, and a JDBC driver c. a database URL, the program name, and database name d. the JDBC driver path 36. What should be on the class path when you launch a Java program that accesses a database? a. the JDBC driver b. the derby.jar file c. the user name and password d. the JDK 37. What statement will return the value of a given key from the configuration file? Assume props is of type Properties. a. String driver = props.getProperty("database.properties"); b. Connection conn = SimpleDataSource.getProperty("database.properties"); c. String driver = props.getProperty("jdbc.driver"); d. Properties props = SampleDataSource.init("jdbc.driver"); 38. One of the steps for testing the JDBC driver is: a. to setup your user account. b. to find the name of the database URL that your driver expects. c. to install the JDBC driver program. d. to change the directory to the JDBC driver directory. 39. Oracle is an example of a: a. Heavyweight Java database. b. Lightweight Java database. c. Desktop database. d. Production-quality database. Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch24 40. Microsoft Access is an example of a: a. Heavyweight Java database. b. Lightweight Java database. c. Desktop database. d. Production-quality database. 41. Apache Derby is an example of a: a. Heavyweight Java database. b. Lightweight Java database. c. Desktop database. d. Production-quality database. 42. An example of a production-quality database is: a. Oracle b. MS Access c. Apache Derby d. Powerbuilder 43. An example of a desktop database is: a. Oracle b. MS Access c. Apache Derby d. MySQL 44. In jdbc.URL, the acronym URL stands for: a. Universal Resource Locator b. Uniform Resource Locator c. Universe Resultset Locator d. Uniform Resultset Locator 45. In a Java program, the result of a SQL query is returned in a _____________ object. a. ResultSet b. connection c. view d. driver 46. A ______________ object can create statement objects that are used to execute SQL commands. a. ResultSet b. Connection c. JDBC d. Driver 47. If your statement has variable parts, you should use a _________ object. a. ResultSet Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch24 b. ResultSetMetaData c. PreparedStatement d. Statement 48. Why should we use try-with-resources to open a Connection to a database? a. To commit the changes b. To display the ResultSet c. To display the metadata d. To close the connection 49. Which Java statement connects to a database using a Connection object? a. Connection conn = new Connection(url, username, password); b. Conenction conn = DriverManager.getConnection(); c. Connection conn = DriverManager.connect(url, username, password); d. Connection conn = DriverManager.getConnection(url, username, password); 50. The ___ symbol in the query string denotes variables that you fill in when you make an actual query a. ? b. * c. ! d. :: 51. When you first get a result set from the executeQuery method, you need to call ____ to move to the first row a. first() b. start() c. move() d. next() 52. What is the effect of the following statement?

String productCode = result.getString(1); a. it will return the data in the second column. b. it will return the data in the first column. c. it will store the integer 1 as a string in productCode. d. it will return the name of the column. 53. If you want to find out about properties of a result set from an unknown table, you need to use: a. the ResultSet class. b. the Statement class. c. the ResultSetData class. d. the ResultSetMetaData class. 54. What will the following command do? Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch24

java -classpath derby.sql;. ExecSQL database.properties Product.sql a. It will execute the statements in the database.properties file. b. It will execute the statements in the derby.sql file. c. It will execute the statements in the Product.sql file. d. It will act as an interactive testing tool only. 55. What will the following command do?

java -classpath derby.sql;. ExecSQL database.properties a. It will execute the statements in the database.properties file. b. It will execute the statements in the derby.sql file. c. It will compile the statements in the derby.sql file. d. It will use ExecSQL program as an interactive testing tool. 56. You can use the generic ____ method to execute arbitrary SQL statements. a. setString() b. prepareStatement() c. executeQuery() d. execute() 57. What does the execute method return? a. ResultSet b. Query c. RecordSet d. boolean 58. What is wrong with the following statement?

boolean result = statement.execute("SELECT * FROM emp WHERE empNum = '?'"); a. boolean should be ResultSet b. execute should be executeQuery c. execute should be prepareStatement d. ? should be an integer 59. What is wrong with the following statement?

ResultSet result = statement.execute("SELECT * FROM emp WHERE empNum = '5'"); a. ResultSet should be String Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch24 b. execute should be executeQuery c. execute should be prepareStatement d. 5 should not be used as an empNum value 60. If your program needs to look at several result sets at the same time, _____. a. you need to create multiple Statement objects. b. you can reuse the Statement or PreparedStatement objects c. you should close the ResultSet before creating a new one. d. you are not able to see several sets at the same time. 61. When you are done with a Statement object, _______. a. you should close it and you must close the associated result set as well. b. you should not close it and should not close the associated result set. c. you should close it and that automatically closes the associated result set. d. you should only close the associated result set. 62. When you close a connection: a. it closes the connection only. b. it closes the connection and the associated result set. c. it closes the connection and the associated statement. d. it closes the connection and closes all statements and result sets. 63. The ______ class has a next method to visit the next row of a query result. a. Scanner b. Statement c. ResultSet d. Connection 64. To fetch a column in a result set that stores prices, use the ______ method. a. nextInt() b. getInt() c. nextDouble() d. getDouble() 65. Metadata are ______ a. data about an object. b. the properties of a result set. c. the objects that are used to execute the SQL commands. d. data about a connection. 66. To get the number of columns in a result set, you use _________ method of the ResultSetMetaData class. a. getColumnInt() b. getColumnsCount() c. getCount() Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch24 d. getColumnCount() 67. "SQL injection attacks" have been responsible for many cases of data theft. One of the solutions for preventing these attacks is: a. Never use double quotes in the query. b. Never use single quotes in the query. c. Never add a string to a query that you didn't type yourself. d. Never add a number to a query that you didn't type yourself. 68. What does the following statement do?

String prodCode = nextLine(in, "Product Code (D=Done, L=List)"); a. It will store the string "Product Code (D=Done, L=List)" in the variable in. b. It will display "in, Product Code (D=Done, L=List)" on the screen. c. It will display the contents of the variable in on the screen. d. It will read the user's input and store it in the object prodCode. 69. Which import statement will allow you to use a SQLException object? a. import javax.swing.SQLException; b. import java.sql.SQLException; c. import java.util.SQLException; d. import java.io.SQLException; 70. Database tables store rows that contain the following except a. strings b. fundamental data types c. arbitrary objects d. numbers 71. What is the main purpose of the Connection object? a. Accesses a database from a Java program b. Combines multiple data tables c. Skips the loading step of the database driver class d. Manually loads the database driver class 72. In what format does the SQL query return a result? a. XPath syntax b. ResultSet object c. A String separated by colons d. An array of results 73. If you encounter an error during updating a transaction, then call the ______ method: a. undo Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch24 b. takeback c. rollaround d. rollback 74. An important part of database processing is transaction handling. What is a transaction? a. A set of data that is translated into the required language and then added to the database b. A set of database transfers to another database c. A set of database updates that may have some parts successful d. A set of database updates that should either succeed fully or not happen at all 75. When you execute a rollback: a. the temporary data are made permanent. b. the temporary tables are simply discarded. c. the database stores the changes in a temporary table. d. it will commit all the updates.

Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch24 Answer Key 1. d 2. b 3. a 4. c 5. c 6. c 7. b 8. c 9. c 10. b 11. c 12. c 13. a 14. d 15. c 16. b 17. d 18. c 19. d 20. d 21. c 22. a 23. c 24. c 25. b Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch24 26. d 27. a 28. b 29. c 30. c 31. c 32. c 33. d 34. a 35. a 36. a 37. c 38. b 39. d 40. c 41. b 42. a 43. b 44. b 45. a 46. b 47. c 48. d 49. d 50. a 51. d Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch24 52. b 53. d 54. c 55. d 56. d 57. d 58. d 59. b 60. a 61. c 62. d 63. c 64. d 65. a 66. d 67. c 68. d 69. b 70. c 71. a 72. b 73. d 74. d 75. b

Powered by Cognero

Page 16


Name:

Class:

Date:

testbank-bj-7-ch25

Indicate the answer choice that best completes the statement or answers the question. 1. ____________ is an extensible syntax that can be used to specify many different kinds of data. a. DOM b. ELEMENT c. XHTML d. XML 2. In XML, an attribute has a name and a(n) ____________________. a. variable b. element c. value d. object 3. Which of the following statements is correct? a. XML is an extensible syntax that can be used to specify many different kinds of data. b. XML has one specific purpose: to describe web documents. c. XML tells you how to display data. d. You can always replace XML elements with attributes. 4. Which of the following statements is correct? a. XML-formatted data files are resilient to change. b. In XML, start-tags need not have matching end-tags. c. XML describes how to display data. d. HTML is a special case of XML. 5. Which of the following statements is correct? a. In XML, every start-tag must have a matching end-tag. b. XML files are readable by computer programs but not by humans. c. Attribute values need not be enclosed in quotes. d. An element cannot contain mixed content. 6. Which of the following statements is correct? a. Elements cannot have attributes. b. An XML document starts out with an HTML declaration and contains elements and text. c. An element must contain text or elements, not both. d. An attribute is appropriate only if it tells something about the data but is not part of the data itself. 7. Which of the following statements is correct? a. Elements describe how to interpret attributes. b. In XML, attribute values must be enclosed in quotes. c. Mixed content allows you to have control over the order in which elements appear. d. You should always use mixed content for elements that describe data sets. 8. Which of the following XML fragments contains an error? Powered by Cognero

Page 1


Name:

Class:

Date:

testbank-bj-7-ch25 a. <name lang="en">half dollar</name> b. <img src="hamster.jpeg"/> c. <img src="hamster.jpeg" width=400 height=300/> d. <name lang="germ">quarter</name> 9. The XML standard recommends that every XML document start with ____. a. <xml version="1.0"?> b. <?xml version="1.0"?> c. <xml version="1.0"> d. <?xml version="1.0"> 10. Which of the following is a correctly-formatted XML fragment for a course element and two child elements, courseID and credits. The course ID is CS605 and it has 3 credit hours. a. <course> <courseID>CS605</courseID><credits>3</credits></course> b. <course> <courseID> CS605 <credits> 3 </credits> </courseID> </course> c. <courseID> <course> CS605 </course> <credits> 3 </credits> </courseID> d. <course> <courseID> CS605 </courseID> </course> <course> <credits> 3 </credits> </course> 11. Which of the following is true about HTML and XML? a. HTML describes the meaning of the data and XML also describes the meaning of the data b. HTML describes the website to the browser while XML describes the meaning of the data c. HTML describes the website to the browser while XML describes how to display the data d. HTML describes the meaning of the data while XML describes how to display the data 12. Which of the following is not true when using XML? a. Attribute values must be enclosed in quotes b. Tags are case-sensitive c. Indents matter to the parser d. Every start-tag must have a matching end-tag 13. Which of the following best describes the line of code? <p>Have a <strong>fantastic</strong> day!</p> a. Mixed content b. Element content c. Attribute content d. Combined content 14. An XPath describes a node or_______, using a syntax that is similar to directory paths. a. folder b. set of nodes c. parser d. model 15. A ___________ is a program that reads a document, checks whether it is syntactically correct, and takes some action Powered by Cognero

Page 2


Name:

Class:

Date:

testbank-bj-7-ch25 as it processes the document. a. browser b. compiler c. document builder d. parser 16. A ________ parser reports the building blocks of an XML document. a. tree-based b. XPath c. streaming d. DOM 17. To read and analyze the contents of an XML document, you need an XML ____________. a. parser b. document analyzer c. path d. tokenizer 18. The ____ standard defines interfaces and methods to analyze and modify the tree structure that represents an XML document. a. DTD b. SAX c. DOM d. API 19. A _____________ reads and reports on each element of an XML document as it reads it. a. DOM parser b. tree-based parser c. block parser d. streaming parser 20. Which parser gives you an overview of the complete document so you can analyze it? a. grammar parser b. tree-based parser c. block parser d. streaming parser 21. What does DOM stand for? a. Data Object Model b. Data Oriented Model c. Document Object Model d. Definition Object Model 22. When converting an XML document to Java classes, how should you think about XML elements? a. Elements are equivalent to classes. Powered by Cognero

Page 3


Name:

Class:

Date:

testbank-bj-7-ch25 b. Elements are like instance variables. c. Elements are similar to superclasses. d. Elements can be instance variables, classes, or methods. 23. Where is the newDocumentBuilder method? a. In the DocumentBuilder class. b. In the DocumentFactoryBuilder class. c. In the DocumentFactory class. d. In the DocumentBuilderFactory class. 24. Given the following code, what will the XPath /items/item[0]/quantity select?

<items> <item> <product> <description>Ink Jet Refill Kit</description> <price>29.95</price> </product> <quantity>8</quantity> </item> <item> <product> <description>4-port Mini Hub</description> <price>19.95</price> </product> <quantity>4</quantity> </item> </items> a. 19.95 b. 4 c. 8 d. The element does not exist. 25. Given the following code, what will the XPath name(/items/item[2]/*[2]) generate?

<items> <item> <product> <description>Ink Jet Refill Kit</description> <price>29.95</price> </product> <quantity>8</quantity> </item> <item> <product> Powered by Cognero

Page 4


Name:

Class:

Date:

testbank-bj-7-ch25

<description>4-port Mini Hub</description> <price>19.95</price> </product> <quantity>4</quantity> </item> </items> a. price b. product c. description d. quantity 26. Given the following code, what will the XPath /items/item[2]/product/price generate?

<items> <item> <product> <description>Ink Jet Refill Kit</description> <price>29.95</price> </product> <quantity>8</quantity> </item> <item> <product> <description>4-port Mini Hub</description> <price>19.95</price> </product> <quantity>4</quantity> </item> </items> a. 29.95 b. 19.95 c. 2 d. 4 27. Given the following code, what will the XPath count(/items/*) generate?

<items> <item> <product> <description>Ink Jet Refill Kit</description> <price>29.95</price> </product> <quantity>8</quantity> </item> <item> Powered by Cognero

Page 5


Name:

Class:

Date:

testbank-bj-7-ch25

<product> <description>4-port Mini Hub</description> <price>19.95</price> </product> <quantity>4</quantity> </item> </items> a. 1 b. 2 c. 3 d. 4 28. Assuming that path is properly instantiated object of type XPath and doc is the document below, what is the value of result in the statement

String result = path.evaluate("count(/items/*", doc); <items> <item> <product> <description>Ink Jet Refill Kit</description> <price>29.95</price> </product> <quantity>8</quantity> </item> <item> <product> <description>4-port Mini Hub</description> <price>19.95</price> </product> <quantity>4</quantity> </item> </items> a. 1 b. 2 c. 3 d. 4 29. What kind of object do you need to read an XML document? a. DocumentBuilder b. newBuilder c. newInstance d. newDocumentBuilder 30. Which of the following is true about XML streaming parsers and tree-based parsers? Powered by Cognero

Page 6


Name:

Class:

Date:

testbank-bj-7-ch25 a. Tree-based parsers require little memory while streaming parsers require a large amount of memory b. Tree-based parsers read the XML input one token at a time while the streaming parsers builds an overview that represents the parsed document c. Tree-based parsers give a complete overview of the data while streaming parsers give information bits at a time d. Tree-based parsers report the building blocks of an XML document while a streaming parser gives the overall view of the XML document 31. What is the purpose of the XPath? a. Describes a node or set of nodes in an XML document b. Describes the logic flow of an XML document c. Describes the path to an XML document d. Describes the nodes from the path of the XML document 32. To generate an object of a class that implements the Document interface, you need a __________. a. DocumentGenerator b. DocumentBuilder c. DocumentValidator d. ObjectBuilder 33. To get a DocumentBuilder object, first call the static ____ method of the DocumentBuilderFactory class. a. newInstance b. document c. connection d. newDocument 34. What kind of object do you need to create a new, empty XML document? a. DocumentBuilder b. newBuilder c. newInstance d. newDocumentBuilder 35. The package javax.xml.parsers contains: a. Element and Text b. Document and DocumentBuilder c. DocumentBuilder and DocumentBuilderFactory d. Element and Document 36. What method do you use to insert a node into an XML document? a. insertNode method. b. createNode method. c. createElement method. d. insertElement method. Powered by Cognero

Page 7


Name:

Class:

Date:

testbank-bj-7-ch25 37. Where is the createElement method located? a. DocumentBuilder class. b. newBuilder class. c. DocumentBuilder interface. d. Document interface. 38. You set element attributes with the _________method. a. setElementAttributes b. setElement c. setAttributes d. setAttribute 39. To insert text, you need the _________methods. a. insertElement and setElement b. createNode and insertChild c. createTextNode and appendChild d. insertTextNode and insertChild 40. To write a DOM document, you need to use an object that implements the _________ interface. a. DocumentBuilder b. Serializable c. Serializer d. LSSerializer 41. Using the grammar notation in your textbook, the expression <article> ::= a means: a. “article must be equal to a” b. “article can be replaced with a or not a” c. “article can be replaced with a” d. “article cannot be equal to” 42. Using the grammar notation in your textbook, the expression <article> ::= a | the means: a. “article must be equal to a and the” b. “article can be replaced with a or the” c. “article can be replaced with a and the” d. “article cannot be equal a or the” 43. Using the grammar notation in your textbook, the expression <digit> ::= 0 | 1 | 2 means: a. “digit must be equal to 012” b. “digit can be replaced with 1 or 2” c. “digit must start with 0 then 1 then 2" d. “digit can be replaced with 0 or 1 or 2" 44. Using the grammar notation in your textbook, which rule means that a verb can be either jumps over or eats? a. <verb> ::= "jumps over" | "eats" | </verb> Powered by Cognero

Page 8


Name:

Class:

Date:

testbank-bj-7-ch25 b. <verb> ::= jumps over | eats c. <verb> ::= jumps | over | eats d. <verb> ::= <jumps over> | <eats> | </verb> 45. What package will you use to import DocumentBuilder? a. javax.swing.DocumentBuilder b. javax.xml.DocumentBuilder c. javax.parsers.DocumentBuilder d. javax.xml.parsers.DocumentBuilder 46. What package will you use to import Document? a. javax.swing.Document b. org.w3c.xml.Document c. javax.parsers.Document d. org.w3c.dom.Document 47. Why is generating an XML file as a sequence of print statements not a good idea? a. It takes up more memory to generate an XML document b. It makes it easy to build an illegal XML document c. It skips random lines of code, thus not building the desired XML document d. It is easy to save the XML document in the wrong place 48. Which of the following attribute types describes any sequence of character in a DTD? a. #REQUIRED b. #IMPLIED c. CDATA d. ATTLIST 49. A ____________ is a sequence of rules that describes the valid attributes for each element and the valid child elements for each element type. a. DOM b. Protocol c. DTD d. Data Definition Type 50. Which of the following represents the declaration of a DTD contained within the XML document? a. <!ELEMENT rootElement [ rules ]> b. <!DOCTYPE rootElement [ rules ]> c. <!DTD rootElement [ rules ]> d. <!REQUIRED rootElement [ rules ]> 51. When referencing an external DTD (one not on the current file system), you must supply a(n) ____ for locating the DTD. a. URL Powered by Cognero

Page 9


Name:

Class:

Date:

testbank-bj-7-ch25 b. domain name c. IP address d. element 52. In XML, a DTD is introduced with the ___________ declaration. a. FIXED b. REQUIRED c. IMPLIED d. DOCTYPE 53. The inclusion of a DTD in an XML document allows you tell the parser to validate the document. The ___________ method of the DocumentBuilderFactory class allows you to turn on validation. a. setValidator b. setValidating c. documentBuilder d. setFactory 54. To make the parser ignore white space between elements, you should call the __________ method of the DocumentBuilderFactory class. a. setIgnoringElementContentWhitespace b. setElementContentWhitespace c. setIgnoringContentWhitespace d. setIgnoringElementContent 55. How can a DTD specify that a course child element in a semester element is optional? a. <!ELEMENT semester (class?, course)> b. <!ELEMENT semester (class, course) /> c. <!ELEMENT semester (class, course?)> d. <!ELEMENT semester (class, course*)> 56. The XML encoding for the “>” character is: a. &gr; b. &greaterThan; c. > d. < 57. The XML encoding & is the replacement for the ____ character. a. @ b. ! c. % d. & 58. An element that is declared as _______ in a DTD may not have any children. a. PCDATA Powered by Cognero

Page 10


Name:

Class:

Date:

testbank-bj-7-ch25 b. ELEMENT c. NULL d. EMPTY 59. An EMPTY element is: a. an element that may have zero or more children. b. an element that has no value. c. an element whose value is the null string. d. an element that may not have any children. 60. Given the following DTD expression, which section element is valid?

<!ELEMENT section (title, (paragraph | (image, title?))+)> a. <section>

<title/> <paragraph/> <image/> <title/> <paragraph/> </section> b. <section> <paragraph/> <paragraph/> <title/> </section> c. <section> <paragraph/> <title/> <title/> <paragraph/> </section> d. <section> <paragraph/> <image/> <title/> <paragraph/> </section>

61. The #PCDATA rule means ____________. a. the children can consist of any numeric data. b. the children can consist of 0 or more elements. c. the children can consist of any character data. d. any children allowed. 62. Mixed content is ____________. a. any sequence of numeric data and character data. b. any sequence of character data followed by character data. c. any sequence of character data and specified elements. Powered by Cognero

Page 11


Name:

Class:

Date:

testbank-bj-7-ch25 d. any sequence of numeric data and specified elements. 63. In an attribute definition in a DTD, an #IMPLIED declaration means ____________. a. the attribute is valid. b. the attribute is required. c. the attribute is optional. d. the attribute is implied. 64. In an attribute definition in a DTD, a #FIXED declaration of V means ____________. a. the attribute must be either unspecified or contain V. b. the attribute is unspecified. c. the attribute is optional. d. the attribute is required. 65. In an attribute definition in a DTD, a V declaration means ____________. a. use the value V or a value that contains V. b. use the value V if the attribute is unspecified. c. use the value V if the attribute is optional. d. use the value V if the attribute is required. 66. When referencing an external DTD (one not on the current file system), you must ____________. a. supply a DOCTYPE. b. supply a URL. c. supply both DOCTYPE and URL. d. use the SYSTEM reserved word. 67. When you parse an XML file with a DTD, ____________. a. you should tell the parser to ignore the white space. b. you don’t need to request validation. c. you should supply the URL for locating the DTD. d. your should tell the parser to convert all white space to text. 68. What is one reason to have the DOM parser ignore white space in an XML document? a. White space may make the element names invalid. b. The parser will otherwise make unneeded nodes of the white space. c. The parser will otherwise add white space to the elements. d. White space cannot be streamed. 69. The method setIgnoringElementContentWhitespace is in the _____ class: a. DocumentDataDefinition b. DocumentFactory c. DocumentFactoryBuilder d. DocumentBuilderFactory Powered by Cognero

Page 12


Name:

Class:

Date:

testbank-bj-7-ch25 70. For elements that contain text, the DTD rule is: a. <!ELEMENT name (#FIXED "STATE")> b. <!ELEMENT name (#PCDATA)> c. <!ELEMENT name (#IMPLIED)> d. <!ELEMENT name ("STATE")> 71. Suppose price is an element and currency is an attribute, to represent that a price element must contain currency, we must specify ____ . a. <!ATTLIST price currency CDATA #REQUIRED> b. <!ATTLIST price currency CDATA "USD"> c. <!ATTLIST price currency #REQUIRED "USD"> d. <!ATTLIST price #REQUIRED "USD"> 72. Which definition in an XML schema restricts the contents of quantity to an integer? a. <xsd:element name="quantity" type="integer"/> b. <xsd:element name="quantity" type="xsd:string" /> c. <xsd:element name="quantity" type="integer:xsd" /> d. <xsd:element name="quantity" type="xsd:integer" /> 73. A number of useful advanced XML technologies have been standardized. Among them is: a. HTML b. HXML c. XHTML d. W3C 74. The symbol #PCDATA refers to text, called “parsed character data.” What does it mean? a. It parses the data into characters b. It automatically replaces special characters c. The character data can contain any characters d. Declares any character for the attributes 75. How does an XML document reference a DTD? I The document may contain the DTD II The document may refer to a DTD that is stored elsewhere III The document may be set to the DTD a. Only I b. Only II c. I and II d. I and III

Powered by Cognero

Page 13


Name:

Class:

Date:

testbank-bj-7-ch25 Answer Key 1. d 2. c 3. a 4. a 5. a 6. d 7. b 8. c 9. b 10. a 11. b 12. c 13. a 14. b 15. d 16. c 17. a 18. c 19. d 20. b 21. c 22. b 23. d 24. d 25. d Powered by Cognero

Page 14


Name:

Class:

Date:

testbank-bj-7-ch25 26. b 27. b 28. b 29. a 30. c 31. a 32. b 33. a 34. a 35. c 36. c 37. d 38. d 39. c 40. d 41. c 42. b 43. d 44. b 45. d 46. d 47. b 48. c 49. c 50. b 51. a Powered by Cognero

Page 15


Name:

Class:

Date:

testbank-bj-7-ch25 52. d 53. b 54. a 55. c 56. c 57. d 58. d 59. d 60. a 61. c 62. c 63. c 64. a 65. b 66. b 67. a 68. b 69. d 70. b 71. b 72. d 73. c 74. c 75. c

Powered by Cognero

Page 16


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.