Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e Chapter 1 MULTIPLE CHOICE 1. Which of the following professions use the computer as a tool? a. Accountants b. Engineers c. Mechanics d. Nurses e. All of the above ANS: E 2. The computer can do such a wide variety of tasks because: a. It can be programmed b. It is a machine c. It contains a central processing unit (CPU) d. It has the ability to connect to the Internet ANS: A 3. Computer programming is: a. An art b. A science c. Both of the above d. Neither of the above ANS: C 4. Another term for programs is: a. Hardware b. Software c. Firmware d. Shareware ANS: B 5. refers to the physical components that a computer is made of. a. b. c. d. Device System Hardware Software ANS: C 6. The major components of a typical computer system consist of: a. The CPU b. Input/output devices c. Main memory d. Secondary storage devices e. All of the above © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: E 7. A program is a sequence of instructions stored in: a. The CPU b. The computer’s memory c. Software d. Firmware ANS: B 8. When a computer is running a program, the CPU is engaged in a process formally known as: a. The decrypt/validate/commit cycle b. Low-level machine mode c. The fetch/decode/execute cycle d. Parallax data execution ANS: C 9. A byte is a collection of: a. Four bits b. Six bits c. Eight bits d. A dollar ANS: C 10. Which of the following is a secondary storage device? a. Hard drives b. Floppy disks c. USB drives d. None of the above e. All of the above ANS: E 11. An operating system can be categorized according to: a. The number of users they can accommodate b. The number of tasks they can perform at one time c. Both of the above d. Neither of the above ANS: C 12. This is a special language used to write computer programs. a. Programming language b. Operating system c. Application d. Pseudocode ANS: A Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 13. The original name for Java was a. Java b. HotJava c. Elm d. Oak ANS: D 14. Syntax is: a. Words that have a special meaning in the programming language b. Rules that must be followed when writing a program c. Punctuation d. Symbols or words that perform operations ANS: B 15. Variables are: a. Symbolic names made up by the programmer that represents locations in the computer's RAM b. Reserved words c. Symbolic names made up by the programmer whose values cannot be changed d. Operators that perform operations on one or more operands ANS: A 16. Byte code instructions are: a. Another name for source code b. Syntax errors c. Machine code instructions d. Read and interpreted by the JVM ANS: D 17. Suppose you are at an operating system command line, and you are going to use the following command to compile a program: javac MyClass.java Before entering the command, you must: a. b. c. d. Save the program with the .comp extension Execute the java.sun.com program Make sure you are in the same directory or folder where MyClass.java is located Close all other Windows on your computer system ANS: C 18. In the programming process which of the following is not involved in defining what the program is to do: a. Process b. Compile code c. Input d. Output e. Purpose Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: B 19. One of the design tools used by programmers when creating a model of the program is: a. Disk drive b. Compiler c. ALU d. Pseudocode ANS: D 20. A runtime error is usually the result of: a. A logical error b. A syntax error c. A compilation error d. Bad data ANS: A 21. The purpose of validating the results of the program is: a. To create a model of the program b. To correct syntax errors c. To correct runtime errors d. To determine whether the program solves the original problem ANS: D 22. This is a software entity that contains data and procedures. a. Method b. Object c. Class d. Program ANS: B 23. results in only the object's methods being able to directly access and make the changes to the object's data. a. Component reusability b. Classes c. Data hiding d. Procedures ANS: C 24. Software refers to: a. Secondary storage. b. Firmware c. Programs d. Applets ANS: C Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 25. Each different type of CPU has its own: a. Syntax b. Firmware c. Machine language d. Software ANS: C 26. Internally, the central processing unit (CPU) consists of two parts: a. The control unit and the arithmetic and logic unit (ALU) b. The control unit and main memory c. The arithmetic and login unit (ALU) and main memory d. The input and output devices ANS: A 27. RAM is usually: a. A static type of memory, used for permanent storage b. A volatile type of memory, used only for temporary storage c. Secondary storage d. An input/output device ANS: B 28. Application software refers to: a. The operating system b. Pseudocode c. Key words d. The programs that make the computer useful to the user ANS: D 29. A computer program is: a. A set of instructions that enable the computer to solve a problem or perform a task. b. Main memory c. Pseudocode d. A flow chart ANS: A 30. Java was developed by a. Microsoft. b. IBM c. Sun Microsystems d. Hewlett-Packard ANS: C 31. Key words are: a. The data names in your program b. Words that have a special meaning in the programming language c. Symbols or words that perform operations on one or more operands Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e d. Words or names defined by the programmer ANS: B 32. These are used to indicate the end of a Java statement. a. Semicolons b. Colons c. Periods d. Asterisks ANS: A 33. Because Java byte code is the same on all computers, compiled Java programs a. Must be re-compiled for each different machine it is run on b. Cannot run on Linux systems c. Are non-existent d. Are highly portable ANS: D 34. Which of the following will compile a program called ReadIt? a. java ReadIt.java b. java ReadIt.javac c. javac ReadIt.java d. javac ReadIt.javac ANS: C 35. Which of the following will run the compiled program ReadIt? a. java ReadIt.java b. java ReadIt c. run ReadIt d. go ReadIt ANS: B 36. Which of the following is not part of the programming process? a. Design b. Testing c. Debugging d. All the above are parts of the programming process ANS: D 37. This is a cross between human language and a programming language. a. Pseudocode b. Java c. The Java Virtual Machine d. The compiler ANS: A © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 38. This is a set of programming language statements that, together, perform a specific task. a. Object b. Compiler c. Procedure d. Pseudocode ANS: C 39. The data contained in an object is known as: a. Methods b. Attributes c. Classes d. Atriums ANS: B TRUE/FALSE 1. The computer is a tool used by so many professions that it cannot be easily categorized. ANS: T 2. Without programmers, the users of computers would have no software, and without software, computers would not be able to do anything. ANS: T 3. Application software refers to programs that make the computer useful to the user. ANS: T 4. Colons are used to indicate the end of a Java statement. ANS: F 5. When an object’s internal data is hidden from outside code and access to that data is restricted to the object's methods, the data is protected from accidental corruption. ANS: T 6. Each byte is assigned a unique number known as an address. ANS: T 7. The Java Virtual Machine is a program that reads Java byte code instructions and executes them as they are read. ANS: T 8. The contents of a variable cannot be changed while the program is running. ANS: F 9. Logical errors are mistakes that cause the program to produce erroneous results. ANS: T Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 10. Encapsulation refers to the combining of data and code into a single object. ANS: T 11. Compiled byte code is also called source code. ANS: F 12. Java source files end with the .class extension. ANS: F © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education Chapter 2 MULTIPLE CHOICE 1. Which one of the following would contain the translated Java byte code for a program named Demo? a. Demo.java b. Demo.code c. Demo.class d. Demo.byte ANS: C 2. To compile a program named First, use the following command: a. java First.java b. javac First c. javac First.java d. compile First.javac ANS: C 3. A Java program must have at least one of these: a. Class definition b. Variable c. Comment d. System.out.println(); statement ANS: A 4. In Java, the beginning of a comment is marked with: a. // b. "" c. ; d. # ANS: A 5. The term typically refers to the device that displays console output. a. Standard output device b. Central processing unit c. Secondary storage device d. Liquid crystal display ANS: A 6. In Java, a. Variables b. Literals c. Key words d. Comments must be declared before they can be used. Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: A 7. If the following Java statements are executed, what will be displayed? System.out.println("The top three winners are\n"); System.out.print("Jody, the Giant\n"); System.out.print("Buffy, the Barbarian"); System.out.println("Adelle, the Alligator"); a. The top three winners are Jody, the Giant Buffy, the Barbarian Adelle, the Alligator b. The top three winners are Jody, the Giant\nBuffy, the BarbarianAdelle, the Alligator c. The top three winners are Jody, the Giant\nBuffy, the BarbarianAdelle, and the Albino d. The top three winners are Jody, the Giant Buffy, the BarbarianAdelle, the Alligator ANS: D 8. This is a value that is written into the code of a program. a. literal b. assignment statement c. variable d. operator ANS: A 9. When the + operator is used with strings, it is known as the: a. Assignment operator b. String concatenation operator c. Addition operator d. Combined assignment operator ANS: B 10. What would be printed out as a result of the following code? System.out.println("The quick brown fox" + "jumped over the \n" "slow moving hen."); a. The quick brown fox jumped over the \nslow moving hen. b. The quick brown fox jumped over the slow moving hen. c. The quick brown fox jumped over the slow moving hen. d. Nothing. This is an error. ANS: D 11. Which of the following is not a rule that must be followed when naming identifiers? Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e a. b. c. d. © 2012 Pearson Education The first character must be one of the letters a-z, A-Z, and underscore or a dollar sign. Identifiers can contain spaces. Uppercase and lowercase characters are distinct. After the first character, you may use the letters a-z, A-Z, the underscore, a dollar sign, or digits 09. ANS: B 12. Which of the following cannot be used as identifiers in Java? a. Variable names b. Class names c. Key words d. All of the above e. None of the above ANS: C 13. In Java, it is standard practice to capitalize the first letter of: a. Class names b. Variable names c. Key words d. Literals ANS: A 14. Which of the following is not a primitive data type? a. short b. long c. float d. String ANS: D 15. Which of the following is valid? a. float y; y = 54.9; b. float y; double z; z = 934.21; y = z; c. float w; w = 1.0f; d. float v; v = 1.0; ANS: C 16. The boolean data type may contain values in the following range of values a. true or false © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e b. c. d. -128 to + 127 - 2,147,483,648 to +2,147,483,647 - 32,768 to +32,767 ANS: A 17. Character literals are enclosed in a. single quotes; single quotes b. double quotes; double quotes c. single quotes; double quotes d. double quotes; single quotes ; string literals are enclosed in ANS: C 18. What is the result of the following expression? 10 + 5 * 3 - 20 a. b. c. d. -5 5 25 -50 ANS: B 19. What is the result of the following expression? 25 / 4 + 4 * 10 % 3 a. b. c. d. 19 5.25 3 7 ANS: D 20. What will be displayed as a result of executing the following code? int x = 5, y = 20; x += 32; y /= 4; System.out.println("x = " + x + ", y = " + y); a. b. c. d. x = 32, y = 4 x = 9, y = 52 x = 37, y = 5 x = 160, y = 80 ANS: C 21. What will be the value of z as a result of executing the following code? . Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e int x = 5, y = 28; float z; z = (float) (y / x); a. b. c. d. 5.60 5.6 3.0 5.0 ANS: D 22. What will be the displayed when the following code is executed? final int x = 22, y = 4; y += x; System.out.println("x = " + x + ", y = " + y); a. b. c. d. x = 22, y = 4 x = 22, y = 26 x = 22, y = 88 Nothing, this is an error ANS: D 23. In the following Java statement what value is stored in the variable name? String name = "John Doe"; a. b. c. d. John Doe The memory address where "John Doe" is located name The memory address where name is located ANS: B 24. What will be displayed as a result of executing the following code? int x = 6; String msg = "I am enjoying this class."; String msg1 = msg.toUpperCase(); String msg2 = msg.toLowerCase(); char ltr = msg.charAt(x); int strSize = msg.length(); System.out.println(msg); System.out.println(msg1); System.out.println(msg2); System.out.println("Character at index x = " + ltr); System.out.println("msg has " + strSize + "characters."); a. I am enjoying this class. I AM ENJOYING THIS CLASS. © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e i am enjoying this class. Character at index x = e msg has 24 characters. b. I am enjoying this class. I AM ENJOYING THIS CLASS. i am enjoying this class. Character at index x = e msg has 25 characters. c. I am enjoying this class. I AM ENJOYING THIS CLASS. i am enjoying this class. Character at index x = n msg has 24 characters. d. I am enjoying this class. I AM ENJOYING THIS CLASS. i am enjoying this class. Character at index x = n msg has 25characters. ANS: D 25. What will be displayed as a result of executing the following code? public class test { public static void main(String[] args) { int value1 = 9; System.out.println(value1); int value2 = 45; System.out.println(value2); System.out.println(value3); value = 16; } } a. b. c. d. 9 45 16 94516 9 45 16 Nothing, this is an error ANS: D 26. Which of the following is not a valid comment statement? a. // comment 1 b. /* comment 2 */ c. */ comment 3 /* d. /** comment 4 */ © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: C 27. When saving a Java source file, save it with an extension of a. .javac b. .class c. .src d. .java ANS: D 28. Every Java application program must have a. a class named MAIN b. a method named main c. comments d. integer variables ANS: B 29. To print "Hello, world" on the monitor, use the following Java statement a. SystemOutPrintln("Hello, world"); b. System.out.println{"Hello, world"} c. System.out.println("Hello, world"); d. Print "Hello, world"; ANS: C 30. To display the output on the next line, you can use the println method or use this escape sequence in the print method. a. b. c. d. \n \r \t \b ANS: A 31. This is a named storage location in the computer's memory. a. Literal b. Constant c. Variable d. Operator ANS: C 32. What would be displayed as a result of the following code? int x = 578; System.out.print("There are " + x + 5 + "\n" + "hens in the hen house."); a. There are 583 hens in the hen house. Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e b. c. d. There are 5785 hens in the hen house. There are x5\nhens in the hen house. There are 5785 hens in the hen house. ANS: D 33. Variables are classified according to their a. value b. data type c. names d. location in the program ANS: B 34. The primitive data types only allow a(n) a. variable b. object c. class d. literal to hold a single value. ANS: A 35. If x has been declared an int, which of the following statements is invalid? a. x = 0; b. x = -58932; c. x = 1,000; d. x = 592; ANS: C 36. Given the declaration double r;, which of the following statements is invalid? a. r = 326.75; b. r = 9.4632e15; c. r = 9.4632E15; d. r = 2.9X106; ANS: D 37. Variables of the boolean data type are useful for a. working with small integers b. evaluating true/false conditions c. working with very large integers d. evaluating scientific notation ANS: B 38. What is the result of the following expression? 25 - 7 * 3 + 12 / 3 © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e a. b. c. d. © 2012 Pearson Education 6 8 10 12 ANS: B 39. What is the result of the following expression? 17 % 3 * 2 - 12 + 15 a. b. c. d. 7 8 12 105 ANS: A 40. What will be displayed after the following statements have been executed? int x = 15, y = 20, z x += 12; y /= 6; z -= 14; System.out.println("x ", ", a. b. c. d. = 32; = " + x + y = " + y + z = " +z); x = 27, y = 3.333, z = 18 x = 27, y = 2, z = 18 x = 27, y = 3, z = 18 x = 37, y = 14, z = 4 ANS: C 41. What will be the value of z after the following statements have been executed? int x = 4, y = 33; double z; z = (double) (y / x); a. b. c. d. 8.25 4 8 8.0 ANS: D 42. This is a variable whose content is read only and cannot be changed during the program's execution. a. b. c. operator literal named constant Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e d. reserved word ANS: C 43. What will be displayed after the following statements have been executed? final double x; x = 54.3; System.out.println("x = " + x ); a. b. c. d. x = 54.3 x x = 108.6 Nothing, this is an error. ANS: D 44. Which of the following is a valid Java statement? a. String str = 'John Doe'; b. string str = "John Doe"; c. string str = 'John Doe'; d. String str = "John Doe"; ANS: D 45. What will be displayed as a result of executing the following code? int x = 8; String msg = "I am enjoying java."; String msg1 = msg.toUpperCase(); String msg2 = msg.toLowerCase(); char ltr = msg.charAt(x); int strSize = msg.length(); System.out.println(msg); System.out.println(msg1); System.out.println(msg2); System.out.println("Character at index x = " + ltr); System.out.println("msg has " + strSize + " characters."); a. I am enjoying java. I AM ENJOYING JAVA. i am enjoying java. Character at index x = j msg has 20 characters. b. I am enjoying java. I AM ENJOYING JAVA. i am enjoying java. Character at index x = o msg has 20 characters. c. I am enjoying java. © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education I AM ENJOYING JAVA. i am enjoying java. Character at index x = o msg has 19 characters. d. I am enjoying java. I AM ENJOYING JAVA. i am enjoying java. Character at index x = y msg has 19 characters. ANS: C 46. Which of the following does not describe a valid comment in Java? a. Single line comments, two forward slashes - // b. Multi-line comments, start with /* and end with */ c. Multi-line comments, start with */ and end with /* d. Documentation comments, any comments starting with /** and ending with */ ANS: C 47. Which of the following statements correctly creates a Scanner object for keyboard input? a. Scanner kbd = new Scanner(System.keyboard); b. Scanner keyboard(System.in); c. Scanner keyboard = new Scanner(System.in); d. Keyboard scanner = new Keyboard(System.in); ANS: C 48. Which Scanner class method reads an int? a. b. readInt() nextInt() c. d. getInt() read_int() c. d. getString() nextLine() ANS: B 49. Which Scanner class method reads a String? a. b. readString() nextString() ANS: D 50. Which one of the following methods would you use to convert a string to a double? a. b. Byte.ParseByte Long.ParseLong c. d. Integer.ParseInt Double.ParseDouble Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: D TRUE/FALSE 1. A Java program will not compile unless it contains the correct line numbers. ANS: F 2. All Java statements end with semicolons. ANS: F 3. Java is a case-insensitive language. ANS: F 4. Although the dollar sign is a legal identifier character, you should not use it because it is normally used for special purposes. ANS: T 5. Assuming that pay has been declared a double, the following statement is valid. pay = 2,583.44; ANS: F 6. Named constants are initialized with a value, that value cannot be changed during the execution of the program. ANS: T 7. A variable's scope is the part of the program that has access to the variable. ANS: T 8. In Java the variable named total is the same as the variable named Total. ANS: F 9. Class names and key words are examples of variables. ANS: F 10. Both character literals and string literals can be assigned to a char variable. ANS: F 11. If the compiler encounters a statement that uses a variable before the variable is declared, an error will result. ANS: T 12. Programming style includes techniques for consistently putting spaces and indentation in a program so visual cues are created. ANS: T Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education Chapter 3 MULTIPLE CHOICE 1. The statement is used to make simple decisions in Java. a. do/while b. for c. branch d. if ANS: D 2. A Boolean expression is one that is either: a. true or false b. x or y c. Positive or negative d. None of the above ANS: A 3. This type of operator determines whether a specific relationship exists between two values: a. Logical b. Mathematical c. Unary d. Relational ANS: D 4. Which of the following expressions will determine whether x is less than or equal to y? a. x > y b. x =< y c. x <= y d. x >= y ANS: C 5. Which one of the following is the not equal operator? a. <> b. NOT c. *& d. != ANS: D 6. What will be the value of x after the following code is executed? int x = 75; int y = 60; if (x > y) x = x - y; Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e a. b. c. d. 75 15 60 135 ANS: B 7. What will be the value of ans after the following code has been executed? int ans = 10; int x = 65; int y = 55; if (x >= y) ans = x + y; a. b. c. d. 10 120 100 No value, there is a syntax error ANS: B 8. What will be the value of ans after the following code has been executed? int x = 90, y = 55, ans = 10; if ( x == y); ans *= 2; a. b. c. d. 10 145 20 No value, there is a syntax error ANS: C 9. A block of code is enclosed in a set of a. braces { } b. parentheses ( ) c. double quotes " " d. brackets [ ] ANS: A 10. A flag may have the values a. 0 or 1 b. +1 or -1 c. true or false d. of any character ANS: C © 2012 Pearson Education © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 11. If chr is a character variable, which of the following if statements is written correctly? a. if (chr = "a") b. if (chr == "a") c. if (chr = 'a') d. if (chr == 'a') ANS: D 12. In Java, when a character is stored in memory, it is actually stored as a(n) a. Unicode number b. ASCII character code c. EBCDIC character code d. Morse code . ANS: A 13. This is an international coding system that is extensive enough to represent all the characters of all the world’s alphabets: a. ASCII b. Unicode c. Java d. None of the above ANS: B 14. What will be the values of ans, x, and y after the following statements are executed? int ans = 35, x = 50, y =50; if ( x >= y) { ans = x + 10; x -=y; } else { ans = y + 10; y += x; } a. b. c. d. ans ans ans ans = 60, x = 50, y =100 = 60, x =0, y =50 = 45, x = 50, y = 0 = 45, x = 50, y = 50 ANS: B 15. What will be the value of bonus after the following code is executed? int bonus, sales = 10000; if (sales < 5000) bonus = 200; else if (sales < 7500) bonus = 500; Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e else if (sales < 10000) bonus = 750; else if (sales < 20000) bonus = 1000; else bonus = 1250; a. b. c. d. e. 200 500 750 1000 1250 ANS: D 16. In most editors, you are indenting by one level each time that you press this key: a. Tab b. Shift c. Alt d. Space ANS: A 17. If you prematurely terminate an if statement with a semicolon, the compiler will: a. Not display an error message b. Assume you are placing a null statement there c. All of the above d. None of the above ANS: C 18. What would be the value of bonus after the following statements are executed? int bonus, sales = 1250; if (sales > 1000) bonus = 100; if (sales > 750) bonus = 50; if (sales > 500) bonus = 25; else bonus = 0; a. b. c. d. 100 500 25 0 ANS: C 19. What would be the value of bonus after the following statements are executed? int bonus, sales = 85000; © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education char dept = 'S'; if (sales > 100000) if (dept == 'R') bonus = 2000; else bonus = 1500; else if (sales > 75000) if (dept == 'R') bonus = 1250; else bonus = 1000; else bonus = 0; a. b. c. d. 2000 1500 1250 1000 ANS: D 20. Which of the following is the correct boolean expression to test for: int x being a value between, but not including, 500 and 650, or int y not equal to 1000? a. ((x >= 500 && x <= 650) && (y != 1000)) b. ((x > 500 AND x < 650) OR !(y.equal(1000))) c. ((x > 500 && x < 650) || (y != 1000)) d. ((x < 500 && x > 650) || !(y == 1000)) ANS: C 21. works like this: If the expression on the left side of the && operator is false, the expression the right side will not be checked. a. Short-circuit evaluation b. Reverse logic c. Boolean logic d. Relational evaluation ANS: A 22. If str1 and str2 are both Strings, which of the following will correctly test to determine whether str1 is less than str2? (1) (str1 < str2) (2) (str1.equals(str2) < 0) (3) (str1.compareTo(str2) < 0) a. b. c. d. 1, 2, and 3 will all work 2 3 2 and 3 ANS: C Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 23. To do a case insensitive compare which of the following could be used to test the equality of two strings, str1 and str2? a. (str1.equalsIgnoreCase(str2)) b. (str1.compareToIgnoreCase(str2) == 0) c. Only a d. a and b ANS: D 24. What will be the value of pay after the following statements are executed? int hours = double pay, pay = hours 40 * a. b. c. d. 45; payRate = 10.00; <= 40 ? hours * payRate : payRate + (hours - 40) * payRate * 1.5; 400.00 450.00 465.00 475.00 ANS: D 25. What would be the value of x after the following statements were executed? int x = 10; switch (x) { case 10: x += 15; case 12: x -= 5; break; default: x *= 3; } a. b. c. d. 5 20 25 30 ANS: B 26. What will be printed when the following code is executed? double x = 45678.259; DecimalFormat formatter = new DecimalFormat("#,###,##0.00"); System.out.println(formatter.format(x)); a. b. 45678.259 0,045,678.26 Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e c. d. 45,678.26 45,678.3 ANS: C 27. Which of the following will format .1278 to display as 12.8%? a. 000.0% b. #0.00% c. ###.##% d. ##0.0% ANS: D 28. The expression tested by an if statement must evaluate to a. 0 or 1 b. +1 or -1 c. true or false d. t or f ANS: C 29. These operators use two operands: a. Unary b. Binary c. Tertiary d. None of the above ANS: B 30. What is the value of x after the following code has been executed? int x = 75; int y = 90; if ( x != y) x += y; a. b. c. d. 75 90 15 165 ANS: D 31. What is the value of ans after the following code has been executed? int x = 40; int y = 40; int ans = 0; if (x = y) ans = x + 10; a. 50 © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e b. c. d. © 2012 Pearson Education 80 30 No value, this is a syntax error. ANS: D 32. What is the value of ans after the following code has been executed? int x = 35; int y = 20, ans = 80; if (x < y); ans += y; a. b. c. d. 80 100 35 55 ANS: B 33. Enclosing a group of statements inside a set of braces creates a a. block of statements b. boolean expression c. loop d. Nothing, it is just for readability ANS: A 34. This is a boolean variable that signals when some condition exists in the program a. Sentinel b. Block c. Flag d. Case ANS: C 35. Which of the following correctly tests the char variable chr to determine whether it is not equal to the character B? a. if (chr > 'B') b. if (chr < 'B') c. if (chr != 'B') d. if (chr != "B") ANS: C 36. In an if/else statement, if the boolean expression is false, a. the first statement or block is executed b. the statement or block following the else is executed c. all statements or blocks are executed d. no statements or blocks are executed Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: B 37. What will be the values of ans, x, and y after the following statements are executed? int ans = 0, x = 15, y =25; if ( x >= y) { ans = x + 10; x -=y; } else { ans = y + 10; y += x; } a. b. c. d. ans ans ans ans = 0, x = 15, y = 25 = 25, x = -10, y = 25 = 35, x = 15, y = 40 = 25, x = 15, y = 40 ANS: C 38. What would be the value of discountRate after the following statements are executed? double discountRate = 0.0; int purchase = 100; if (purchase > 1000) discountRate = .05; else if (purchase > 750) discountRate = .03; else if (purchase > 500) discountRate = .01; a. b. c. d. .05 .03 .01 0.0 ANS: D 39. What would be the value of discountRate after the following statements are executed? double discountRate = 0.0; int purchase = 1250; if (purchase > 1000) discountRate = .05; if (purchase > 750) discountRate = .03; if (purchase > 500) discountRate = .01; else discountRate = 0; Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e a. b. c. d. © 2012 Pearson Education .05 .03 .01 0 ANS: C 40. What would be the value of discountRate after the following statements are executed? double discountRate = 0.0; int purchase = 1250; char cust = 'N'; if (purchase > 1000) if (cust == 'Y') discountRate = .05; else discountRate = .04; else if (purchase > 750) if (cust == 'Y') discountRate = .04; else discountRate = .03; else discountRate = 0; a. b. c. d. .05 .04 .03 0 ANS: B 41. Which of the following is the correct boolean expression to test for: int x being a value less than or equal to 500 or greater than 650, and int y not equal to 1000? a. ((x >= 500 && x <650) && (y != 1000)) b. ((x <= 500 OR x > 650) AND !(y.equal(1000))) c. ((x >= 500 || x < 650) || (y != 1000)) d. ((x <= 500 || x > 650) && !(y == 1000)) ANS: D 42. If str1 and str2 are both Strings, which of the following expressions will correctly determine whether they are equal? (1) (str1 == str2) (2) str1.equals(str2) (3) (str1.compareTo(str2) == 0) a. 1, 2, and 3 will all work b. 1 and 2 c. 1 and 3 d. 2 and 3 ANS: D Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 43. What will be printed when the following code is executed? int y = 10; if ( y == 10) { int x = 30; x += y; } System.out.print("x = "); System.out.print(x); a. b. c. d. x = 30 x = 40 x = 20 x is unknown when the last statement is executed ANS: D 44. The a. b. c. d. switch statement is a: Multiple alternative decision structure Nested decision structure Sequence structure Test expression ANS: A 45. What will be the value of charges after the following code is executed? double charges, rate = 7.00; int time = 180; charges = time <= 119 ? rate * 2 : time / 60.0 * rate; a. b. c. d. 7.00 14.00 21.00 28.00 ANS: C 46. What would be the value of discountRate after the following statements are executed? double discountRate; char custType = 'B'; switch (custType) { case 'A': discountRate = .08; break; case 'B': discountRate = .06; case 'C': discountRate = .04; Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e default: discountRate = 0.0; } a. b. c. d. .08 .06 .04 0.0 ANS: D 47. What will be printed when the following code is executed? double x = 45678.259; DecimalFormat formatter = new DecimalFormat("#,##0.0"); System.out.println(formatter.format(x)); a. b. c. d. 45678.259 45,678.259 45,678.26 45,678.3 ANS: D 48. Which of the following will format 12.78 to display as 012.8? a. 000.0 b. #0.00 c. ###.# d. ##0.0% ANS: A 49. What does the following code display? int d = 9, e = 12; System.out.printf("%d %d\n", d, e); a. %d %d b. 9 12 c. %d 9 d. %9 %12 ANS: B 50. What does the following code display? double x = 12.3798146; System.out.printf("%.2f\n", x); a. 123798146 b. 1238 c. %12.38 d. 12.38 ANS: D TRUE/FALSE © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 1. Programs never need more than one path of execution. ANS: F 2. An important style rule you should adopt for writing if statements is to write the conditionally executed statement on the line after the if statement. ANS: T 3. The if/else statement will execute one group of statements if its boolean expression is true or another group if its boolean expression is false. ANS: T 4. Because the && operator performs short-circuit evaluation, your boolean expression will usually execute faster if the subexpression that is most likely false is on the left of the && operator. ANS: T 5. A local variable's scope always ends at the closing brace of the block of code in which it is declared. ANS: T 6. When testing for character values, the switch statement does not test for the case of the character. ANS: F 7. An important style rule you should follow when writing if statements is to line up the conditionally executed statement with the if statement. ANS: F 8. Unicode is an international encoding system that is extensive enough to represent ALL the characters of ALL the world's alphabets. ANS: T 9. Because the || operator performs short-circuit evaluation, your boolean expression will generally be evaluated faster if the subexpression that is most likely to be true is on the left. ANS: T 10. When two Strings are compared using the compareTo method, the cases of the two strings are not considered. ANS: F 11. In a switch statement, each of the case values must be unique. ANS: T 12. In a switch statement, if two different values for the CaseExpression would result in the same code being executed, you must have two copies of the code, one after each CaseExpression. ANS: F Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e Chapter 4 MULTIPLE CHOICE 1. The increment operator is: a. ++ b. -c. *= d. -= ANS: A 2. What will be the values of x and y as a result of the following code? int x = 25, y = 8; x += y++; a. b. c. d. x = 25, y = 8 x = 33, y = 8 x = 33, y = 9 x = 34, y = 9 ANS: C 3. What will be the value of x after the following code is executed? int x, y = 4, z = 6; x = (y++) * (++z); a. b. c. d. 24 28 30 35 ANS: B 4. This is a control structure that causes a statement or group of statements to repeat. a. Block b. Loop c. Prefix mode d. Body ANS: B 5. If a loop does not contain within itself a way to terminate, it is called a(n) a. while loop b. do-while loop c. for loop d. infinite loop ANS: D © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 6. Each repetition of a loop is known as what? a. An iteration b. A cycle c. An execution d. A Lap ANS: A 7. This variable controls the number of times that the loop iterates. a. Counter variable b. Loop control variable c. Running total d. Decrement variable ANS: B 8. This type of loop will always be executed at least once. a. pre-test loop b. post-test loop c. sentinel loop d. for loop ANS: B 9. If you are using a block of statements, don’t forget to enclose all of the statements in a set of: a. Braces b. Double quotes c. Semicolons d. Parentheses ANS: A 10. What will be the value of x after the following code is executed? int x = 10; while (x < 100) { x += 10; } a. b. c. d. 90 100 110 This is an infinite loop ANS: B 11. What will be the value of x after the following code is executed? int x = 10, y = 20; while (y < 100) Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education { x += y; } a. b. c. d. 90 110 210 This is an infinite loop ANS: D 12. a. b. c. d. is the process of inspecting data given to the program by the user and determining if it is valid. Data parsing Input validation User authentication Defensive coding ANS: B 13. This type of loop allows the user to decide the number of iterations. a. Counter-controlled loop b. Dynamically executed loop c. User controlled loop d. Infinite loop ANS: C 14. In the following code, what values could be read into number to terminate the while loop? Scanner keyboard = new Scanner(System.in); System.out.print("Enter a number: "); int number = keyboard.nextInt(); while (number < 100 && number > 500) { System.out.print("Enter another number: number = keyboard.nextInt(); } a. b. c. d. Numbers less than 100 or greater than 500 Numbers in the range 100 - 499 Numbers in the range 100 - 500 The boolean condition can never be true ANS: D 15. What will be the value of x after the following code is executed? int x = 10; do { x *= 20; } while (x > 5); "); Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e a. b. c. d. 10 200 This is an infinite loop. The loop will not be executed, the initial value of x > 5. ANS: C 16. How many times will the following do-while loop be executed? int x = 11; do { x += 20; } while (x > 100); a. b. c. d. 0 1 4 5 ANS: B 17. A loop that repeats a specific number of times is known as a(n) a. sentinel loop b. conditional loop c. counter-controlled loop d. infinite loop ANS: C 18. How many times will the following for loop be executed? for (int count = 10; count <= 21; count++) System.out.println("Java is great!!!"); a. b. c. d. 1 10 11 0 ANS: C 19. What will be the value of x after the following code is executed? int x = 10; for (int y = 5; y < 20; y +=5) x += y; a. b. c. d. 40 25 30 Invalid for statement © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: A 20. This is a value that signals when the end of a list of values has been reached. a. Terminal value b. Final value c. End value d. Sentinel ANS: D 21. Before entering a loop to compute a running total, the program should first do this. a. Read all the values into main memory b. Set the accumulator where the total will be kept to an initial value, usually zero c. Know exactly how many values there are to total d. Set all variables to zero ANS: B 22. This type of loop is ideal in situations where the exact number of iterations is known. a. while loop b. do-while loop c. for loop d. if statement ANS: C 23. Given the following statement, which statement will write "Calvin" to the file DiskFile.txt? PrintWriter diskOut = new PrintWriter("DiskFile.txt"); a. b. c. d. System.out.println(diskOut, "Calvin"); DiskFile.println("Calvin"); PrintWriter.println("Calvin"); diskOut.println("Calvin"); ANS: D 24. When using the PrintWriter class, which of the following import statements would you write near the top of your program? a. import javax.swing.*; b. import java.io.*; c. import PrintWriter; d. import java.file.*; ANS: B 25. Which of the following will open a file named MyFile.txt and allow you to append data to its existing contents? a. FileWriter fwriter = new FileWriter("MyFile.txt", true); PrintWriter outFile = new PrintWriter(fwriter); Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education b. FileWriter fwriter = new FileWriter("MyFile.txt"); PrintWriter outFile = new PrintWriter(fwriter); c. PrintWriter outfile = new PrintWriter("MyFile.txt", true); d. PrintWriter outfile = new PrintWriter(true, "MyFile.txt"); ANS: A 26. Assume that inputFile references a Scanner object that was used to open a file. Which of the following while loops shows the correct way to read data from the file until the end of the file is reached? a. while (inputFile != null) { … } b. while (!inputFile.EOF) { … } c. while (inputFile.hasNext()) { … } d. while (inputFile.nextLine == " ") { … } ANS: C 27. What will be the values of x and y as a result of the following code? int x = 12, y = 5; x += y--; a. b. c. d. x = 12, y = 5 x = 16, y = 4 x = 17, y = 5 x = 17, y = 4 ANS: D 28. What will be the value of x after the following code is executed? int x, y = 15, z = 3; x = (y--) / (++z); a. b. c. d. 3 4 5 6 ANS: A 29. In all but rare cases, loops must contain within themselves a. arithmetic statements b. if statements Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e c. d. © 2012 Pearson Education a way to terminate nested loops ANS: C 30. Which of the following are pre-test loops? a. while, for, do-while b. while, do-while c. while, for d. for, do-while ANS: C 31. What will be the value of x after the following code is executed? int x = 10; while (x < 100); { x += 10; } a. b. c. d. 90 100 110 This is an infinite loop ANS: D 32. What will be the value of x after the following code is executed? int x = 10, y = 20; while (y < 100) { x += y; y += 20; } a. b. c. d. 90 110 130 210 ANS: D 33. In the following code, what values could be read into number to terminate the while loop? Scanner keyboard = new Scanner(System.in); System.out.print("Enter a number: "); int number = keyboard.nextInt(); while (number < 100 || number > 500) { System.out.print("Enter another number: number = keyboard.nextInt(); "); Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education } a. b. c. d. Numbers less than 100 Numbers greater than 500 Numbers in the range 100 - 499 Numbers in the range 100 - 500 ANS: D 34. What will be the value of x after the following code is executed? int x = 10; do { x *= 20; } while (x < 5); a. b. c. d. 10 200 This is an infinite loop. The loop will not be executed, the initial value of x > 5. ANS: B 35. How many times will the following do-while loop be executed? int x = 11; do { x += 20; } while (x <= 100); a. b. c. d. 1 3 4 5 ANS: D 36. A loop that executes as long as a particular condition exists is called a(n) a. sentinel loop b. conditional loop c. count-controlled loop d. infinite loop ANS: B 37. A for loop normally performs which of these steps? a. initializes a control variable to a starting value b. tests the control variable by comparing it to a maximum/minimum value and terminate when the variable reaches that value Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e c. d. e. © 2012 Pearson Education updates the control variable during each iteration all of the above None of the above ANS: D 38. What will be printed after the following code is executed? for (int number = 5; number <= 15; number +=3) System.out.print(number + ", "); a. b. c. d. 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 5, 8, 11, 14, 17, 5, 8, 11, 14, This is an invalid for statement ANS: C 39. This is a sum of numbers that accumulates with each iteration of a loop. a. Running total b. Final total c. Grand finale d. Galloping total ANS: A 40. A sentinel value and signals that there are no more values to be entered. a. is a different data type than the values being processed b. is a special value that cannot be mistaken as a member of the list c. indicates the start of a list d. guards the list ANS: B 41. This type of loop is ideal in situations where you always want the loop to iterate at least once. a. while loop b. do-while loop c. for loop d. if statement ANS: B 42. This is an item that separates other items. a. Controller b. Partition c. Doorway d. Delimiter ANS: D 43. Which of the following will open a file named MyFile.txt and allow you to read data from it? Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education a. File file = new File("MyFile.txt"); b. Scanner inputFile = new Scanner("MyFile.txt"); c. File file = new File("MyFile.txt"); Scanner inputFile = new Scanner(file); d. PrintWriter inputFile = new PrintWriter("MyFile.txt"); ANS: C 44. Assuming that inputFile references a Scanner object that was used to open a file, which of the following statements will read an int from the file? a. int number = inputFile.nextInt(); b. int number = inputFile.next(); c. int number = inputFile.readInt(); d. int number = inputFile.integer(); ANS: A 45. You can use this method to determine whether a file exists. a. The Scanner class's exists method b. The File class's exists method c. The File class's canOpen method d. The PrintWriter class's fileExists method ANS: B TRUE/FALSE 1. Java provides a set of simple unary operators designed just for incrementing and decrementing variables. ANS: T 2. The while loop has two important parts: (1) a boolean expression that is tested for a true or false value, and (2) a statement or block of statements that is repeated as long as the expression is true. ANS: T 3. The do-while loop is a pre-test loop. ANS: F 4. In the for loop, the control variable cannot be initialized to a constant value and tested against a constant value. ANS: F 5. When the break statement is encountered in a loop, all the statements in the body of the loop that appear after it are ignored, and the loop prepares for the next iteration. ANS: F Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 6. You can use the PrintWriter class to open a file for writing and write data to it. ANS: T 7. The do-while loop must be terminated with a semicolon. ANS: T 8. In a for statement, the control variable can only be incremented. ANS: F 9. When the continue statement is encountered in a loop, all the statements in the body of the loop that appear after it are ignored, and the loop prepares for the next iteration. ANS: T 10. A file must always be opened before using it and closed when the program is finished using it. ANS: T 11. When you open a file with the PrintWriter class, the class can potentially throw an IOException. ANS: T 12. When you pass the name of a file to the PrintWriter constructor, and the file already exists, it will be erased and a new empty file with the same name will be created. ANS: T Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education Chapter 5 MULTIPLE CHOICE 1. Methods are commonly used to a. speed up the compilation of a program b. break a problem down into small manageable pieces c. emphasize certain parts of the logic d. document the program ANS: B 2. Which of the following is not a benefit derived from using methods in programming? a. problems are more easily solved b. simplifies programs c. code reuse d. all of the above are benefits ANS: D 3. This type of method performs a task and sends a value back to the code that called it. a. value-returning b. void c. complex d. local ANS: A 4. In the following code, System.out.println(num) is an example of double num = 5.4; System.out.println(num); num = 0.0; a. b. c. d. a value-returning method a void method a complex method a local variable ANS: B 5. To create a method you must write its: a. header b. return type c. body d. definition ANS: D 6. In the header, the method name is always followed by this: a. parentheses . Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e b. c. d. © 2012 Pearson Education return type data type braces ANS: A 7. This part of a method is a collection of statements that are performed when the method is executed. a. method header b. return type c. method body d. method modifier ANS: C 8. Which of the following is not part of a method call? a. method name b. return type c. parentheses d. all of the above are part of a method call ANS: B 9. If method A calls method B, and method B calls method C, and method C calls method D, when method D finishes, what happens? a. control is returned to method A b. control is returned to method B c. control is returned to method C d. the program terminates ANS: C 10. Values that are sent into a method are called a. variables b. arguments c. literals d. types . ANS: B 11. When an argument is passed to a method, a. its value is copied into the method’s parameter variable b. its value may be changed within the called method c. values may not be passed to methods d. the method must not assign another value to the parameter that receives the argument ANS: A 12. What is wrong with the following method call? displayValue (double x); Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e a. b. c. d. There is nothing wrong with the statement. displayValue will not accept a parameter. Do not include the data type in the method call. x should be a String. ANS: C 13. Given the following method header, which of the method calls would be an error? public void displayValues(int x, int y) a. b. c. d. displayValue(a,b); // where a is a short and b is a byte displayValue(a,b); // where a is an int and b is a byte displayValue(a,b); // where a is a short and b is a long they would all give an error ANS: C 14. Which of the following would be a valid method call for the following method? public static void showProduct (int num1, double num2) { int product; product = num1 * (int)num2; System.out.println("The product is " + product); } a. b. c. d. showProduct(5.5, 4.0); showProduct(10.0, 4); showProduct(10, 4.5); showProduct(33.0, 55.0); ANS: C 15. When an object, such as a String, is passed as an argument, it is a. actually a reference to the object that is passed b. passed by value like any other parameter value c. encrypted d. necessary to know exactly how long the string is when writing the program ANS: A 16. All @param tags in a method's documentation comment must a. end with a */ b. appear after the general description of the method c. appear before the method header d. span several lines ANS: B 17. A special variable that holds a value being passed into a method is called what? © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e a. b. c. d. © 2012 Pearson Education Modifier Parameter Alias Argument ANS: B 18. When you pass an argument to a method, be sure that the argument’s data type is compatible with: a. the parameter variable’s data type b. the method’s return type c. the version of Java currently being used d. IEEE standards ANS: A 19. A parameter variable’s scope is: a. the method in which the parameter is declared b. the class to which the method belongs c. the main method d. All of the above ANS: A 20. The lifetime of a method's local variable is a. the duration of the program b. the duration of the class to which the method belongs c. the duration of the method that called the local variable's method d. only while the method is executing ANS: D 21. Local variables a. are hidden from other methods b. may have the same name as local variables in other methods c. lose the values stored in them between calls to the method in which the variable is declared d. All of the above ANS: D 22. Which of the following values can be passed to a method that has an int parameter variable? a. b. c. d. e. float double long All of the above None of the above ANS: E 23. The header of a value-returning method must specify this. Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e a. b. c. d. © 2012 Pearson Education The method's local variable names The name of the variable in the calling program that will receive the returned value The data type of the return value All of the above ANS: C 24. What will be returned from the following method? public static double methodA() { double a = 8.5 + 9.5; return a; } a. b. c. d. 18.0 18 (as an integer) 8 This is an error ANS: A 25. In a @return tag statement the description a. cannot be longer than one line b. describes the return value c. must be longer than one line d. describes the parameter values ANS: B 26. When a method tests an argument and returns a true or false value, it should return a. a zero for true and a one for false b. a boolean value c. a zero for false and a non-zero for true d. a method should not be used for this type test ANS: B 27. The phrase divide and conquer is sometimes used to describe a. the backbone of the scientific method b. the process of dividing functions c. the process of breaking a problem down into smaller pieces d. the process of using division to solve a mathematical problem ANS: C 28. In a general sense, a method is a. a plan b. a statement inside a loop c. a comment d. a collection of statements that performs a specific task © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e ANS: D 29. Breaking a program down into small manageable methods a. makes problems more easily solved b. allows for code reuse c. simplifies programs d. all of the above ANS: D 30. This type of method performs a task and then terminates. a. value-returning b. void c. local d. simple ANS: B 31. In the following code, Integer.parseInt(str), is an example of int num; string str = "555"; num = Integer.parseInt(str) + 5; a. b. c. d. a value-returning method a void method a local variable a complex method ANS: A 32. Which of the following is not a part of the method header? a. return type b. method name c. parentheses d. semicolon ANS: D 33. Which of the following is included in a method call? a. return type b. method modifiers c. parentheses d. return variable ANS: C 34. You should always document a method by writing comments that appear a. just before the method’s definition. b. just after the method’s definition. c. at the end of the file. . Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e d. only if the method is more than five lines long. ANS: A 35. When an argument value is passed to a method, the receiving parameter variable is a. declared within the body of the method b. declared in the method header inside the parentheses c. declared in the calling method d. uses the declaration of the argument ANS: B 36. If you attempt to use a local variable before it has been given a value, a. a compiler error will occur b. the local variable will always contain the value 0 c. the results will be unpredictable d. the local variable will be ignored ANS: A 37. What will be the result of the following code? int num; string str = "555"; num = Integer.parseInt(string str) + 5; a. b. c. d. num will be set to 560 str will have a value of “560” the last line of code will cause an error neither num or str will be changed ANS: C 38. Given the following method header, which of the method calls would be an error? public void displayValues(double x, int y) a. displayValue(a,b); // where a is a long and b is a byte b. displayValue(a,b); // where a is an int and b is a byte c. displayValue(a,b); // where a is a short and b is a long d. they would all give an error ANS: C 39. Which of the following would be a valid method call for the following method? public static void showProduct(double num1, int num2) { double product; product = num1 * num2; System.out.println("The product is " + product); } © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e a. b. c. d. © 2012 Pearson Education showProduct("5", "40"); showProduct(10.0, 4.6); showProduct(10, 4.5); showProduct(3.3, 55); ANS: D 40. When writing the documentation comments for a method, you can provide a description of each parameter by using a a. @comment tag b. @doc tag c. @param tag d. @return tag ANS: C 41. Values stored in local variables a. are lost between calls to the method in which they are declared b. retain their values from the last call to the method in which they are declared c. may be referenced by the calling method d. may be referenced by any other method, if the method in which they are declared is a public method ANS: A 42. Local variables can be initialized with a. constants b. parameter values c. the results of an arithmetic operation d. any of the above ANS: D 43. A value-returning method must specify this as its return type in the method header. a. an int b. a double c. a boolean d. any valid data type ANS: D 44. What will be returned from the following method? public static int methodA() { double a = 8.5 + 9.5; return a; } a. 18.0 Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e b. c. d. © 2012 Pearson Education 18 (as an integer) 8.0 This is an error ANS: D 45. To document the return value of a method, use this in a documentation comment. a. The @param tag b. The @comment tag c. The @return tag d. The @returnValue tag ANS: C 46. The process of breaking a problem down into smaller pieces is sometimes called a. divide and conquer b. scientific method c. top-down programming d. whole-into-part ANS: A 47. Any method that calls a method with a throws clause in its header must a. handle the potential exception b. have the same throws clause c. Both of the above d. do nothing, the called program will take care of the throws clause ANS: C 48. Assume that the following method header is for a method in class A. public void displayValue(int value) Assume that the following code segments appear in another method, also in class A. Which contains a legal call to the displayValue method? a. int x = 7; void displayValue(x); b. int x = 7; displayValue(x); c. int x = 7; displayValue(int x); d. int x = 7; displayValue(x) ANS: B Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education TRUE/FALSE 1. Methods are commonly used to break a problem into small manageable pieces. ANS: T 2. Two general categories of methods are void methods and value returning methods. ANS: T 3. In the method header, the method modifier public means that the method belongs to the class, not a specific object. ANS: F 4. Constants, variables, and the values of expressions may be passed as arguments to a method. ANS: T 5. A parameter variable’s scope is the method in which the parameter is declared. ANS: T 6. You must have a return statement in a value-returning method. ANS: T 7. Any method that calls a method with a throws clause in its header must either handle the potential exception or have the same throws clause. ANS: T 8. In the method header the static method modifier means the method is available to code outside the class. ANS: F 9. Only constants and variables may be passed as arguments to methods. ANS: F 10. No statement outside the method in which a parameter variable is declared can access the parameter by its name. ANS: T 11. The expression in a return statement can be any expression that has a value. ANS: T 12. A value-returning method can return a reference to a non-primitive type. ANS: T Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education Chapter 6 MULTIPLE CHOICE 1. One or more objects may be created from a(n): a. field b. class c. method d. instance ANS: B 2. Class objects normally have _ not. a. fields b. instances c. methods d. relationships that perform useful operations on their data, but primitive variables do ANS: C 3. In the cookie cutter metaphor, think of the a. object; classes b. class; objects c. class; fields d. attribute; methods as a cookie cutter and as the cookies. ANS: B 4. Which of the following are classes from the Java API? a. Scanner b. Random c. PrintWriter d. All of the above ANS: D 5. When you are working with a a. primitive variable b. reference variable c. numeric literal d. binary number ANS: A 6. What is stored by a reference variable? a. A binary encoded decimal b. A memory address c. An object d. A string , you are using a storage location that holds a piece of data. Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: B 7. Most programming languages that are in use today are: a. procedural b. logic c. object-oriented d. functional ANS: C 8. Java allows you to create objects of this class in the same way you would create primitive variables. a. Random b. String c. PrintWriter d. Scanner ANS: B 9. A UML diagram does not contain: a. the class name. b. the method names. c. the field names. d. object names ANS: D 10. Data hiding, which means that critical data stored inside the object is protected from code outside the object, is accomplished in Java by: a. using the public access specifier on the class methods b. using the private access specifier on the class methods c. using the private access specifier on the class definition d. using the private access specifier on the class fields ANS: D 11. For the following code, which statement is not true? public class Sphere { private double radius; public double x; private double y; private double z; } a. b. c. d. x is available to code that is written outside the Circle class. radius is not available to code written outside the Circle class. radius, x, y, and z are called members of the Circle class. z is available to code that is written outside the Circle class. Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: D 12. You should not define a class field that is dependent upon the values of other class fields: a. in order to avoid having stale data b. because it is redundant c. because it should be defined in another class d. in order to keep it current ANS: A 13. What does the following UML diagram entry mean? + setHeight(h : double) : void a. b. c. d. this is a public attribute named Height and is a double data type this is a private method with no parameters and returns a double data type this is a private attribute named Height and is a double data type this is a public method with a parameter of data type double and does not return a value ANS: D 14. Methods that operate on an object's fields are called: a. instance variables b. instance methods c. public methods d. private methods ANS: B 15. The a. b. c. d. scope of a private instance field is: the instance methods of the same class inside the class, but not inside any method inside the parentheses of a method header the method in which they are defined ANS: A 16. A constructor: a. always accepts two arguments b. has return type of void c. has the same name as the class d. always has an access specifier of private ANS: C 17. Which of the following statements will create a reference, str, to the String, “Hello, World”? a. String str = "Hello, World"; b. string str = "Hello, World"; c. String str = new "Hello, World"; d. str = "Hello, World"; Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: A 18. Two or more methods in a class may have the same name as long as: a. they have different return types b. they have different parameter lists c. they have different return types, but the same parameter list d. you cannot have two methods with the same name ANS: B 19. Given the following code, what will be the value of finalAmount when it is displayed? public class Order { private int orderNum; private double orderAmount; private double orderDiscount; public Order(int orderNumber, double orderAmt, double orderDisc) { orderNum = orderNumber; orderAmount = orderAmt; orderDiscount = orderDisc; } public int getOrderAmount() { return orderAmount; } public int getOrderDisc() { return orderDisc; } } public class CustomerOrder { public static void main(String[] args) { int ordNum = 1234; double ordAmount = 580.00; double discountPer = .1; Order order; double finalAmount = order.getOrderAmount() – order.getOrderAmount() * order.getOrderDisc(); System.out.println("Final order amount = $" + finalAmount); } } a. 528.00 b. 580.00 c. There is no value because the constructor has an error. d. There is no value because the object order has not been created. Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: D 20. A class specifies the and a. relationships; methods b. fields; object names c. fields; methods d. relationships; object names that a particular type of object has. ANS: C 21. This refers to the combining of data and code into a single object. a. Data hiding b. Abstraction c. Object d. Encapsulation ANS: D 22. Another term for an object of a class is a. access specifier b. instance c. member d. method ANS: B 23. In your textbook the general layout of a UML diagram is a box that is divided into three sections. The top section has the ; the middle section holds ; the bottom section holds . a. class name; attributes or fields; methods b. class name; object name; methods c. object name; attributes or fields; methods d. object name; methods; attributes or fields ANS: A 24. For the following code, which statement is not true? public class Circle { private double radius; public double x; private double y; } a. b. c. d. x is available to code that is written outside the Circle class. radius is not available to code written outside the Circle class. radius, x, and y are called members of the Circle class. y is available to code that is written outside the Circle class. ANS: D 25. It is common practice in object-oriented programming to make all of a class's Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e a. b. c. d. © 2012 Pearson Education methods private fields private fields public fields and methods public ANS: B 26. After the header, the body of the method appears inside a set of: a. brackets, [] b. parentheses, () c. braces, {} d. double quotes, "" ANS: C 27. In UML diagrams, this symbol indicates that a member is private: a. * b. # c. d. + ANS: C 28. In UML diagrams, this symbol indicates that a member is public. a. b. c. d. / @ + ANS: D 29. In a UML diagram to indicate the data type of a variable enter: a. the variable name followed by the data type b. the variable name followed by a colon and the data type c. the class name followed by the variable name followed by the data type d. the data type followed by the variable name ANS: B 30. When an object is created, the attributes associated with the object are called: a. instance fields b. instance methods c. fixed attributes d. class instances ANS: A 31. When an object is passed as an argument to a method, what is passed into the method’s parameter variable? a. the class name b. the object’s memory address Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e c. d. © 2012 Pearson Education the values for each field the method names ANS: B 32. A constructor is a method that: a. returns an object of the class. b. never receives any arguments. c. with the name ClassName.constructor. d. performs initialization or setup operations. ANS: D 33. The scope of a public instance field is: a. only the class in which it is defined b. inside the class, but not inside any method c. inside the parentheses of a method header d. the instance methods and methods outside the class ANS: D 34. Which of the following statements will create a reference, str, to the string, “Hello, world”? String str = new String("Hello, world"); String str = "Hello, world"; (1) (2) a. b. c. d. 1 2 1 and 2 Neither 1 or 2 ANS: C 35. Overloading means multiple methods in the same class a. have the same name, but different return types b. have different names, but the same parameter list c. have the same name, but different parameter lists d. perform the same function ANS: C 36. Given the following code, what will be the value of finalAmount when it is displayed? public class Order { private int orderNum; private double orderAmount; private double orderDiscount; public Order(int orderNumber, double orderAmt, double orderDisc) { Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education orderNum = orderNumber; orderAmount = orderAmt; orderDiscount = orderDisc; } public double finalOrderTotal() { return orderAmount - orderAmount * orderDiscount; } } public class CustomerOrder { public static void main(String[] args) { Order order; int orderNumber = 1234; double orderAmt = 580.00; double orderDisc = .1; order = new Order(orderNumber, orderAmt, orderDisc); double finalAmount = order.finalOrderTotal(); System.out.println("Final order amount = $" + finalAmount); } } a. 528.00 b. 580.00 c. 522.00 d. There is no value because the object order has not been created. ANS: C 37. A class’s responsibilities include: a. b. the things a class is responsible for doing the things a class is responsible for knowing c. d. both A and B neither A or B ANS: C 38. Instance methods do not have this key word in their headers: a. public b. static c. private d. protected ANS: B 39. Which of the following is not involved in finding the classes when developing an object-oriented application? a. b. Describe the problem domain. Identify all the nouns. c. d. Write the code. Refine the list of nouns to include only those that are relevant to the problem. Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: C 40. This is a group of related classes. a. b. archive package c. d. collection attachment ANS: B 41. Quite often you have to use this statement to make a group of classes available to a program. a. b. import use c. d. link assume c. d. unconditional import conditional import c. d. unconditional import conditional import ANS: A 42. Look at the following statement. import java.util.Scanner; This is an example of a. b. a wildcard import an explicit import ANS: B 43. Look at the following statement. import java.util.*; This is an example of: a. b. a wildcard import an explicit import ANS: A 44. The following package is automatically imported into all Java programs. a. b. java.java java.default ANS: D TRUE/FALSE 1. An object can store data. ANS: T c. d. java.util java.lang Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 2. A class in not an object, but a description of an object. ANS: T 3. An access specifier indicates how the class may be accessed. ANS: T 4. A method that stores a value in a class's field or in some other way changes the value of a field is known as a mutator method. ANS: T 5. Instance methods should be declared static. ANS: F 6. A constructor is a method that is automatically called when an object is created. ANS: T 7. Shadowing is the term used to describe where the field name is hidden by the name of a local or parameter variable. ANS: T 8. The public access specifier for a field indicates that the attribute may not be accessed by statements outside the class. ANS: F 9. A method that gets a value from a class's field but does not change it is known as a mutator method. ANS: F 10. Instance methods do not have the key word static in their headers. ANS: T 11. The term "default constructor" is applied to the first constructor written by the author of a class. ANS: F 12. When a local variable in an instance method has the same name as an instance field, the instance field hides the local variable. ANS: F 13. The term "no-arg constructor" is applied to any constructor that does not accept arguments. ANS: T 14. The java.lang package is automatically imported into all Java programs. ANS: T Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education Chapter 7 MULTIPLE CHOICE 1. This indicates the number of elements, or values, the array can hold. a. the new operator b. the array’s size declarator c. the array’s data type d. the version of Java ANS: B 2. What does the following statement do? double[] array1 = new double[10]; a. b. c. d. Declares array1 to be a reference to an array of double values Creates an instance of an array of 10 double values Will allow valid subscripts in the range of 0 - 9 All of the above ANS: D 3. It is common practice to use a a. static b. reference c. final d. boolean variable as a size declarator. ANS: C 4. What do you call the number that is used as an index to pinpoint a specific element within an array? a. subscript b. global unique identifier c. element d. argument ANS: A 5. Subscript numbering always starts at what value? a. 0 b. 1 c. -1 d. None of the above ANS: A 6. By default, Java initializes array elements with what value? a. 0 b. 100 c. 1 Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e d. © 2012 Pearson Education -1 ANS: A 7. What will be the value of x[8] after the following code has been executed? final int SUB = 12; int[] x = new int[SUB]; int y = 100; for(int i = 0; i < SUB; i++) { x[i] = y; y += 10; } a. 170 b. 180 c. 190 d. 200 ANS: B 8. Java performs , which means that it does not allow a statement to use a subscript that is outside the range of valid subscripts for the array. a. active array sequencing b. array bounds checking c. scope resolution binding d. buffer overrun protection ANS: B 9. In Java, you do not use the new operator when you use a(n): a. array size declarator b. initialization list c. two-dimensional array d. All of the above ANS: B 10. What will be the results of the following code? final int ARRAY_SIZE = 5; float[] x = float[ARRAY_SIZE]; for(int i = 1; i <= ARRAY_SIZE; i++) { x[i] = 10.0; } a. All the values in the array are initialized to 10.0 b. All the values, except the first, are set to 10.0 c. An error will occur when the program runs. d. There will be a compilation error ANS: C Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 11. Each array in Java has a public field named a. size b. capacity c. length d. limit that contains the number of elements in the array. ANS: C 12. What would be the results of the following code? int[] x = { 55, 33, 88, 22, 99, 11, 44, 66, 77 }; int a = 10; if(x[2] > x[5]) a = 5; else a = 8; a. b. c. d. a=5 a=8 a = 10 This is a compilation error, you cannot compare array elements ANS: A 13. What would be the results after the following code was executed? int[] x = {23, 55, 83, 19}; int[] y = {36, 78, 12, 24}; for(int a = 0; a < x.length; a++) { x[a] = y[a]; y[a] = x[a]; } a. b. c. d. © 2012 Pearson Education x[] = {36, 78, 12, 24} and y[] = {23, 55, 83, 19} x[] = {36, 78, 12, 24} and y[] = {36, 78, 12, 24} x[] = {23, 55, 83, 19} and y[] = {23, 55, 83, 19} This is a compilation error ANS: B 14. What will be the value of x[1] after the following code is executed? int[] x = {22, 33, 44}; arrayProcess(x); … public static void arrayProcess(int[] a) { for(int k = 0; k < 3; k++) { a[k] = a[k] + 5; } Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education } a. b. c. d. 27 33 38 49 ANS: C 15. When an array is passed to a method: a. a reference to the array is passed b. it is passed just as an object c. the method has direct access to the original array d. All of the above ANS: D 16. What would be the results of the following code? int[] array1 = new int[25]; … // Code that will put values in array1 int value = array1[0]; for (int a = 1; a < array1.length; a++) { if (array1[a] < value) value = array1[a]; } a. b. c. d. value contains the highest value in array1 value contains the lowest value in array1 value contains the sum of all the values in array1 value contains the average of the values in array1 ANS: B 17. What do you normally use with a partially-filled array? a. A class that does nothing but manage the array b. An accompanying parallel array c. An accompanying integer value that holds the number of items stored in the array d. An accumulator ANS: C 18. To return an array of long values from a method, use this as the return type for the method. a. long b. long[] c. long[ARRAY_SIZE] d. []long ANS: B 19. In memory, an array of String objects Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e a. b. c. d. © 2012 Pearson Education consists of elements, each of which is a reference to a String object. is always implemented as a ragged array. consists of elements, each of which is a String object. must be initialized when the array is declared. ANS: A 20. Given that String[] str has been initialized, to get a copy of str[0] with all characters converted to upper case, use the following statement: a. str.uppercase(); b. str[0].upperCase(); c. str.toUpperCase(); d. str[0].toUpperCase(); ANS: D 21. The sequential search algorithm: a. requires the array to be ordered b. must always be implemented as a method c. uses a loop to sequentially step through an array, starting with the first element d. will not execute, if the element is not in the array ANS: C 22. In order to do a binary search on an array, a. the values of the array must be numeric b. the array must first be sorted in ascending order c. you must first do a sequential search of the array to assure the element you are looking for is there d. There are no requirements ANS: B 23. What is the value of scores[2][3] in the following array? int [] [] scores = { {88, 80, 79, 92}, {75, 84, 93, 80}, {98, 95, 92, 94}, {91, 84, 88, 96} }; a. 94 b. 84 c. 93 d. 95 ANS: A 24. If numbers is a two-dimensional array, which of the following would give the length of row r? a. numbers.length b. numbers.length[r] c. numbers[r].length[r] d. numbers[r].length ANS: D Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 25. Which of the following is a correct method header for receiving a two-dimensional array as an argument? a. public static void passArray(int[1,2]) b. public static void passArray(int [][]) c. public static void passArray(int[1],[2]) d. public static void passArray(int[], int[]) ANS: B 26. A ragged array is: a. a two-dimensional array for which the number of rows is unknown b. a one-dimensional array for which the number of elements is unknown c. a two-dimensional array where the rows are of different lengths d. There is no such thing as a ragged array ANS: C 27. Which of the statements are true about the following code? final int ARRAY_SIZE = 10; long[] array1 = new long[ARRAY_SIZE]; a. b. c. d. Declares array1 to be a reference to an array of long values Creates an instance of an array of 10 long values Will allow valid subscripts in the range of 0 - 9 All of the above ANS: D 28. What will be the value of x[8] after the following code has been executed? final int SUB = 12; int[] x = new int[SUB]; int y = 20; for(int i = 0; i < SUB; i++) { x[i] = y; y += 5; } a. b. c. d. 50 55 60 65 ANS: C 29. What will be the result of executing the following code? int[] x = {0, 1, 2, 3, 4, 5}; a. b. An array of 6 values ranging from 0 through 5 and referenced by the variable x will be created A compilation error will occur Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e c. d. © 2012 Pearson Education The program will crash when it is executed The value of x[1] will be 0, x[2] will be 0, x[3] will be 0, x[4] will be 0, x[5] will be 0, and x[6] will be 0. ANS: A 30. If final int SIZE = 15 and int[] x = new int[SIZE], what would be the range of subscript values that could be used with x[]? a. b. c. d. 1 through 15 1 through 14 0 through 14 0 through 15 ANS: C 31. What would be the results after the following code was executed? int[] x = {23, 55, 83, 19}; int[] y = {36, 78, 12, 24}; x = y; y = x; a. b. c. d. x[] = {36, 78, 12, 24} and y[] = {23, 55, 83, 19} x[] = {36, 78, 12, 24} and y[] = {36, 78, 12, 24} x[] = {23, 55, 83, 19} and y[] = {23, 55, 83, 19} This is a compilation error ANS: B 32. What will be the value of x[1] after the following code is executed? int[] x = {22, 33, 44}; arrayProcess(x[1]); ... public static void arrayProcess(int a) { a = a + 5; } a. b. c. d. 27 33 38 49 ANS: B 33. When an individual element of an array is passed to a method: a. a reference to the array is passed b. it is passed like any other variable c. the method does not have direct access to the original array d. All of the above Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e ANS: C 34. What would be the results of the following code? final int SIZE = 25; int[] array1 = new int[SIZE]; … // Code that will put values in array1 int value = 0; for (int a = 0; a <= array1.length; a++) { value += array1[a]; } a. b. c. d. value contains the highest value in array1 value contains the lowest value in array1 value contains the sum of all the values in array1 This would cause the program to crash ANS: D 35. What would be the results of the following code? final int SIZE = 25; int[] array1 = new int[SIZE]; … // Code that will put values in array1 int value = 0; for (int a = 0; a < array1.length; a++) { value += array1[a]; } a. b. c. d. value contains the highest value in array1 value contains the lowest value in array1 value contains the sum of all the values in array1 This would cause the program to crash ANS: C 36. What will be returned from the following method? public static float[] getValue(int x) a. A float value b. An array of float values c. An integer d. An array of integers ANS: B 37. For the following code, what would be the value of str[2]? String[] str = {"abc", "def", "ghi", "jkl"}; © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e a. b. c. d. © 2012 Pearson Education "ghi" "def" A reference to the String "ghi" A reference to the String "def" ANS: C 38. Which of the following for loops is valid, given the following declaration? String[] names = {"abc", "def", "ghi", "jkl"}; a. for (int i = 0; i < names.length; i++) System.out.println(names[i].length); b. for (int i = 0; i < names.length(); i++) System.out.println(names[i].length); c. for (int i = 0; i < names.length; i++) System.out.println(names[i].length()); d. for (int i = 0; i < names.length(); i++) System.out.println(names[i].length()); ANS: C 39. A search algorithm: a. is a way to locate a specific item in a larger collection of data b. is rarely used with arrays c. arranges elements in ascending order d. arranges elements in descending order ANS: A 40. The binary search algorithm: a. is less efficient than the sequential search algorithm b. will cut the portion of the array being searched in half each time the loop fails to locate the search value c. will have a maximum number of comparisons equal to the number of elements in the array d. will have an average of N/2 comparisons, where N is the number of elements in the array ANS: B 41. Given the following two-dimensional array declaration, which statement is true? int [][] numbers = new int [6] [9]; a. b. c. d. The The The The array array array array numbers numbers numbers numbers has has has has 6 columns and 9 rows 6 rows and 9 columns 15 rows 54 rows Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: B 42. If numbers is a two-dimensional int array that has been initialized and total is an int that has been set to 0, which of the following will sum all the elements in the array? a. for (int row = 1; row < numbers.length; row++) { for (int col = 1; col < numbers.length; col++) total += numbers[row][col]; } b. for (int row = 0; row < numbers.length; row++) { for (int col = 0; col < numbers.length; col++) total += numbers[row][col]; } c. for (int row = 0; row < numbers[row].length; row++) { for (int col = 0; col < numbers.length; col++) total += numbers[row][col]; } d. for (int row = 0; row < numbers.length; row++) { for (int col = 0; col < numbers[row].length; col++) total += numbers[row][col]; } ANS: D 43. Which of the following is a correct method header for receiving a two-dimensional array as an argument? a. public static void passArray(int[2]) b. public static void passArray(int [][]) c. public static void passArray(int[1][2]) d. public static void passArray(int[], int[]) ANS: B 44. Which of the following is a valid declaration for a ragged array? a. int[] ragged = new int[5]; b. int[][] ragged = new int[5][6]; c. int[][] ragged = new int[5][]; d. int[][] ragged = new int[][5]; ANS: C 45. This ArrayList class method is used to insert an item into an ArrayList. a. b. insert add c. d. store putItem Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: B 46. You can use this ArrayList class method to insert an item at a specific location in an ArrayList. a. b. insert add c. d. store putItem ANS: B 47. You can use this ArrayList class method to replace an item at a specific location in an ArrayList. a. b. replace add c. d. store set ANS: D 48. This ArrayList class method deletes an item from an ArrayList. a. b. remove delete c. d. erase purge ANS: A 49. You use this method to determine the number of items stored in an ArrayList object. a. b. numberItems capacity c. d. size items ANS: A 50. The following statement creates an ArrayList object. What is the purpose of the <String> notation? ArrayList<String> arr = new ArrayList<String>(); a. b. It specifies that only String objects may be stored in the ArrayList object. It specifies that the get method will return only String objects. d. It specifies that String objects may not be stored in the ArrayList object. It specifies that everything stored in the ArrayList object will be converted to a String. c. d. java.array java.util c. ANS: A 51. The ArrayList class is in this package. a. b. java.arraylist java.lang ANS: D Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education TRUE/FALSE 1. An array can hold multiple values of several different data types simultaneously. ANS: F 2. Declaring an array reference variable does not create an array. ANS: T 3. To compare the contents of two arrays, you must compare the elements of the two arrays. ANS: T 4. Once an array is created, its size cannot be changed. ANS: T 5. When an array of objects is declared, but not initialized, the array values are set to null. ANS: T 6. A sorting algorithm is a technique for scanning through an array and rearranging its contents in some specific order. ANS: T 7. Any items typed on the command-line, separated by space, after the name of the class are considered to be one or more arguments that are to be passed into the main method. ANS: T 8. Java limits the number of dimensions that an array may have to 15. ANS: F 9. If a[] and b[] are two integer arrays, the expression a == b compares the array contents. ANS: F 10. Objects in an array are accessed with subscripts, just like any other data type in an array. ANS: T 11. A sorting algorithm is used to locate a specific item in a larger collection of data. ANS: F 12. The String[] args parameter in the main method header allows the program to receive arguments from the operating system command-line. ANS: T 13. Java does not limit the number of dimensions that an array may have. Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: T 14. An ArrayList object automatically expands in size to accommodate the items stored in it. ANS: T Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education Chapter 8 MULTIPLE CHOICE 1. A static field is created by placing: a. the key word static after the field name b. the key word static after the access specifier and before the field's data type c. the key word static after the access specifier and field's data type d. it in a static field block ANS: B 2. Static methods can only operate on a. instance b. static c. global d. local fields. ANS: B 3. Which of the following is not true about static methods? a. It is not necessary for an instance of the class to be created to execute the method. b. They are created by placing the key word static after the access specifier in the method header. c. They are called from an instance of the class. d. They are often used to create utility classes that perform operations on data, but have no need to collect and store data. ANS: C 4. The only limitation that static methods have is: a. they can refer to only non-static members of the class b. they can only be called from static members of the class c. they must be declared as public methods d. they cannot refer to non-static members of the class ANS: D 5. Java automatically stores this value in all uninitialized static member variables: a. 0 b. -1 c. null d. false ANS: A 6. If you have defined a class named SavingsAccount with a public static data member named numberOfAccounts, and created a SavingsAccount object referenced by the variable account20, which of the following will assign numberOfAccounts to numAccounts? a. b. numAccounts = account20.numAccounts; numAccounts = numberOfAccounts; Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e c. d. © 2012 Pearson Education numAccounts = SavingsAccount.numberOfAccounts; None of the above, you cannot reference a static data member. ANS: C 7. When a reference variable is passed as an argument to a method: a. a copy of the variable’s value is passed into the method’s parameter b. the method has access to the object that the variable references c. the method becomes a static method d. the program will terminate ANS: B 8. In Java, it is possible to write a method that will return: a. a whole number b. a monetary value c. a string of characters d. a reference to an object e. All of the above ANS: E 9. When a method's return type is a class, what is actually returned to the calling program? a. An object of that class b. A reference to an object of that class c. Only the values in the object that the method accessed d. Nothing, the return type is strictly for documentation in this situation ANS: B 10. An object’s a. value b. assessment c. record d. state is simply the data that is stored in the object’s fields at any given moment. ANS: D 11. If the following is from the method section of a UML diagram, which of the following statements is true? + equals(object2:Stock) : boolean a. b. c. d. This is a private method that receives two objects from the Stock class and returns a boolean value This is a public method that accepts a Stock object as its argument and returns a boolean value This is a private method that returns a boolean value This is a public method that returns a Stock object ANS: B Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 12. You cannot use the == operator to compare the contents of: a. objects b. strings c. integers d. Boolean values ANS: A 13. To compare two objects in a class: a. use the == operator, e.g. object1 == object2 b. write a method to do a byte-by-byte compare of the two objects c. write an equals method that will make a field by field compare of the two objects d. Since objects consist of several fields, you cannot compare them ANS: C 14. If object1 and object2 are objects of the same class, to make object2 a copy of object1: a. assign object1 to object2, such as object2 = object1; b. write a copy method that will make a field by field copy of object1 data members into object2 data members c. use the Java copy method that is a part of the Java language d. use the default constructor to create object2 with object1 data members ANS: B 15. A deep copy of an object: a. is an assignment of that object to another object b. is an operation that copies an aggregate object, and all the objects it references c. is a bogus term, it has no meaning d. is always a private method ANS: B 16. The term for the relationship created by object aggregation is: a. has a b. is a c. Sub-class object d. Inner class ANS: A 17. If the this variable is used to call a constructor: a. a compiler error will result, if it is not the first statement of the constructor. b. a compiler error will result, if it is the first statement of the constructor. c. nothing will happen. d. The this variable cannot be used as a constructor call. ANS: A Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 18. When a field is declared static, there will be: a. a copy of the field in each class object b. only one copy of the field in memory c. a copy of the field for each static method in the class d. only two copies of the field in memory ANS: B 19. Which of the following is not true about static methods? a. It is necessary for an instance of the class to be created to execute the method. b. They are created by placing the key word static after the access specifier in the method header. c. They are called directly from the class. d. They are often used to create utility classes that perform operations on data, but have no need to collect and store data. ANS: A 20. If you have defined a class SavingsAccount with a public static method getNumberOfAccounts(), and created a SavingsAccount object referenced by the variable account20, which of the following will call the getNumberOfAccounts()method? a. b. c. d. getNumberOfAccounts(); SavingsAccount.getNumberOfAccounts(); getNumberOfAccounts(account20); None of the above, you cannot call a static method. ANS: B 21. What will be returned from a method, if the following is the method header? public Rectangle getRectangle() a. b. c. d. An object of the class Rectangle The address of an object of the class Rectangle The values stored in the data members of the Rectangle object the method changed A graph of a rectangle ANS: B 22. If the following is from the method section of a UML diagram, which of the following statements is true? + add(object2:Stock): Stock a. b. c. d. This is a private method named add that accepts and returns objects of the Stock class. This is a private method named Stock that adds two objects. This is a public method named add that accepts and returns references to objects in the Stock class. This is a public method named Stock that adds two objects. ANS: C Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 23. The whole-part relationship created by object aggregation is more often called: a. a has a relationship b. an inner class relationship c. an extra class relationship d. an inside class relationship ANS: A 24. If you attempt to perform an operation with a null reference variable: a. the resulting operation will always be zero b. the results will be unpredictable c. the program will terminate d. Java will create an object to reference the variable ANS: C 25. When the this variable is used to call a constructor: a. it must be the first statement in the constructor making the call b. it must be the last statement in the constructor making the call c. it can be anywhere in the constructor making the call d. You cannot use the this variable in a constructor call. ANS: A 26. A declaration for an enumerated type begins with this key word. a. enumerated c. enum b. enum_type d. ENUM ANS: C 27. Look at the following declaration: enum Tree { OAK, MAPLE, PINE } What is the ordinal value of the MAPLE enum constant? a. b. c. 0 1 2 d. e. 3 Tree.MAPLE ANS: B 28. Look at the following declaration: enum Tree { OAK, MAPLE, PINE } What is the fully-qualified name of the PINE enum constant? a. b. PINE enum.PINE d. e. enum.PINE PINE.Tree © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e c. © 2012 Pearson Education Tree.PINE ANS: C 29. Assuming the following declaration exists: enum Tree { OAK, MAPLE, PINE } What will the following code display? System.out.println(Tree.OAK); a. b. c. Tree.OAK 0 1 d. e. OAK Nothing. This statement will cause an error. c. d. Class, Redundancy, Collections Class, Recyclability, Collaborations ANS: D 30. CRC stands for: a. b. Code, Reuse, Constancy Class, Responsibilities, Collaborations ANS: B 31. You cannot use the fully-qualified name of an enum constant for this. a. b. a switch expression an argument to a method c. d. a case expression all of these ANS: C 32. Enumerated types have this method, which returns the position of an enum constant in the declaration list. a. b. toString position c. d. ordinal location ANS: C 33. The JVM periodically performs this process to remove unreferenced objects from memory. a. b. memory sweeping garbage collection c. d. memory shuffling system restore ANS: B 34. Assume the class BankAccount has been created, and the following statement correctly creates an instance of the class: BankAccount account = new BankAccount(5000.0); Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education What is true about the following statement? System.out.println(account); a. b. The method will display unreadable binary data on the screen. A compiler error will occur. c. d. The account object’s toString method will be implicitly called. A runtime error will occur. ANS: C TRUE/FALSE 1. An instance of a class does not have to exist in order for values to be stored in a class's static fields. ANS: T 2. Both instance fields and instance methods are associated with a specific instance of a class, and they cannot be used until an instance of the class is created. ANS: T 3. A single copy of a class’s static field is shared by all instances of the class. ANS: T 4. When an object is passed as an argument, it is actually a reference to the object that is passed. ANS: T 5. If you write a toString method to display the contents of an object, object1, for a class, Class1, then the following two statements are equivalent: System.out.println(object1); System.out.println(object1.toString()); ANS: T 6. The this key word is the name of a reference variable that is available to all static methods. ANS: F 7. If a class has a method named finalize, it is called automatically just before a data member that has been identified as final of the class is destroyed by the garbage collector. ANS: F 8. A class's static methods do not operate on the fields that belong to any instance of the class. ANS: T 9. When an object reference is passed to a method, the method may change the values in the object. ANS: T Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 10. If you write a toString method for a class, Java will automatically call the method any time you concatenate an object of the class with a string. ANS: T 11. The key word this is the name of a reference variable that an object can use to refer to itself. ANS: T 12. If a class has a method named finalize, it is called automatically just before an instance of the class is destroyed by the garbage collector. ANS: T 13. The names of the enum constants in an enumerated data type must be enclosed in quotation marks. ANS: F 14. An enumerated data type is actually a special type of class. ANS: T 15. You can declare an enumerated data type inside of a method. ANS: F 16. Enum constants have a toString method. ANS: T Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education Chapter 9 MULTIPLE CHOICE 1. What is term used for a class that is “wrapped around” a primitive data type and allows you to create objects instead of variables? a. Intrinsic class b. Enclosed object c. Wrapper class d. Transitional object ANS: C 2. The a. b. c. d. Character wrapper class provides numerous methods for testing String objects testing and converting char variables converting String variables adding two char variables ANS: B 3. The term commonly is used to refer to a string that is part of another string. a. strand b. substring c. character fragment d. nested string ANS: B 4. What will be printed after the following code is executed? String str = "abc456"; int m = 0; while ( m < 6 ) { if (Character.isLetter(str.charAt(m))) System.out.print( Character.toUpperCase(str.charAt(m))); m++; } a. b. c. d. abc456 ABC456 ABC 456 ANS: C 5. Assuming that str is declared as follows, String str = "RSTUVWXYZ"; Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education What value will be returned from str.charAt(5)? a. U b. V c. W d. X ANS: C 6. What will be the value of matches after the following code is executed? boolean matches; String[] productCodes = {"456HI345", "3456hj"}; matches = productCodes[0].regionMatches(true, 1, productCodes[1], 2, 3); a. 56H b. 56h c. true d. false ANS: C 7. What will be the value of loc after the following code is executed? int loc; String str = "The cow jumped over the moon."; loc = str.indexOf("ov"); a. b. c. d. 15 16 17 18 ANS: A 8. In the following statement, what data type must recField be? str.getChars(5, 10, recField, 0); a. b. c. d. String int char char[] ANS: D 9. This character is one that appears at the end, or right side, of a string, after the non-space characters: a. Leading whitespace b. Carriage return c. Trailing whitespace d. Line feed ANS: C Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 10. When you are writing a program with String objects that may have unwanted spaces at the beginning or end of the strings, use this method to delete them. a. replace b. trim c. valueOf d. substring ANS: B 11. If your program needs to make a lot of changes to one or more string, you might consider using objects of this class: a. Character b. String c. StringBuilder d. All of the above ANS: C 12. Look at the following statement: StringBuilder str = new StringBuilder(25); What will the StringBuilder constructor do? a. give the object, str, 25 bytes of storage and store spaces in them b. give the object, str, 25 bytes of storage and not store anything in them c. give the object, str, 25 or more bytes of storage and store spaces in them d. give the object, str, 0 bytes of storage ANS: B 13. What would be the results of executing the following code? StringBuilder str = new StringBuilder("Little Jack Horner "); str.append("sat on the "); str.append("corner"); a. b. c. d. The program would crash. str would reference "Little Jack Horner ". str would reference "Little Jac Horner sat on the ". str would reference "Little Jack Horner sat on the corner". ANS: D 14. When using the StringBuilder class's insert method, you can insert: a. any primitive type b. a String object c. a char array d. All of the above ANS: D Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 15. What will be the value of str after the following statements are executed? StringBuilder str = new StringBuilder("We have lived in Chicago, " + "Trenton, and Atlanta."); str.replace(17, 24, "Tampa"); a. b. c. d. We have lived in Tampa, Trenton, and Atlanta. We have lived in Chicago, Tampa, and Atlanta. We have lived in Tampa Trenton, and Tampa. We have lived in Tampalanta. ANS: A 16. Sometimes a string will contain a series of words or other items of data separated by spaces or other characters. In programming terms, items such as these are known as what? a. Tokens b. Delimiters c. Key characters d. lists ANS: A 17. What is the term used for the character that separates tokens? a. tokenizer b. delimiter c. whitespace d. separator ANS: B 18. The process of breaking a string down into tokens is known as what? a. tokenizing b. buffering c. simplifying d. parsing ANS: A 19. To a. b. c. d. use the StringTokenizer class you must have the following import statement. import java.util.StringTokenizer; import java.util.String; import java.StringTokenizer; import java.String; ANS: A 20. What will be the tokens in the following statement? StringTokenizer strToken = new StringTokenizer("123-456-7890", Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education "-", true); a. b. c. d. 123, 456, and 7890 123, 456, 7890, and None of the above ANS: C 21. For the following code, how many times would the while loop execute? StringTokenizer strToken = new StringTokenizer("Cars, trucks, and SUVs " + "are all types of automobiles."); while (strToken.hasMoreTokens()) { System.out.println(strToken.nextToken()); } a. b. c. d. 1 5 7 9 ANS: D 22. Each of the numeric wrapper classes has a static a. GetString b. Parse c. ToString d. Convert method that converts a number to a string. ANS: C 23. What does the following statement do? Double number = new Double(8.8); a. b. c. d. It creates a Double object It initializes that object to 8.8 It assigns the object's address to the number variable All of the above ANS: D 24. To a. b. c. d. convert the double double double double ANS: B string, str = "285.74" to a double, use the following statement. x = str; x = Double.parseDouble(str); x = Double.Double(str); x = str,Double.parseDouble; Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 25. To a. b. c. d. convert the int String str String str String str String str © 2012 Pearson Education variable, number to a string, use the following statement: = Integer.toString(number); = integer.toString(number); = integer(number); = number.Integer.toString(str); ANS: A 26. Which of the following statements will print the maximum value a double variable may have? a. System.out.println(MAX_VALUE); b. System.out.println(double.MAX_VALUE); c. System.out.println(Double.MAX_VALUE); d. System.out.println(Double.MAXIMUM_VALUE); ANS: C 27. Use a. b. c. d. the following import statement when using the Character wrapper class: import java.Char import java.lang.Char import java.String No import statement is needed ANS: D 28. What will be printed after the following code is executed? String str = "abc456"; int m = 0; while ( m < 6 ) { if (!Character.isLetter(str.charAt(m))) System.out.print( Character.toUpperCase(str.charAt(m))); m++; } a. b. c. d. 456 ABC456 ABC abc456 ANS: A 29. If str is declared as: String str = "ABCDEFGHI"; What will be returned from Character.toLowerCase(str.charAt(5))? a. e b. E c. f d. F Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: C 30. What will be the value of matches after the following code has been executed? boolean matches; String str1 = "The cow jumped over the moon."; String str2 = "moon"; matches = str1.endsWith(str2); a. b. c. d. true false moon The cow ANS: B 31. What will be the value of loc after the following code is executed? int loc; String str = "The cow jumped over the moon."; loc = str.lastIndexOf("ov", 14); a. b. c. d. 15 16 0 -1 ANS: D 32. What is the value of str after the following code has been executed? String str; String sourceStr = "Hey diddle, diddle, the cat and the fiddle"; str = sourceStr.substring(12,17); a. b. c. d. diddle diddl , didd Iddle ANS: B 33. Two ways of concatenating two Strings are: a. Use the concat() method or use the + between the two Strings b. Use the concatenate() method or use the + between the two Strings c. Use the contenate() method or the concat() method d. Use the concat() method or the trim() method ANS: A Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 34. The no-arg constructor for a StringBuilder object gives the object enough storage space to hold this many characters. a. 0 characters b. 8 characters c. 16 characters d. 32 characters ANS: C 35. What would be the results of executing the following code? StringBuilder str = new StringBuilder(12); str.append("The cow"); str.append(" jumped over the "); str.append("moon."); a. b. c. d. The program would crash str would reference "The cow jump" str would reference "The cow jumped over the " str would reference "The cow jumped over the moon." ANS: D 36. Given the following statement, which of the following is not true? str.insert(8, 32); a. b. c. d. str is a StringBuilder type object The insert will start at position 32 The starting position for the insert is 8 The literal number 32 will be inserted ANS: B 37. If you do not specify delimiters in the StringToken constructor, which of the following cannot be a delimiter? a. Space b. Tab c. Semicolon d. Newline ANS: C 38. What will be the tokens in the following statement? StringTokenizer strToken = new StringTokenizer("January 1, 2008", ", ", true); a. The tokens will be: January, 1 2008 b. The tokens will be , Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education space c. The tokens will be: January 1 2008 space d. The tokens will be: January space 1 , space 2008 ANS: D 39. For the following code, how many times would the while loop execute? StringTokenizer strToken = new StringTokenizer("Ben and Jerry's ice cream is great."); while (strToken.hasMoreTokens()) { System.out.println(strToken.nextToken()); } a. b. c. d. 1 3 5 7 ANS: D 40. This is the process of converting a wrapper class object to a primitive type. a. simplifying b. unboxing c. parsing d. devaluating ANS: B 41. What does the following statement do? Float number = new Float(8.8); a. b. c. d. It creates a Float object It initializes that object to 8.8 It assigns the object's address to the number variable All of the above Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: D 42. To a. b. c. d. convert the string, str = "285" to an int, use the following statement int x = str; int x = Integer.parseInteger(str); int x = Integer.integer(str); int x = Integer.parseInt(str); ANS: D 43. To convert the double variable, d = 543.98, to a string, use the following statement. a. String str = Double.toString(d); b. String str = double.toString(d); c. String str = double(d); d. String str = d.Double.toString(str); ANS: A 44. Autoboxing is: a. Java’s process of automatically “boxing up” a value inside an object b. The automatic allocation array elements c. The process of assigning a default value to primitive data types d. The process of identifying tokens in a string ANS: A 45. Which of the following statements will print the maximum value an int variable may have? a. System.out.println(MAX_VALUE); b. System.out.println(integer.MAX_VALUE); c. System.out.println(Integer.MAX_VALUE); d. System.out.println(INTEGER.MAX_VALUE); ANS: C 46. What will be the tokens in the following statement? String str = "red$green&blue#orange"; String tokens = str.split("[$&#]"); a. b. c. d. "red", "green", "blue"and "orange" "$", "&", and "#" "[", "$", "&", "#", and "]" None of the above ANS: A 47. Look at the following code. Integer myNumber; Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education myNumber = 5; Which of the following is true about the second statement? a. b. It results in an error because you cannot assign c. a primitive type to a wrapper class object. The statement performs autoboxing. d. The statement performs unboxing. The statement performs autowrapping. ANS: B 48. Look at the following code: Integer myNumber = new Integer(5); int var = myNumber; Which of the following is true about the second statement? a. b. It results in an error because you cannot assign c. a wrapper class object to a primitive variable. The statement performs autoboxing. d. The statement performs unboxing. The statement performs unwrapping. ANS: C TRUE/FALSE 1. The wrapper classes in Java are immutable, which means that once you create an object, you cannot change the object’s value. ANS: T 2. If a non-letter is passed to the toLowerCase or toUpperCase method, it is returned unchanged. ANS: T 3. The String class’s valueOf() method accepts a string representation as an argument and returns its equivalent integer value. ANS: F 4. You can change the contents of a StringBuilder object, but you cannot change the contents of a String object. ANS: T 5. StringBuilder objects are immutable. ANS: F 6. If you are using characters other than whitespaces as delimiters, you will probably want to trim the string before tokenizing; otherwise, the leading and/or following whitespaces will become part of the first and/or last token. ANS: T 7. You must call a method to get the value of a wrapper class object. Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: F 8. If a non-letter argument is passed to the toLowerCase or toUpperCase method, the boolean value false is returned. ANS: F 9. The String class’s valueOf() method accepts a value of any primitive data type as an argument and returns a string representation of the value. ANS: T 10. The following statement correctly creates a StringBuilder object. StringBuilder str = "Caesar Salad"; ANS: F 11. If a string has more than one character used as a delimiter, we must write a loop to determine the tokens, one for each delimiter character. ANS: F 12. You cannot assign a value to a wrapper class object. ANS: F Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education Chapter 10 MULTIPLE CHOICE 1. When an "is a" relationship exists between objects, it means that the specialized object has: a. some of the characteristics of the general class, but not all, plus additional characteristics. b. some of the characteristics of the general object, but not all. c. none of the characteristics of the general object. d. all the characteristics of the general object, plus additional characteristics. ANS: D 2. Which of the following a. public class b. public class c. public class d. public class statements declares Salaried as a subclass of PayType? Salaried extends PayType Salaried implements PayType Salaried derivedFrom(Paytype) PayType derives Salaried ANS: A 3. If ClassA extends ClassB, then: a. public and private members of ClassB are public and private, respectively, in ClassA b. public members in ClassB are public in ClassA, but private members in ClassB cannot be directly accessed in ClassA c. neither public or private members in ClassB can be directly accessed in ClassA d. private members in ClassB are changed to protected members in ClassA ANS: B 4. In an inheritance relationship: a. The superclass constructor always executes before the subclass constructor b. The subclass constructor always executes before the superclass constructor c. The constructor with the lowest overhead always executes first regardless of inheritance d. The unified constructor always executes first regardless of inheritance ANS: A 5. In UML diagrams, inheritance is shown: a. With a line that has an open arrowhead at one end that points to the superclass b. With a line that has an open arrowhead at one end that points to the subclass c. With a line that has a closed arrowhead at one end that points to the superclass d. With a line that has a closed arrowhead at one end that points to the subclass ANS: A 6. What key word can you use to call a superclass constructor explicitly? a. goto b. this c. super d. extends Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: C 7. What is wrong with the following code? public class ClassB extends ClassA { public ClassB() { int init = 10; super(40); } } a. b. c. d. Nothing is wrong with the code. The method super is not defined. The call to the method super must be the first statement in the constructor. No values may be passed to super. ANS: C 8. Look at the following code and determine what the call to super will do. public class ClassB extends ClassA { public ClassB() { super(10); } } a. b. c. d. This cannot be determined form the code shown. It will call the constructor of ClassA that receives an integer as an argument. It will call the method named super and pass the value 10 to it as an argument. The method super will have to be defined before we can say what will happen. ANS: B 9. If a subclass constructor does not explicitly call a superclass constructor: a. it must include the code necessary to initialize the superclass fields. b. the superclass fields will be set to the default values for their data types. c. Java will automatically call the superclass's default or no-arg constructor immediately after the code in the subclass's constructor executes. d. Java will automatically call the superclass's default or no-arg constructor just before the code in the subclass's constructor executes. ANS: D 10. The super statement that calls the superclass constructor: a. must be the first statement in the superclass’s constructor b. can appear in any method of the subclass c. must be the first statement in the subclass’s constructor d. is deprecated and is no longer supported in newer versions of Java Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: C 11. Replacing inadequate superclass methods with more suitable subclass methods is known as what? a. Method upgrading b. Tactical inheritance c. Method overriding d. Method overloading ANS: C 12. If two methods have the same name but different signatures, they are: a. overridden b. overloaded c. superclass methods d. subclass methods ANS: B 13. Look at the following code. The method in line Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10 Line 11 Line 12 a. b. c. d. will override the method in line public class ClassA { public ClassA() {} public int method1(int a){} public double method2(int b){} } public ClassB extends ClassA { public ClassB(){} public int method1(int b, int c){} public double method2(double c){} } 10, 4 11, 5 Both a and b None of the above ANS: D 14. Look at the following code. Which line will cause a compiler error? Line Line Line Line Line Line Line Line 1 2 3 4 5 6 7 8 public class ClassA { public ClassA() {} public final int method1(int a){} public double method2(int b){} } public ClassB extends ClassA { . Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e Line 9 Line 10 Line 11 Line 12 a. b. c. d. © 2012 Pearson Education public ClassB(){} public int method1(int b){} public double method2(double c){} } 4 5 10 11 ANS: C 15. When a subclass overloads a superclass method: a. Both methods may be called with a subclass object b. Only the subclass method may be called with a subclass object c. Only the superclass method may be called with a subclass object d. Neither method may be called with a subclass object ANS: A 16. A protected member of a class may be directly accessed by: a. methods of the same class b. methods of a subclass c. methods in the same package d. All of the above. ANS: D 17. When declaring class data members, it is best to declare them as: a. private members b. public members c. protected members d. restricted members ANS: A 18. If you do not provide an access specifier for a class member, the class member is given a. private b. public c. protected d. package ANS: D 19. When a method is declared with the a. extends b. final c. super d. public ANS: B modifier, it cannot be overridden in a subclass. by default. Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 20. If ClassC extends ClassB, which extends ClassA, this would be an example of: a. multiple inheritance. b. a chain of inheritance. c. a family tree. d. packaging. ANS: B 21. Look at the following code. Line Line Line Line Line Line Line Line Line Line Line Line Line Line Line 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class ClassA { public ClassA() {} public void method1(){} } public class ClassB extends ClassA { public ClassB(){} public void method1(){} } public class ClassC extends ClassB { public ClassC(){} public void method1(){} } Which method1 will be executed as a result of the following statements? ClassA item1 = new ClassC(); item1.method1(); a. b. c. d. Line 4 Line 9 Line 14 This is an error and will cause the program to crash ANS: C 22. Look at the following code. Line Line Line Line Line Line Line Line Line Line Line Line Line Line 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class ClassA { public ClassA() {} public void method1(int a){} } public class ClassB extends ClassA { public ClassB(){} public void method1(){} } public class ClassC extends ClassB { public ClassC(){} public void method1(){} Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e Line 15 } Which method will be executed as a result of the following statements? ClassB item1 = new ClassA(); item1.method1(); a. Line 4 b. Line 9 c. Line 14 d. This is an error and will cause the program to crash ANS: D 23. If a class contains an abstract method: a. you cannot create an instance of the class b. the method will have only a header, but not a body, and end with a semicolon c. the method must be overridden in subclasses d. All of the above ANS: D 24. Given the following code which of the following is true? public class ClassB implements ClassA{} a. b. c. d. ClassA ClassB ClassB ClassA must override each method in ClassB must override each method in ClassA inherits from ClassA inherits from ClassB ANS: B 25. All fields declared in an interface: a. are final and static b. have protected access c. must be initialized in the class implementing the interface d. have private access ANS: A 26. Look at the following code. Which line has an error? Line Line Line Line Line a. b. c. d. 1 2 3 4 1 2 3 4 5 public interface Interface1 { int FIELDA = 55; public int methodA(double){} } © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: D 27. Look at the following code. Which line in ClassA has an error: Line Line Line Line Line Line Line Line Line Line a. b. c. d. 1 2 3 4 5 6 7 8 9 10 public interface MyInterface { int FIELDA = 55; public int methodA(double); } public class ClassA implements MyInterface { FIELDA = 60; public int methodA(double) { } } 6 7 8 9 ANS: C 28. Look at the following code. What is missing from ClassA? Line Line Line Line Line Line Line Line Line Line a. b. c. d. 1 2 3 4 5 6 7 8 9 10 public interface MyInterface { int FIELDA = 55; public int methodA(double); } public class ClassA implements MyInterface { FIELDA = 60; public int methodB(double) { } } It does not override methodA. It does not have a constructor. It does not overload methodA. Nothing is missing. It is a complete class. ANS: A 29. When one object is a specialized version of another object, there is this type of relationship between them. a. "has a" b. "is a" c. direct d. "contains a" ANS: B 30. A subclass can directly access: a. all members of the superclass b. only public and private members of the superclass Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e c. d. only protected and private members of the superclass only public and protected members of the superclass ANS: D 31. In the following statement, which is the superclass? public class ClassA extends ClassB implements ClassC a. ClassA b. ClassB c. ClassC d. Cannot tell ANS: B 32. A subclass may call an overridden superclass method by: a. prefixing its name with the super key word and a dot (.) b. prefixing its name with the name of the superclass in parentheses c. using the extends keyword before the method is called d. calling the superclass method first and then calling the subclass method ANS: A 33. In the following statement, which is the subclass? public class ClassA extends ClassB implements ClassC a. ClassA b. ClassB c. ClassC d. Cannot tell ANS: A 34. In the following statement, which is the interface? public class ClassA extends ClassB implements ClassC a. ClassA b. ClassB c. ClassC d. Cannot tell ANS: C 35. What is wrong with the following code? public class ClassB extends ClassA { public ClassB() { super(40); System.out.println("This is the last statement " + "in the constructor."); © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education } } a. b. c. d. Nothing is wrong with the code The method super is not defined The call to the method super must be the first statement in the constructor No values may be passed to super ANS: A 36. In the following code, what will the call to super do? public class ClassB extends ClassA { public ClassB() { super(40); System.out.println("This is the last statement "+ "in the constructor."); } } a. This cannot be determined from the code. b. It will call the method super and pass the value 40 to it as an argument. c. It will call the constructor of ClassA that receives an integer as an argument. d. The method super will have to be defined before we can say what will happen. ANS: C 37. If a superclass does not have a default constructor or a no-arg constructor: a. then a class that inherits from it, must initialize the superclass values. b. then a class that inherits from it, must call one of the constructors that the superclass does have. c. then a class that inherits from it, does not inherit the data member fields from the superclass. d. then a class that inherits from it, must contain the default constructor for the superclass. ANS: B 38. Look at the following code. The method in line Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10 Line 11 Line 12 a. b. c. 4, 10 5, 11 10, 4 will override the method in line public class ClassA { public ClassA() {} public int method1(int a){} public int method2(int b){} } public ClassB extends ClassA { public ClassB(){} public int method1(int b){} public int method2(double c){} } . Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e d. e. © 2012 Pearson Education 11, 5 Both a and b ANS: C 39. Look at the following code. Which line will cause a compiler error? Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10 Line 11 Line 12 a. b. c. d. public class ClassA { public ClassA() {} public int method1(int a){} public final int method2(double b){} } public ClassB extends ClassA { public ClassB(){} public int method1(int b){} public int method2(double c){} } 4 5 10 11 ANS: D 40. Protected members are: a. not quite private b. not quite public c. Both A and B d. Neither A or B ANS: C 41. Protected class members are denoted in a UML diagram with the symbol a. * b. # c. + d. - ANS: B 42. Which of the following is true about protected access? a. Protected members may be accessed by methods in the same package or in a subclass, even when the subclass is in a different package. b. Protected members may be accessed by methods in the same package or in a subclass, but only if the subclass is in the same package. c. Protected members cannot be accessed by methods in any other classes. d. Protected members are actually named constants. ANS: A Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 43. Like a family tree, a a. flowchart b. class map c. class hierarchy d. binary tree © 2012 Pearson Education shows the inheritance relationship between classes. ANS: C 44. In a class hierarchy: a. the more general classes are toward the bottom of the tree and the more specialized are toward the top. b. the more general classes are toward the top of the tree and the more specialized are toward the bottom. c. the more general classes are toward the left of the tree and the more specialized are toward the right. d. the more general classes are toward the right of the tree and the more specialized are toward the left. ANS: B 45. Look at the following code: Line Line Line Line Line Line Line Line Line Line Line Line Line Line Line 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class ClassA { public ClassA() {} public void method1(int a){} } public class ClassB extends ClassA { public ClassB(){} public void method1(){} } public class ClassC extends ClassB { public ClassC(){} public void method1(){} } Which method1 will be executed when the following statements are executed? ClassA item1 = new ClassB(); item1.method1(); a. Line 4 b. Line 9 c. Line 14 d. This is an error and will cause the program to crash. ANS: B 46. Look at the following code: Line Line 1 2 public class ClassA { Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e Line Line Line Line Line Line Line Line Line Line Line Line Line 3 4 5 6 7 8 9 10 11 12 13 14 15 © 2012 Pearson Education public ClassA() {} public void method1(int a){} } public class ClassB extends ClassA { public ClassB(){} public void method1(){} } public class ClassC extends ClassB { public ClassC(){} public void method1(){} } Which method will be executed when the following statements are executed? ClassC item1 = new ClassA(); item1.method1(); a. b. c. d. Line 4 Line 9 Line 14 This is an error and will cause the program to crash. ANS: D 47. If a class contains an abstract method: a. you must create an instance of the class b. the method will have only a header, but not a body, and end with a semicolon c. the method cannot be overridden in subclasses d. All of the above. ANS: B 48. In an interface all methods have: a. private access b. protected access c. public access d. packaged access ANS: C 49. Which of the following statements correctly specifies three interfaces? a. public class ClassA implements Interface1, Interface2, Interface3 b. public class ClassA implements [Interface1, Interface2, Interface3] c. public class ClassA implements (Interface1, Interface2, Interface3) d. public class ClassA implements Interface1 Interface2 Interface3 ANS: A TRUE/FALSE Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 1. Inheritance involves a subclass, which is the general class, and a superclass, which is the specialized class. ANS: F 2. Private members of the superclass cannot be accessed by the subclass. ANS: T 3. It is not possible for a superclass to call a subclass's method. ANS: T 4. When a subclass extends a superclass, the public members of the superclass become public members of the subclass. ANS: T 5. If a method in a subclass has the same signature as a method in the superclass, the subclass method overloads the superclass method. ANS: F 6. Every class is either directly or indirectly derived from the Object class. ANS: T 7. An abstract class is not instantiated, but serves as a superclass for other classes. ANS: T 8. In an inheritance relationship, the subclass constructor always executes before the superclass constructor. ANS: F 9. If two methods in the same class have the same name but different signatures, the second overrides the first. ANS: F 10. Every class has a toString method and an equals method inherited from the Object class. ANS: T 11. All methods in an abstract class must also be declared abstract. ANS: F 12. When an interface variable references an object, you can use the interface variable to call any and all of the methods in the class implementing the interface. ANS: F Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education Chapter 11 MULTIPLE CHOICE 1. A(n) is an object that is generated in memory as the result of an error or an unexpected event. a. exception handler b. exception c. default exception handler d. error message ANS: B 2. All of the exceptions that you will handle are instances of classes that extend this class. a. RunTimeException b. IOException c. Error d. Exception ANS: D 3. All exceptions are instances of classes that extend this class. a. RunTimeException b. Throwable c. Error d. Exception ANS: B 4. If your code does not handle and exception when it is thrown, this prints an error message and crashes the program. a. Java error handler b. multi-catch c. default exception handler d. try statement ANS: C 5. In a try/catch construct, after the catch statement is executed: a. the program returns to the statement following the statement in which the exception occurred. b. the program terminates. c. the program resumes at the statement that immediately follows the try/catch construct. d. the program resumes at the first statement of the try statement. ANS: C 6. An exception’s default error message can be retrieved using this method. a. getMessage() b. getErrorMessage() c. getDefaultMessage() d. getDefaultErrorMessage() Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: A 7. The following catch statement can: catch (Exception e) {…} a. b. c. d. can handle all exceptions that are instances of the Exception class, but not a subclass of Exception. handle all throwable objects by using polymorphic reference as a parameter in the catch clause. handle all exceptions that are instances of the Exception class or a subclass of Exception. is an error since no objects are instantiated in the Exception class. ANS: C 8. The exception classes are in packages in the a. Java API b. JVM c. Compiler d. Ex class . ANS: A 9. If, within one try statement you want to have catch clauses of the following types, in which order should they appear in your program: (1) Exception (2) IllegalArgumentException (3) RuntimeException (4) Throwable a. b. c. d. 1, 2, 3, 4 2, 3, 1, 4 4, 1, 3, 2 3, 1, 2, 4 ANS: B 10. In the following code, assume that inputFile references a Scanner object that has been successfully used to open a file: Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education double totalIncome = 0.0; while (inputFile.hasNext()) { try { totalIncome += inputFile.nextDouble(); } catch(InputMismatchException e) { System.out.println("Non-numeric data encountered " + "in the file."); inputFile.nextLine(); } finally { totalIncome = 35.5; } } What will be the value of totalIncome after the following values are read from the file? 2.5 8.5 3.0 5.5 abc 1.0 a. b. c. d. 19.5 0.0 35.5 75.0 ANS: C 11. When an exception is thrown: a. it must always be handled by the method that throws it. b. the program terminates even if the exception is handled. c. it must be handled by the program or by the default exception handler. d. it may be ignored. ANS: C 12. If the code in a method can potentially throw a checked exception, then that method must: a. handle the exception b. have a throws clause listed in the method header c. Neither a or b d. Either a or b ANS: D 13. The numeric classes’ “parse” methods all throw an exception of this type if the string being converted does not contain a convertible numeric value. a. NumberFormatException b. ParseIntError c. ExceptionMessage Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e d. © 2012 Pearson Education FileNotFoundException ANS: A 14. Why does the following code cause a compiler error? try { number = Integer.parseInt(str); } catch (IllegalArgumentException e) { System.out.println("Bad number format."); } catch (NumberFormatException e) { System.out.println(str + " is not a number."); } a. b. c. d. Because you can have only one catch clause in a try statement. Because NumberFormatException inherits from IllegalArgumentException. The code should handle NumberFormatException before IllegalArgumentException. Because the Integer.parseInt method does not throw a NumberFormatException. Because the Integer.parseInt method does not throw an IllegalArgumentException. ANS: B 15. Given the following constructor code, which of the statements are true? public Book(String ISBNOfBook, double priceOfBook, int numberOrderedOfBook) { if (ISBNOfBook == "") throw new BlankISBN(); if (priceOfBook < 0) throw new NegativePrice(priceOfBook); if (numberedOrderedOfBook < 0) throw new NegativeNumberOrdered(numberOrderedv); ISBN = ISBNOfBook; price = priceOfBook; numberedOrdered = numberOrderedOfBook; } a. b. c. d. There is an error: a throws clause should be added to the constructor header. Classes extending the Exception class should be created for each of the custom exceptions that are thrown in the constructor. The calling method must handle the exceptions thrown in the constructor, or have its own throws clause specifying them. All of the above. ANS: D 16. The IllegalArgumentException class extends the RuntimeException class, and is therefore: Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e a. b. c. d. © 2012 Pearson Education a checked exception class. an unchecked exception class never used directly None of the above ANS: B 17. The ability to catch multiple types of exceptions with a single catch is known as introduced in Java 7. a. multi-catch b. super catch c. Exception trapping d. compound catch , and was ANS: A 18. What is demonstrated by the following code? try { (try block statements . . .) } catch(NumberFormatException | IOException ex) { respondToError(); } a. b. c. d. Multi-catch, a catch clause that can handle more than one exception, beginning in Java 7 A catch clause that can handle either exception type, but not both A conditional catch clause prototype that uses an overloaded OR operator to bind exception types. This code is not supported in any version of Java, an error will result. ANS: A 19. To write data to a binary file you create objects from the following classes: a. b. c. d. File and PrintWriter File and Scanner FileOutputStream and DataOutputStream BinaryFileWriter and BinaryDataWriter ANS: C 20. To read data from a binary file you create objects from the following classes: a. b. c. d. FileInputStream and DataInputStream File and PrintWriter File and Scanner BinaryFileReader and BinaryDataReader ANS: A 21. Look at the following code: Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education FileInputStream fstream = new FileInputStream("MyInfo.dat"); DataInputStream inputFile = new DataInputStream(fstream); This code can also be written as: a. FileInputStream inputFile = new FileInputStream(new DataInputStream("MyInfo.dat")); b. DataInputStream inputFile = new DataInputStream(new FileInputStream("MyInfo.dat")); c. FileInputStream fstream = new DataInputStream("InputFile.txt"); d. DataInputStream inputFile = new DataInputStream("InputFile.txt"); ANS: B 22. What will be the result of the following statements? FileInputStream fstream = new FileInputStream("DataIn.dat"); DataInputStream inFile = new DataInputStream(fstream); a. b. c. d. The inFile variable will reference an object that is able to read only text data from the Input.dat file. The inFile variable will reference an object that is able to read binary data from the Input.dat file. The inFile variable will reference an object that is able to write binary data to the Input.dat file. The inFile variable will reference an object that is able to read random access data from the Input.dat file ANS: B 23. When writing a string to a binary file or reading a string from a binary file, it is recommended that you use a. Methods that use UTF-8 encoding b. The Scanner class methods c. The FileReader and Writer class methods d. The System.In and System.Out methods ANS: A 24. If the IOData.dat file does not exist, what will happen when the following statement is executed? RandomAccessFile randomFile = new RandomAccessFile("IOData.dat", "rw"); a. b. c. d. A FileNotFoundException will be thrown An IOExcepton will be thrown The file IOData.dat will be created This is a critical error, the program will stop execution Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: C 25. This is a section of code that gracefully responds to exceptions when they are thrown. a. Thrown class b. Default exception handler c. Exception d. Exception handler ANS: D 26. Classes that inherit from the Error class are: a. for exceptions that are thrown when a critical error occurs, and the application program should not try to handle them. b. for exceptions that are thrown when a critical error occurs, and the application program should try to handle them. c. for exceptions that are thrown when an IOException occurs, and the application program should not try to handle them. d. for exceptions that are thrown when an IOException error occurs, and the application program should try to handle them. ANS: A 27. The catch clause: a. follows the try clause. b. starts with the word catch followed by a parameter list in parentheses containing an ExceptionType parameter variable. c. contains code to gracefully handle the exception type listed in the parameter list. d. All of the above. ANS: D 28. In a multi-catch, (introduced in Java 7) the exception types are separated in the catch clause by this symbol: a. * b. ? c. | d. & ANS: C 29. In a catch statement, what does the following code do? System.out.println(e.getMessage()); a. b. c. d. It prints the stack trace. It prints the error message for an exception. It prints the code that caused the exception. It overrides the toString method ANS: B 30. When an exception is thrown by code in the try block, the JVM begins searching the try statement for a catch clause that can handle it and passes control of the program to a. each catch clause that can handle the exception. b. the last catch clause that can handle the exception. c. the first catch clause that can handle the exception. Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e d. © 2012 Pearson Education If there are two or more catch clauses that can handle the exception, the program halts. ANS: C 31. If, within one try statement you want to have catch clauses that catch exceptions of the following types, in which order should they appear in your program? (1) Throwable (2) Exception (3) RuntimeException (4) NumberFormatException a. b. c. d. 4, 3, 2, 1 2, 3, 1, 4 4, 1, 3, 2 3, 1, 2, 4 ANS: A 32. The try statement may have an optional clauses. a. try-again b. finally c. default d. abort clause, which must appear after all of the catch ANS: B 33. If the program does not handle an unchecked exception: a. the exception is ignored. b. the program is halted and the default exception handler handles the exception. c. the program must handle the exception. d. this will cause a compilation error. ANS: B 34. Unchecked exceptions are those that inherit from: a. the Error class or the RuntimeException class. b. the Error class or the Exception class. c. the Exception Class or the RuntimeException class. d. only the Error class. ANS: A 35. If a method does not handle a possible checked exception, what must the method have? a. A catch clause in its header b. A try/catch clause in its header c. A try clause in its header d. A throws clause in its header ANS: D 36. Assume that the classes BlankISBN, NegativePrice, and NegativeNumberOrdered are exception classes that inherit from Exception. The following code is a constructor for the Book class. What must be true about any method that instantiates the Book class with this constructor? Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education public Book(String ISBNOfBook, double priceOfBook, int numberOrderedOfBook) throws BlankISBN, NegativePrice, NegativeNumberOrdered { if (ISBNOfBook == "") throw new BlankISBN(); if (priceOfBook < 0) throw new NegativePrice(priceOfBook); if (numberedOrderedOfBook < 0) throw new NegativeNumberOrdered(numberOrderedv); ISBN = ISBNOfBook; price = priceOfBook; numberedOrdered = numberOrderedOfBook; } a. b. c. d. It must call the constructor with valid data or a compiler error will occur. It must contain an inner class that extends the IOException class. It must handle all of the possible exceptions thrown by the constructor or have its own throws clause specifying them. All of the above. ANS: C 37. When you write a method that throws a checked exception, you must: a. b. c. d. have a throws clause in the method header. override the default error method. use each class only once in a method. ensure that the error will occur at least once each time the program is executed. ANS: A 38. In order for an object to be serialized, its class must implement this interface. a. b. c. d. Serial Writable Serializable ObjectOutputStream ANS: C 39. Under Windows, which of the following statements will open the file InputFile.txt that is in the root directory on the C: drive? a. FileReader freader = new FileReader("C:\InputFile.txt"); b. FileReader freader = new FileReader("C:\InputFile\txt"); c. FileReader freader = new FileReader("/c/InputFile.txt"); d. FileReader freader = new FileReader("C:\\InputFile.txt"); ANS: D 40. To serialize an object and write it to the file, use this method of the ObjectOutputStream class. a. b. c. SerializeObject WriteObject Serialize Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e d. © 2012 Pearson Education SerializeAndWrite ANS: B 41. What will be the result of the following code? FileOutputStream fstream new FileOutputStream("Output.dat"); DataOutputStream outputFile = new DataOutputStream(fstream); a. b. c. d. The outputFile variable will reference an object that is able to write text data only to the Output.dat file. The outputFile variable will reference an object that is able to write binary data to the Output.dat file. The outputFile variable will reference an object that is able to read binary data from the Output.dat file. The outputFile variable will reference an object that is able to write to Output.dat as a random access file. ANS: B 42. If you want to append data to the existing binary file, BinaryFile.dat, use the following statements to open the file. a. FileOutputStream fstream = new FileOutputStream("BinaryFile.dat"); DataOutputStream binaryOutputFile = new DataOutputStream(fstream); b. FileOutputStream fstream = new FileOutputStream("BinaryFile.dat", false); DataOutputStream binaryOutputFile = new DataOutputStream(fstream); c. FileOutputStream fstream = new FileOutputStream("BinaryFile.dat", true); DataOutputStream binaryOutputFile = new DataOutputStream(fstream); d. FileOutputStream fstream = new FileOutputStream("BinaryFile.dat"); DataOutputStream binaryOutputFile = new DataOutputStream(fstream, true); ANS: C 43. If a random access file contains a stream of characters, which of the following would you use to set the pointer on the fifth character? a. file.seek(4); b. file.seek(5); c. file.seek(9); d. file.seek(8); ANS: D 44. What will the following code display? String input = "99#7"; Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education int number; try { number = Integer.parseInt(input); } catch(NumberFormatException ex) { number = 0; } catch(RuntimeException ex) { number = 1; } catch(Exception ex) { number = -1; } System.out.println(number); a. b. c. d. 99 997 0 1 ANS: C TRUE/FALSE 1. When the code in a try block may throw more than one type of exception, you need to write a catch clause for each type of exception that could potentially be thrown. ANS: T 2. The call stack is an internal list of all the methods that are currently executing. ANS: T 3. The throw statement informs the compiler that a method throws one or more exception. ANS: F 4. A class must implement the Serializable interface in order for objects of the class to be serialized. ANS: T 5. When deserializing an object using the readObject method, you must cast the return value to the desired class type. ANS: T 6. A catch clause that uses a parameter variable of the Exception type is capable of catching any exception that extends the Error class. ANS: F Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 7. In versions of Java prior to Java 7, each catch clause can handle only one type of exception. ANS: T 8. When an exception is thrown by a method that is executing under several layers of method calls, a stack trace indicates the method executing when an exception occurred and all of the methods that were called in order to execute that method. ANS: T 9. Beginning in Java 7, multi-catch can reduce a lot of duplicated code in a try statement that needs to catch multiple exceptions, but perform the same operation for each one. ANS: T 10. The throws clause causes an exception to be thrown. ANS: F 11. When an object is serialized, it is converted into a series of bytes that contain the object’s data. ANS: T 12. If the class SerializedClass contains references to objects of other classes as fields, those classes must also implement the Serializable interface in order to be serialized. ANS: T © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e Chapter 12 MULTIPLE CHOICE 1. is a library of classes that do not replace creating GUI applications. a. AWT, Swing b. Swing, AWT c. JFC, AWT d. JFC, Swing , but provide an improved alternative for ANS: B 2. Programs that operate in a GUI environment must be: a. event driven b. in color c. dialog boxes d. layout managers ANS: A 3. In GUI terminology, a container that can be displayed as a window is known as a a. message dialog b. buffer c. Swing package d. frame . ANS: D 4. These components have a consistent look and predictable behavior on any operating system. a. AWT b. GUI c. Swing d. Peer classes ANS: C 5. To end an application, pass this as the argument to the JFrame class's setDefaultCloseOperation() method. a. END_ON_CLOSE b. JFrame.END_ON_CLOSE c. JFrame.EXIT_ON_CLOSE d. JFrame.CLOSE_NOT_HIDE ANS: C 6. Because these components rely on the appearance and behavior of the underlying operating system components, there is little that can be done by the programmer to change their properties. a. Swing b. AWT c. Container Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e d. © 2012 Pearson Education JFC ANS: B 7. The minimize button, maximize button, and close button on a window are sometimes referred to as: a. operations buttons b. sizing buttons c. decorations d. display buttons ANS: C 8. This is an action that takes place in an application, such as the clicking of a button. a. instance b. effect c. case d. event ANS: D 9. Which one of the following GUI components is considered to be a container? a. Frame b. Label c. Slider d. Button ANS: A 10. One of the small dots that make up a screen display is known as what? a. point b. color c. pixel d. texture ANS: C 11. In Swing, labels are created with this class: a. JFCLabel b. AWTLabel c. JLabel d. SwingLabel ANS: C 12. To use the ActionListener interface, as well as other event listener interfaces, you must have the following import statement in your code: a. import java.swing; b. import java.awt; c. import java.awt.*; d. import java.awt.event.*; Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: D 13. When you write an action listener class for a JButton component, it must: a. have a method named buttonClicked b. implement the ActionLIstener interface c. have a method named actionPerformed which must take an argument of the ActionEvent type d. Both b and c. ANS: D 14. In a Swing application, you create a frame object from the: a. Jlabel class b. JFrame class c. Jpanel class d. AbstractButton class ANS: B 15. To use the Color class, which is used to set the foreground and background of various objects, use the following import statement: a. import java.swing; b. import java.awt; c. import java.awt.*; d. import java.awt.event.*; ANS: C 16. This layout manager arranges components in rows. a. GridLayout b. BorderLayout c. FlowLayout d. RegionLayout ANS: C 17. This is commonly used to hold and organize collections of related components: a. list b. panel c. frame d. label ANS: B 18. This layout manager arranges components in regions named North, South, East, West, and Center. a. GridLayout b. BorderLayout c. FlowLayout d. RegionLayout Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: B 19. If panel references a JPanel object, which of the following statements adds the GridLayout to it? a. panel.setLayout(new (GridLayout(2,3)); b. panel.addLayout(new (GridLayout(2,3)); c. panel.GridLayout(2,3); d. panel.attachLayout(GridLayout(2,3)); ANS: A 20. When using the BorderLayout manager, how many components can each region hold? a. 1 b. 2 c. 5 d. No limit ANS: A 21. You use the a. listener b. interface c. implements d. static key word in a class header to indicate that it implements an interface. ANS: C 22. The GridLayout manager limits each cell to only one component. To put two or more components in a cell, do this: a. Resize the cells so they can hold more b. You can nest panels inside the cells, and add other components to the panels c. The statement is false. The GridLayout manager does not have this restriction d. Resize the components to fit in the cell ANS: B 23. Which of the following statements is not true? a. Radio buttons are round and check boxes are square. b. Radio buttons are often grouped together and are mutually exclusive; Check boxes are not c. Radio buttons and check boxes both implement the ActionListener interface d. They are all true ANS: C 24. How many radio buttons can be selected at the same time as the result of the following code? hours = new JRadioButton("Hours"); minutes = new JRadioButton("Minutes"); seconds = new JRadioButton("Seconds"); days = new JRadioButton("Days"); months = new JRadioButton("Months"); years = new JRadioButton("Years"); Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education timeOfDayButtonGroup = new ButtonGroup(); dateButtonGroup = new ButtonGroup(); timeOfDayButtonGroup.add(hours); timeOfDayButtonGroup.add(minutes); timeOfDayButtonGroup.add(seconds); dateButtonGroup.add(days); dateButtonGroup.add(months); dateButtonGroup.add(years); a. b. c. d. 1 2 3 4 ANS: B 25. Assume that radio references a JRadioButton object. To click the radio button in code, use the following statement: a. radio.Click(); b. Click(radio); c. Click(radio, true); d. radio.doClick(); ANS: D 26. The variable panel references a JPanel object. The variable bGroup references a ButtonGroup object, which contains several button components. If you want to add the buttons to the panel: a. b. c. d. use the statement, panel.add(bGroup); use the statement, bGroup.add(panel); use the statement, Panel panel = new Panel(bGroup); add each button to panel one at a time, e.g. panel.add(button1); ANS: D 27. What will be the result of executing the following statement? panel.setBorder(BorderFactory.createLineBorder(Color.BLUE, 5)); a. b. c. d. The JPanel referenced by panel will have a blue line border that is 5 millimeters thick. The JPanel referenced by panel will have a blue line border that is 5 pixels thick. The JPanel referenced by panel will have a blue line border that is 5 characters thick. The JPanel referenced by panel will have a blue line border that is 5 inches thick. ANS: B 28. When an application uses many components, rather than deriving just one class from the JFrame class, it is often better to encapsulate smaller groups of related components and their event listeners into their own class. A commonly used technique to do this is: a. To extend a class from the JAbstractButton class to contain other components and their related code b. To extend a class from the JComponent class to contain other components and their related code Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e c. d. © 2012 Pearson Education To extend a class from the JPanel class to contain other components and their related code To extend a class from the JFrame class to contain other components and their related code ANS: C 29. To include Swing and AWT components in your program, use the following import statements: a. import java.swing; import java.awt; b. import java.swing; import javax.awt; c. import javax.swing; import java.awt; d. import javax.swing; import javax.awt; ANS: C 30. AWT components are commonly called underlying peer classes. a. Lightweight b. Featherweight c. Middleweight d. Heavyweight components because they are coupled with their ANS: D 31. JFC stands for: a. Java Fundamental Classes b. Java Foundation Classes c. Java Fundamental Core d. Java Frame Class ANS: B 32. When this is the argument passed to the JFrame class's setDefaultCloseOperation() method, the application is hidden, but not closed. a. HIDE_ON_CLOSE b. JFrame. HIDE_ON_CLOSE c. JFrame.EXIT_ON_CLOSE d. JFrame.HIDE_NOT_CLOSE ANS: B 33. This is a basic window that has a border around it, a title bar, and a set of buttons for minimizing, maximizing, and closing the window. a. Pane b. Container c. Frame d. Dialog box ANS: C 34. Which of the following statements creates a class that is extended from the JFrame class? a. JFrame DerivedClass = new JFrame(); Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e b. c. d. © 2012 Pearson Education class JFrame DerivedClass; JFrame(DerivedClass); public class DerivedClass extends JFrame{} ANS: D 35. What does the following statement do? addButton.addActionListener(new AddButtonListener()); a. b. c. d. Creates an AddButtonListener object Registers the addButton object as an ActionListener with the AddButtonListener object Creates an AddButtonListener object and registers the AddButtonListener object with the addButton Nothing, the statement is invalid ANS: C 36. Event listeners must: a. implement an interface b. be included in private inner classes c. not receive any arguments d. exit the application once it has handled the event ANS: A 37. If button1 is a JButton object, which of the following statements will make its background blue? a. button1.makeBackground(BLUE); b. button1.setBackground(Color.BLUE); c. button1.makeBackground(Color.BLUE); d. button1.set.Background(BLUE); ANS: B 38. This layout manager arranges components in five regions. a. GridLayout b. BorderLayout c. FlowLayout d. RegionLayout ANS: B 39. Which of the following is not a rule for the FlowLayout manager? a. Multiple components can be added to a container that uses a FlowLayout manager b. New components will be added in a row from left to right c. When there is no more room in a row, additional components are put on the next row d. All of these are rules for the FlowLayout manager ANS: D Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 40. When a component is added to a region in the BorderLayout manager: a. the component retains its original size b. it results in a compile time error, if it is too large c. the component is stretched so it fills up the entire region d. the region is resized to fit the component ANS: C 41. When adding components to a container that is governed by the GridLayout manager: a. you cannot specify a cell b. you specify the cell with the row and column numbers in the add statement c. you must add them starting with the lower, right cell d. the components are added automatically by filling up the first column, then the second, etc. ANS: A 42. Which of the following statements is not true? a. Radio buttons are round and check boxes are square. b. Radio buttons are often grouped together and are mutually exclusive; Check boxes are not c. Radio buttons implement ActionListener; Check boxes implement ItemListener d. All of these are true ANS: D 43. Why doesn't the following code compile correctly? import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ColorCheckBoxWindow extends JFrame { private JCheckBox greenCheckBox; private final int WINDOW_WIDTH = 300, WINDOW_HEIGHT = 100; public ColorCheckBoxWindow() { setTitle("Green Check Box"); setSize(WINDOW_WIDTH, WINDOW_HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); greenCheckBox = new JCheckBox("Green"); greenCheckBox.addItemListener(new CheckBoxListener()); setLayout(new FlowLayout()); add(greenCheckBox); setVisible(true); } public void itemStateChanged(ItemEvent e) { if (e.getSource() == greenCheckBox) { System.exit(0); } } } a. ColorCheckBoxWindow is not implementing the correct listener Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e b. c. d. © 2012 Pearson Education The button cannot be added to the content pane The itemStateChanged method cannot be coded here greenCheckBox should not be a private member ANS: C 44. Assume that the variable checkbox references a JCheckBox object. To determine whether the check box has been selected, use the following code: a. if (isSelected(checkBox)) {/*code to execute, if selected*/} b. if (checkBox.isSelected()) {/*code to execute, if selected*/} c. if (checkBox) {/*code to execute, if selected*/} d. if (checkBox.doClick()) {/*code to execute, if selected*/} ANS: B 45. What will be the result of executing the following statement? panel.setBorder(BorderFactory.createTitleBorder("Title")); a. b. c. d. The JPanel referenced by panel will have an etched border with the title "Title" displayed on it. The JPanel referenced by panel will have an empty border with the title "Title" displayed on it. The JPanel referenced by panel will have a line border with the title "Title" displayed on it. The JPanel referenced by panel will have a compound border with the title "Title" displayed on it. ANS: A 46. When an application uses many components, instead of extending just one class from the JFrame class, a better approach is to: a. break the application into several smaller applications b. reconsider the design of the application c. encapsulate smaller groups of related components and their event listeners into their own classes d. just go ahead and do it in one large class ANS: C 47. This is a graphic image that is displayed while an application loads into memory and starts up. a. The Java 6 trademark screen b. Memory usage screen c. Blue screen of death d. Splash screen ANS: D 48. You would use this command at the operating system command line to execute the code in the MyApplication class and display the graphic image Logo.jpg as a splash screen. a. java MyApplication Logo.jpg b. java -splash:Logo.jpg MyApplication c. java MyApplication –splash d. java Logo.jpg –splash:MyApplication Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: B TRUE/FALSE 1. Some of the common GUI components are buttons, labels, text fields, check boxes, and radio buttons. ANS: T 2. A GUI program automatically stops executing when the end of the main method is reached. ANS: F 3. A common technique for writing an event listener class is to write it as a private inner class inside the class that creates the GUI. ANS: T 4. The following statement adds the FlowLayout manager to the container, centers the components, and separates the components with a gap of 10 pixels. setLayout(new FlowLayout()); ANS: F 5. Check boxes may be grouped in a ButtonGroup, like radio buttons are. ANS: T 6. All operating systems offer the same set of GUI components. ANS: F 7. The System.exit method will end the application. ANS: T 8. The ActionEvent argument that is passed to an action listener's actionPerformed method is the event object that was generated in response to an event. ANS: T 9. The FlowLayout manager does not allow the programmer to align components. ANS: F 10. You must use the statement import java.swing.*; in order to use the ItemListener interface. ANS: F 11. When a splash screen is displayed, the application does not load and execute until the user clicks the splash screen image with the mouse. ANS: F Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 12. The ability to display splash screens was introduced in Java 6. ANS: T © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education Chapter 13 MULTIPLE CHOICE 1. A text field that can be changed by code in the application, but cannot be edited by the user is known as what? a. Write-only b. Static c. Read-only d. Formal ANS: C 2. What will be the results of executing the following statements? x.setEditable(true); x.setText("Tiny Tim"); a. b. c. d. The text field x will have the value "Tiny Tim" and be read-only. The text field x will have the value "Tiny Tim" and the user will be able to change its value. The text field x will have the value true. The text field x have the value "trueTiny Tim" ANS: B 3. Java provides this component for creating lists: a. JColumn b. JList c. JPanel d. JFrame ANS: B 4. The default selection mode for a JList component is: a. single selection b. single interval selection c. multiple interval selection d. There is no default setting. ANS: C 5. When an item in a Jlist object is selected it generates a(n): a. action listener event b. action performed event c. list selection listener event d. list selection event ANS: D 6. To determine which item in a list is currently selected use: a. the getSelectedIndex method b. the getSelectedValue method Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e c. d. © 2012 Pearson Education Both a and b Neither a or b ANS: C 7. To a. b. c. d. add the JList object addressList to a scroll pane named scrollPane, use the following JScrollPane scrollPane = new JScrollPane(addressList); scrollPane.add(addressList); addressList.add(scrollPane); addressList.addScrollPane(scrollPane); ANS: A 8. If addressList is a JList component, what will the value of x be after the following statement is executed? x = addressList.getSelectedIndex(); a. b. c. d. The value of the first selected item. The index of the first selected item. An array of objects containing the items selected. An array containing the indices of all the selected items in the list. ANS: B 9. When an item in the combo box is selected, the combo box executes its action event listener's actionPerformed method, passing: a. an ItemEvent object as an argurment. b. a SelectionEvent object as an argurment. c. an ActionEvent object as an argument. d. the combo box as an argument. ANS: C 10. If the combo box addressBox contains a list of strings, why is the returned value of getSelectedItem method in the following code cast to String? String selectedAddress; selectedAddress = (String)addressBox.getSelectedItem(); a. b. c. d. This is not necessary. Because the syntax of the method requires it. It makes the program more readable Because the return type of the method is an Object. ANS: D 11. This type of combo box combines a button with a list and allows the user to select items from its list only. a. Editable b. Static c. Bound d. Uneditable Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: D 12. If a user enters a value in the text box of an editable combo box and the value is not in the list, what will the method getSelectedIndex return? a. The index of the item that the user replaced. b. The index of the item the user entered. c. -1 d. 0, since the item is not in the list. ANS: C 13. The ImageIcon class supports all the following file types, except: a. BMP b. JPEG c. GIF d. PNG ANS: A 14. What will display when the following code is executed: JLabel label = new JLabel ("It is a beautiful morning."); labed.setIcon(SunnyFace.gif); a. b. c. d. A label with the text "It is a beautiful day." to the left of the SunnyFace image. A label with the text "It is a beautiful day." to the right of the SunnyFace image. A label with the text "It is a beautiful day." below the SunnyFace image. A label with the text "It is a beautiful day." above the SunnyFace image. ANS: B 15. To force the JFrame that encloses a window to resize itself automatically when a larger object is placed in the frame, use: a. the pack method. b. the resize method. c. the grow method. d. the enlarge method. ANS: A 16. A mnemonic is: a. A single key on the keyboard that you press to quickly access a component such as a button. b. A key on the keyboard that you press in combination with the SHIFT key to quickly access a component such as a button. c. A key on the keyboard that you press in combination with the ALT key to quickly access a component such as a button. d. A key on the keyboard that you press in combination with the CTRL key to quickly access a component such as a button. Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: C 17. To add a tool tip to a component use: a. the setToolTipText method. b. the addToolTipText method. c. the toolTipText method. d. the appendToolTipText method. ANS: A 18. The a. b. c. d. default directory for the JFileChooser constructor is: Your login directory if you are using UNIX Probably My Documents if you are using Windows Neither a nor b Both a and b ANS: D 19. What will happen when the following code is executed? JPanel panel = new JPanel(); Color selectedColor; selectedColor = JColorChooser.showDialog(null, "Select color", Color.BLUE); a. b. c. d. A Color Chooser will be displayed in the upper, left-hand corner of the screen with "Select color" in its Title Bar and blue pre-selected. A Color Chooser will be displayed in the center of the screen with "Select color" in its Title Bar and blue pre-selected. A Color Chooser will be displayed in the center of the screen with "Select color" as the OK button's text and blue pre-selected. A Color Chooser will be displayed in the lower, right-hand corner of the screen with "Select color" in its Title Bar and blue pre-selected. ANS: B 20. A menu system may consist of each of the following, except: a. check box menu item b. combo box menu item c. radio button menu item d. menu item ANS: B 21. A a. b. c. d. object specifies a component’s width and height. Container Region Frame Dimension ANS: D Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 22. Which of the following is not a class used in constructing a menu system? a. JMenuItem b. JCheckBoxMenuItem c. JButton d. JRadioButtonMenuItem ANS: C 23. The a. b. c. d. Dimension class is part of the: javax.swing.event package java.awt.menu package javax.swing package java.awt package ANS: D 24. What will the following code do when it is executed? JTextArea message = JTextArea(greetings, 50, 70); JScrollPane scrollPane = new JScrollPane(message); a. b. c. d. It will create a JScrollPane object for the JTextArea object referenced display a horizontal scroll bar on the text area. It will create a JScrollPane object for the JTextArea object referenced display a vertical scroll bar on the text area. It will create a JScrollPane object for the JTextArea object referenced display both vertical and horizontal scroll bars on the text area. It will create a JScrollPane object for the JTextArea object referenced display no scroll bars on the text area. by message and by message and by message and by message and ANS: C 25. What will happen when the following statement is executed? x.setEditable(false); a. b. c. d. The boolean variable x will be set to false. The text field x will be made read-only. The text field x will be editable. The boolean variable x will be editable. ANS: B 26. When you create an instance of the JList class: a. you pass an array of objects to the constructor. b. the list has a default selection mode of Single Selection Mode. c. the values in the list are automatically sorted. d. you must indicate the maximum number of list items the user may select at any one time. ANS: A Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 27. The following statement: textList.setSelectionMode( ListSelectModel.SINGLE_INTERVAL_SELECTION); a. b. c. d. sets the textList component to single selection mode. sets the textList component to ListSelectModel. sets the textList component to single interval selection mode. sets the value of textList to SINGLE_INTERVAL_SELECTION. ANS: C 28. The a. b. c. d. getSelectedIndex method returns: the index of the selected item. -1 if no item is selected. Both a and b. Neither a or b. ANS: C 29. If nameList is a JList component, use the following statement to display 4 rows in nameList. a. nameList.setRowCount(4); b. nameList.setDisplayRowCount(4); c. nameList.setShowRowCount(4); d. nameList.setVisibleRowCount(4); ANS: D 30. If addressList exists and has values stored in it and addrList is an array with values stored in it, what will be the results when the following code is executed? addressList.setListData(addrList); a. b. c. d. The values of addrList will be attached at the end of the current addressList. The values in addressList will be replaced by the values in addrList. The values of addrList will be inserted at the beginning of the current addressList. addressList will be unchanged. ANS: B 31. The a. b. c. d. JComboBox class is in the: javax.swing package java.awt package java awt.event package java.swing.event package ANS: A 32. Images may be displayed in labels and: a. lists b. buttons Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e c. d. © 2012 Pearson Education combo boxes panels ANS: B 33. If a user enters a value in the text box of an editable combo box and the value is not in the list, what will the method getSelectedItem return? a. The value that the user replaced b. The index of the item the user entered c. The value that appears in the text field, even if it is not in the combo box's list d. Nothing, since the item is not in the list ANS: C 34. The ImageIcon class constructor accepts: a. an integer that references the image. b. a String argument which is the name of the image file. c. a String argument which is the name of the image. d. it does not accept any arguments. ANS: B 35. What will display when the following code is executed: JButton button = new JButton ("It is a beautiful day."); button.setIcon(SunnyFace.gif); a. b. c. d. A button with the text "It is a beautiful day." to the left of the SunnyFace image. A button with the text "It is a beautiful day." to the right of the SunnyFace image. A button with the text "It is a beautiful day." below the SunnyFace image. A button with the text "It is a beautiful day." above the SunnyFace image. ANS: B 36. What will display when the following code is executed? imagePanel = new JPanel(); imageLabel = new JLabel(); imagePanel.Add(imageLabel); ImageIcon sunnyFaceImage = new ImageIcon("SunnyFace.gif"); imageLabel.setIcon(sunnyFaceImage); pack(); a. b. c. d. The JFrame that encloses the window will resize itself to accommodate the SunnyFace image. imagePanel will resize itself to accommodate the SunnyFace image. The SunnyFace image will resize itself to fit on imageLabel. The SunnyFace image will resize itself to fit on imagePanel. ANS: A Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 37. If the letter chosen as the mnemonic is in the component’s text, the first occurrence of that letter will appear when the component is displayed. a. bolded b. italicized c. underlined d. All of the above ANS: C 38. Which of the following assigns ALT+C as a mnemonic key for the JButton object, clearButton? a. clearButton.addMnemonic(KeyEvent.VK_C); b. clearButton.setMnemonic(KeyEvent.C); c. clearButton.setMnemonic(KeyEvent.VK_C); d. clearButton.assignMnemonic(KeyEvent.VK_C); ANS: C 39. A tool tip is: a. a guide provided by the Help menu as to which tool to use for various programming techniques. b. another name for the Tool Bar. c. used to make programming easier. d. text that is displayed in a small box when the user holds the mouse cursor over a component. ANS: D 40. This is a specialized dialog box that allows the user to select a color from a predefined palette of colors. a. Hue picker b. Color chooser c. Paint dialog box d. Palette selector ANS: B 41. If the argument passed to the showOpenDialog method is null: a. the dialog box will normally be displayed in the upper, left-hand corner of the screen. b. the dialog box will normally be centered in the screen. c. nothing will be displayed because there was nothing passed to the method. d. -1 will be returned from the method. ANS: B 42. What will be the results of executing the following code, if the user simply clicks OK? JPanel panel = new JPanel(); Color selectedColor; selectedColor = JColorChooser.showDialog(null, "Select color", Color.blue); panel.setForeground(selectedColor); a. b. The foreground color will remain unchanged. The foreground color will be set to white. Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e c. d. © 2012 Pearson Education The foreground color will be set to black. The foreground color will be set to blue. ANS: D 43. A menu system may consist of each of the following except: a. menu item b. separator bar c. menu bar d. It may have all the above. ANS: D 44. A menu within a menu is called what? a. Nested menu b. Submenu c. Recursive menu d. Formal list ANS: B 45. Which of the following is not a class used in constructing a menu system? a. JMenuItem b. JCheckBoxMenuItem c. JComboBoxMenuItem d. JRadioButtonMenuItem ANS: C 46. The a. b. c. d. JMenuBar method is a(n): JFrame method JPanel method JMenu method JTextComponent method ANS: A 47. What does the following statement do? JTextArea textField = JTextArea(message, 25, 15); a. It creates a text area with 25 columns and 15 rows that will initially display the text stored in the String object message. b. It creates a text area with 25 columns and 15 rows that will initially display the text stored in the text area textField. c. It creates a text area with 25 rows and 15 columns that will initially display the text stored in the String object message. d. It creates a text area with 25 rows and 15 columns that will initially display the text "message". Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: C 48. Which of the following statements creates a horizontal slider component with a minimum value of 0, a maximum value of 50, and an initial value of 25? a. JSlider slider = new JSlider(0, 50, 25, JSlider.HORIZONTAL); b. JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25); c. JSlider slider = new JSlider(JSlider.HORIZONTAL, 25, 0, 50); d. JSlider slider = new JSlider(JSlider.HORIZONTAL, 50, 0, 25); ANS: B TRUE/FALSE 1. Both AWT classes and Swing classes ultimately inherit from the Component class. ANS: T 2. A read-only text field uses the JReadOnlyTextField component. ANS: F 3. By default the scroll bars are always displayed in a JList component. ANS: F 4. When creating images, the argument passed to the image parameter in the JLabel constructor can be an ImageIcon object, or any object that implements the Icon interface. ANS: T 5. In the following code the setPreferredSize method sets the size of the text, "Have a good day". label = new Jlabel("Have a good day", SwingConstants.CENTER); label.setPreferredSize(new Dimension(400,200)); ANS: F 6. When using a slider, by default, tick marks are not displayed, and setting their spacing does not cause them to be displayed. ANS: T Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 7. When a JList component is added to a JScrollPane object, a border will automatically appear around the list. ANS: T 8. You can create a label with an image, or with both an image and text. ANS: T 9. A label's preferred size is determined only by calling the setPreferredSize method. ANS: F 10. When you write a change listener class method for a slider, it must implement the ChangeListener interface which is in the javax.swing.event package. ANS: T Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education Chapter 14 MULTIPLE CHOICE 1. Applets are important because the can be used to: a. extend the capabilities of a web page. b. process large data files. c. run other programs on the user's system. d. convert machine language into HTML. ANS: A 2. When someone visits a Web page containing a Java applet: a. the applet is executed on the server and displayed on the Web page b. the applet is downloaded to the visitor’s browser and executed c. the applet is executed using a portion of the resources from each visitor’s browser d. the visitor’s browser acts as the server and hosts the applet for other visitors ANS: B 3. Applet restrictions are: a. necessary to prevent malicious code from attacking or spying on unsuspecting users b. determined by the Web browser c. optional in Java 7 d. enabled only if the applet is running on a Web server ANS: A 4. Which of the following is not a restriction placed on applets? a. Applets cannot create files on the user's system. b. Applets cannot execute operating system procedures on the user's system. c. Applets cannot display a window. d. Applets cannot retrieve the user's identity. ANS: C 5. Due to security restrictions, applets cannot: a. Delete files b. Read the contents of files c. Create files on the user’s system d. All of the above ANS: D 6. is the language that Web pages are written in. a. b. c. d. PHP XML HTML JavaScript Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: C 7. An HTML document is usually saved with what file name extension? a. .xml b. .asp c. .js d. html ANS: D 8. In an HTML document, the tags: a. instruct the Web browser how to format the text. b. instruct the Web browser where to place images. c. instruct the Web browser what to do when the user clicks on a link. d. All of the above ANS: D 9. Which tag will produce largest text? a. <h4>Hello</h4> b. <h3>Hello</h3> c. <h2>Hello</h2> d. <h1>Hello</h1> ANS: D 10. In the link produced by the following HTML, what word would you click to go to the linked location? Click here to learn more about <a href="http://www.applications.com">applications.</a> a. b. c. d. Click here Click here to learn more about applications ANS: D 11. What does the tag <p /> cause to happen? a. A double space b. A paragraph break c. Indentation for a paragraph d. Plain text to be displayed ANS: B 12. Which of the following will load the applet, TestApplet? a. <applet code="TestApplet.class" width=200 height=50> </applet> b. <applet code=TestApplet.class width=200 height=50> </applet> c. <load code="TestApplet.class" width=200 height=50> Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e d. © 2012 Pearson Education </load> <load code=TestApplet.class w=200 h=50> </load> ANS: A 13. An applet using a Swing GUI extends which class? a. Applet b. JApplet c. JSwing d. JFrame ANS: B 14. In the following code, which line has an error? 1 2 3 4 5 6 7 8 9 10 a. b. c. d. public class TestApplet extends JApplet { public void init() { super.JApplet(); JLabel label = new JLabel("Test label"); setLayout(new FlowLayout()); add(label); } } 1 3 5 There are no errors ANS: C 15. When the applet viewer opens an HTML document with more than one applet tag: a. it terminates immediately. b. it displays the first applet, and then terminates. c. it displays each applet in a separate window. d. it displays each applet in order in the same window. ANS: C 16. Which of the following is not a valid AWT class? a. Panel b. Applet c. TextArea d. JMenu ANS: D 17. If a frame component is 200 pixels wide and 300 pixels high, the lower, left-hand corner has (X, Y) coordinates of: Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e a. b. c. d. © 2012 Pearson Education (0, 299) (0, 300) (200, 0) (0, 0) ANS: A 18. Look at the following applet code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import javax.swing.*; import java.awt.*; public class GraphicsTest extends JApplet { public void init() { getContentPane().setBackground(Color.WHITE); } public void paint(Graphics g) { int[] xCoords = {20, 20, 60, 100, 140, 140, 100, 60}; int[] ycoords = {20, 100, 140, 140, 100, 60, 20, 20}; super.paint(g); g.setColor(Color.YELLOW); g.fillPolygon(xCoords, yCoords, 8); g.setColor(color.BLACK); g.setFont(new Font("SansSerif", Font.BOLD, 35)); g.drawString("SLOW", 35, 95); } } How many vertices does the polygon have? a. 5 b. 6 c. 7 d. 8 ANS: D 19. Look at the following applet code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import javax.swing.*; import java.awt.*; public class GraphicsTest extends JApplet { public void init() { getContentPane().setBackground(Color.WHITE); } public void paint(Graphics g) { int[] xCoords = {20, 20, 60, 100, 140, 140, 100, 60}; int[] ycoords = {20, 100, 140, 140, 100, 60, 20, 20}; super.paint(g); g.setColor(Color.YELLOW); g.fillPolygon(xCoords, yCoords, 8); Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 16 g.setColor(color.BLACK); 17 g.setFont(new Font("SansSerif", Font.BOLD, 35)); 18 g.drawString("SLOW", 35, 95); 19 } 20 } What is the color of the polygon? a. White b. Yellow c. Black d. None of the above ANS: B 20. Look at the following applet code. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import javax.swing.*; import java.awt.*; public class GraphicsTest extends JApplet { public void init() { getContentPane().setBackground(Color.WHITE); } public void paint(Graphics g) { int[] xCoords = {20, 20, 60, 100, 140, 140, 100, 60}; int[] ycoords = {20, 100, 140, 140, 100, 60, 20, 20}; super.paint(g); g.setColor(Color.YELLOW); g.fillPolygon(xCoords, yCoords, 8); g.setColor(color.BLACK); g.setFont(new Font("SansSerif", Font.BOLD, 35)); g.drawString("SLOW", 35, 95); } } What will be the coordinates of the third point of the polygon? a. (60, 140) b. (140, 60) c. (100, 140) d. (140, 100) ANS: A 21. A mouse motion listener class can respond to: a. The mouse button is clicked on b. The mouse cursor exits a component's screen space c. The mouse moved d. The mouse button is released ANS: C Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 22. When you extend an interface, you must implement all the methods defined in the interface. If you are interested in only one or two mouse events, you can extend the class which implements the MouseListener interface, but does not require you to write all the functions in the interface. a. MouseAdapter b. MouseExtender c. MouseMotionAdapter d. MouseMotionExtender ANS: A 23. Given the following code, how many times per second will the TimerListener event be generated? Timer timer = new Timer(1000, new TimerListener()); a. b. c. d. 1 10 100 1000 ANS: A 24. Which of the following sound file formats does Java not support? a. .wav b. .au c. mid d. Java supports all of the above ANS: D 25. These are Java programs that are usually part of a Web site. a. Applications b. Applets c. Classes d. Web services ANS: B 26. If an applet attempts to violate one of the JVM restrictions: a. the program has a fatal error. b. it will display a window stating that it has violated the restriction. c. an exception is thrown. d. it automatically notifies the Web server of the violation. ANS: C 27. Hypertext can contain: a. a Java application program b. exception methods c. executable code d. a link to another Web page © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e ANS: D 28. What does the HTML tag <hr /> cause to happen? a. A header routine is created. b. A horizontal line will be displayed. c. A default header reference will be linked to. d. The window will be blanked out before the remainder of the text is displayed. ANS: B 29. What will happen if you use </CENTER> instead of </center> in an HTML document? a. The tag will be ignored b. The text inside the tag will be centered just the same. c. The text inside the tag will be centered and appear in all uppercase letters d. An exception will be thrown. ANS: B 30. One way of viewing the results of the applet which is invoked in the HTML document TestApplet.html is to enter the following at the command prompt. a. appletviewer TestApplet.html b. appleviewer TestApplet c. viewapplet TestApplet.html d. view TestApplet ANS: A 31. To support the Swing classes in applets, some browsers require a or enhances another program. a. extension b. plug-in c. booster d. widget ANS: B 32. An applet using a Swing GUI is extended from this class. a. JFrame b. JLabel c. JSwing d. JApplet ANS: D 33. In the following code that uses a Swing GUI, which line has an error? 1 2 3 4 5 6 public class TestApplet extends Applet { public void init() { JLabel label = new JLabel("Test label"); setLayout(new FlowLayout()); , which is software that extends Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 7 9 a. b. c. d. © 2012 Pearson Education add(label);8 } } 1 3 5 There are no errors ANS: A 34. In an applet, events are handled: a. with special applet event listeners. b. differently, depending upon which computer is running the applet. c. with event listeners, exactly as they are in GUI applications. d. by always terminating the applet. ANS: C 35. The object is responsible for drawing the entire applet window. a. Graphics b. Applet c. SuperClass d. JFrame ANS: A 36. If a frame component is 300 pixels wide and 200 pixels high, the upper, right-hand corner has (X, Y) coordinates of: a. (0, 0) b. (300, 0) c. (200, 300) d. (299, 0) ANS: D 37. Look at the following applet code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import javax.swing.*; import java.awt.*; public class GraphicsTest extends JApplet { public void init() { getContentPane().setBackground(Color.WHITE); } public void paint(Graphics g) { super.paint(g); g.setColor(Color.YELLOW); g.fillOval(100, 100, 50, 50); g.setColor(Color.BLACK); g.setFont(new Font("SansSerif", Font.BOLD, 35)); Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 16 g.drawString("SLOW", 110, 110); 17 } 18 } Which line sets the color that will be used to draw "SLOW"? a. 7 b. 12 c. 14 d. 16 ANS: C 38. Look at the following applet code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import javax.swing.*; import java.awt.*; public class GraphicsTest extends JApplet { public void init() { getContentPane().setBackground(Color.WHITE); } public void paint(Graphics g) { super.paint(g); g.setColor(Color.YELLOW); g.fillOval(100, 100, 50, 50); g.setColor(Color.BLACK); g.setFont(new Font("SansSerif", Font.BOLD, 35)); g.drawString("SLOW", 110, 110); } } What shape will the oval have? a. Oblong, width greater than height b. Oblong, width less than height c. Circle d. Cannot tell ANS: C 39. Look at the following applet code: 1 2 3 4 5 6 7 8 9 10 11 12 import javax.swing.*; import java.awt.*; public class GraphicsTest extends JApplet { public void init() { getContentPane().setBackground(Color.WHITE); } public void paint(Graphics g) { super.paint(g); g.setColor(Color.YELLOW); © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 13 g.fillOval(100, 100, 50, 50); 14 g.setColor(Color.BLACK); 15 g.setFont(new Font("SansSerif", Font.BOLD, 35)); 16 g.drawString("SLOW", 110, 110); 17 } 18 } What will be the coordinates of the center of the oval? a. (100, 100) b. (50, 50) c. (100, 50) d. (125, 125) ANS: D 40. Which of the following can a mouse listener respond to? a. The mouse button is pressed b. The mouse button is clicked c. The mouse cursor enters a component's screen space d. All of the above ANS: D 41. Given the following code, how many times per second will the TimerListener event be generated? Timer timer = new Timer(500, new TimerListener()); a. b. c. d. 5 50 2 500 ANS: C 42. In the following code, what does getDocumentBase() return? play(getDocumentBase(), "mysound.wav"); a. A URL object containing the location of the applet's .class file b. A URL object containing the location of the HTML file that invoked the applet c. The HTML location "mysound.wav" d. The sound file itself ANS: B TRUE/FALSE 1. The browser creates an instance of the applet class automatically. ANS: T 2. HTML describes the content and layout of a Web page, and creates links to other files and Web pages, but does not have sophisticated abilities such as performing math calculations and interacting with the user. Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: T 3. An applet does not have to be on a Web server in order to be executed. ANS: T 4. If you want to make sure that an applet is compatible with all Java-enabled browsers, use Swing components instead of AWT. ANS: F 5. For all Swing components except JApplet and JFrame, you should override the paintComponent method instead of the paint method. ANS: T 6. The delay parameter in the Timer constructor is the amount of time between action events, measured in milliseconds. ANS: T 7. The play method will load and play a sound file once, then release it for garbage collection. The getAudioClip method will load the sound file and may assign the location of the sound file to a variable so it may be invoked many times. ANS: T 8. The Applet class requires that you write a constructor to create an object of the class. ANS: F 9. Some browsers do not directly support the Swing classes of applets. ANS: T 10. Whenever you need a component of any type to be painted, call the paint method. ANS: F 11. The delay parameter in the Timer constructor is the amount of time between action events, measured in microseconds. ANS: F 12. The following getAudioClip() method returns an object that will load the sound file and assign the location of that file to clip which can then be used to call methods that may play the sound file one or more times: Audioclip clip = getAudioClip(getDocumentBase(), "mysound.wav"); ANS: T Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education Chapter 15 MULTIPLE CHOICE 1. A recursive method is: a. a method that accepts no arguments b. a method that contains a static field c. a method that calls itself d. a method that has a loop ANS: C 2. Like a loop, a recursive method must have: a. a counter b. some way to control the number of times it repeats itself c. a return statement d. a predetermined number of times it will execute before terminating ANS: B 3. How many times will the following method call itself if the value 10 is passed as an argument? public static void message(int n) { if (n > 0) { System.out.println("Print this line.\n"); message(n + 1); } } a. 1 b. 9 c. 10 d. An infinite number of times ANS: D 4. The depth of recursion is: a. the number of times that a method calls itself b. the value returned from the last recursive call c. the value that will terminate the recursive calls d. The order in which the method appears on the stack ANS: A 5. Recursion can be a powerful tool for solving: a. basic problems b. repetitive problems c. object-oriented problems d. binary problems Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: B 6. Recursive algorithms are usually less efficient than: a. iterative algorithms b. quantum algorithms c. pseudocode algorithms d. None of the above ANS: A 7. The actions that the JVM must perform any time a method is called are known as: a. Stack depth b. Overhead c. Housekeeping d. Method calls ANS: B 8. To solve a program recursively, you need to identify at least one case in which the problem can be solved without recursion - this is known as the: a. recursive case b. terminal case c. base case d. final case ANS: C 9. Usually, a problem is reduced by making the value of one or more parameters call. a. larger b. smaller c. negative d. equal ANS: B 10. Look at the following pseudocode algorithm: algorithm Test14(int x) if (x < 8) return (2 * x) else return (3 * Test14(x - 8) + 8) end Test14 What is the base case for the algorithm? a. x < 8 b. 2 * x c. 3 * Test14(x - 8) + 8 d. x >= 8 ANS: A with each recursive Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 11. Look at the following pseudocode algorithm: algorithm Test14(int x) if (x < 8) return (2 * x) else return (3 * Test14(x - 8) + 8) end Test14 What is the recursive case for the algorithm? a. x < 8 b. 2 * x c. x != 8 d. x >= 8 ANS: D 12. Look at the following pseudocode algorithm: algorithm Test14(int x) if (x < 8) return (2 * x) else return (3 * Test14(x - 8) + 8) end Test14 What is the depth of Test14(7)? a. 0 b. 1 c. 6 d. 7 ANS: A 13. Look at the following pseudocode algorithm: algorithm Test14(int x) if (x < 8) return (2 * x) else return (3 * Test14(x - 8) + 8) end Test14 What value is returned for Test14(7)? a. 0 b. 7 c. 14 d. -5 ANS: C 14. Look at the following pseudocode algorithm: © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e algorithm Test14(int x) if (x < 8) return (2 * x) else return (3 * Test14(x - 8) + 8) end Test14 What is the depth of Test14(16)? a. 0 b. 1 c. 2 d. 3 ANS: C 15. Look at the following pseudocode algorithm: algorithm Test14(int x) if (x < 8) return (2 * x) else return (3 * Test14(x - 8) + 8) end Test14 What value is returned for Test14(16)? a. 8 b. 16 c. 24 d. 32 ANS: D 16. Look at the following method: public static int Test2(int x, int y) { if ( x < y) { return -5; } else { return (Test2(x - y, y + 5) + 6); } } What is the base case for the method? a. x < y b. -5 c. Test2(x - y, y + 5) + 6 d. +6 ANS: A © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 17. Look at the following method: public static int test2(int x, int y) { if ( x < y) { return -5; } else { return (test2(x - y, y + 5) + 6); } } What is the recursive case for the method? a. x < y b. -5 c. x >= y d. x != y ANS: C 18. Look at the following method: public static int test2(int x, int y) { if ( x < y) { return -5; } else { return (test2(x - y, y + 5) + 6); } } What is returned for test2(10, 20)? a. b. c. d. 6 10 1 -5 ANS: D 19. Look at the following method: public static int test2(int x, int y) { if ( x < y) { return -5; } else { © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e return (test2(x - y, y + 5) + 6); } } What is returned for test2(18,5)? a. b. c. d. 6 -5 7 1 ANS: C 20. Look at the following method: public static int test2(int x, int y) { if ( x < y) { return -5; } else { return (test2(x - y, y + 5) + 6); } } What is the depth of test2(18,5)? a. b. c. d. 0 1 2 3 ANS: C 21. Look at the following pseudocode algorithm: Algorithm Test3(int a, int b) if (a < b) return 5 else if ( a == b) return -5; else return (a + Test3(a - 1, b) end Test3 What is the base case for the algorithm? a. a < b b. a == b c. Both a and b d. Neither a or b ANS: C © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 22. Look at the following pseudocode algorithm: Algorithm Test3(int a, int b) if (a < b) return 5 else if ( a == b) return -5; else return (a + Test3(a - 1, b) end Test3 What is the recursive case for the algorithm? a. a < b b. a == b c. a > b d. None of the above ANS: C 23. This term is used for methods that directly call themselves. a. Direct recursion b. Simple recursion c. Absolute recursion d. Native recursion ANS: A 24. The Towers of Hanoi is: a. a mathematical game b. often used in computer science textbooks c. demonstrates the power of recursion d. All of the above ANS: D 25. This type of method is a method that calls itself. a. Looping b. Circular c. Recursive d. Reoccurring ANS: C 26. Indirect recursion occurs when: a. a loop is used to solve a recursive problem b. a recursive method has no code to stop it from repeating c. a method calls itself d. a method calls itself from another method ANS: D © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education 27. Like , a recursive method must have some way to control the number of times it repeats. a. a loop b. any method c. a class constructor d. an event ANS: A 28. How many times will the following method call itself if the value 10 is passed as the argument? public static void message(int n) { if (n < 0) { System.out.println("Print this line.\n"); message(n + 1); } } a. 0 b. 9 c. 10 d. An infinite number of times ANS: A 29. The number of times that a method calls itself is known as the: a. height of recursion b. depth of recursion c. width of recursion d. length of recursion ANS: B 30. If the base case in a recursive method is never reached: a. the method will call itself only once b. the result will always be off by one c. the method will call itself indefinitely d. the method will never call itself ANS: C 31. The part of a problem that is solved with recursion is known as the: a. terminal case b. final case c. absolute case d. recursive case ANS: D 32. Look at the following pseudocode algorithm: Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e Algorithm gcd(x, y) if (x < y) gcd (y, x) else if (y = 0) return x else return gcd(y, x mod y) end gcd What is the base case for the algorithm gcd? a. x < y b. y == 0 c. x == 0 d. y > x ANS: B 33. Look at the following pseudocode algorithm: Algorithm gcd(x, y) if (x < y) gcd (y, x) else if (y = 0) return x else return gcd(y, x mod y) end gcd What is returned from gcd(60, 24)? a. 60 b. 24 c. 12 d. 66 ANS: C 34. Which of the following problems can be programmed recursively? a. Towers of Hanoi b. Quicksort c. Binary search d. All of the above ANS: D TRUE/FALSE 1. In Java, it is not possible for a method to call itself. ANS: F 2. Unlike a loop, a recursive method does not require code to stop it from repeating. © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: F 3. Any problem that can be solved recursively can also be solved iteratively. ANS: T 4. A problem can be solved recursively if it can be broken down into successive smaller problems that are unique within the overall problem. ANS: F 5. Indirect recursion occurs when a method calls another method that in turn calls the first method. ANS: T 6. Recursive algorithms are usually less efficient than iterative algorithms. ANS: T 7. A problem can be solved recursively if it can be broken down into successive smaller problems that are identical to the overall problem. ANS: T 8. If method A calls method B, which in turn calls method A, it is called indirect recursion. ANS: T Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education Chapter 16 MULTIPLE CHOICE 1. What do most developers prefer to use when developing applications that work with an intensive amount of data? a. Text files b. Binary files c. A database management system d. Java DB ANS: C 2. This is the standard language for working with database management systems. a. SQL b. BASIC c. ADA d. COBOL ANS: A 3. The DBMS works directly with the data, and sends the results of operations: a. back to the application b. along the encrypted data path c. to the unified data component d. back to the Web server ANS: A 4. SQL stands for . a. structured query language b. standard equivalent language c. semiconductor qualified language d. Simple equation library ANS: A 5. The data that is stored in a row is divided into: a. sections b. tables c. bytes d. columns ANS: D 6. The data that is stored in a table is organized in: a. rows b. folders c. pages d. files Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: A 7. If you try to store duplicate data in a primary key column: a. the column is duplicated b. an error will occur c. the duplicate data will have concurrency issues d. The primary key column will not display the duplicate data ANS: B 8. Which of one the following SQL data types would be the best choice for storing financial data? a. INT b. REAL c. DOUBLE d. VARCHAR ANS: C 9. This type of SQL statement is used to retrieve the rows from a table. a. GET b. SELECT c. READ d. RETRIEVE ANS: B 10. Of the following column names, which one is most likely a primary key column? a. Price b. Description c. ItemNumber d. Quantity ANS: C 11. A result set is an object that is somewhat similar to a collection and: a. contains the results of an SQL statement b. allows the program to execute an SQL statement c. predicts the outcome of an SQL statement d. provides rules for how an SQL statement should be executed ANS: A 12. Which of the following shows how a single quote is represented as part of a string in SQL? a. _' b. "'" c. /' d. '' ANS: D 13. Column names in a database are: a. case sensitive © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e b. c. d. similar to Java data types not case sensitive always uppercase letters ANS: C 14. In SQL, the not equal-to operator is: a. != b. NOT c. || d. <> ANS: D 15. What SQL operator can be used to perform a search for a substring? a. STR b. LIKE c. WHERE d. SUB ANS: B 16. In SQL, this character can be used as a wildcard to represent a single character. a. % b. $ c. _ d. * ANS: C 17. What SQL operator can be used to disqualify search criteria in a WHERE clause? a. AND b. NOT c. EXCLUDE d. NOR ANS: B 18. If you wish to sort the results of an SQL query, you can use the a. SORT BY b. ALIGN ROW c. ORDER BY d. ASCEND clause. ANS: C 19. What must you have installed on your system before you can use JDBC to access a database? a. DBMS b. Java c. Both a and b d. Neither a nor b Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e © 2012 Pearson Education ANS: C 20. What does JDBC stand for? a. Java data binary collection b. Java database connectivity c. Java database collection d. Java data basic computation ANS: B 21. To a. b. c. d. what package does the Connection interface belong? java.swing java.awt java.sql java.io ANS: C 22. What string lists the protocol that should be used to access a database, the name of the database, and potentially other items? a. JDBC driver b. Database URL c. JDBC locator d. Database specifier ANS: B 23. Which Statement interface method should be used to execute a SELECT statement? a. executeSQL b. executeStatement c. executeUpdate d. executeQuery ANS: D 24. Which Statement interface method should be used to execute an INSERT statement? a. executeUpdate b. executeStatement c. executeQuery d. executeSQL ANS: A 25. You use this statement in SQL to insert a new row into a table: a. UPDATE b. ADD c. NEW d. INSERT ANS: D Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 26. In SQL, this statement is used to change the contents of an existing row in a table: a. SET ROW b. CHANGE c. UPDATE d. REFRESH ANS: C 27. In SQL, you use this statement to delete one or more rows from a table: a. DELETE b. DROP ROW c. REMOVE d. PURGE ANS: A 28. This SQL statement can be used to create a database table: a. NEW TABLE b. MAKE TABLE c. BUILD TABLE d. CREATE TABLE ANS: D 29. Which SQL statement is used to delete a table from a database? a. REM TABLE b. DEL TABLE c. DROP TABLE d. ERASE TABLE ANS: C 30. What is the default concurrency level of a ResultSet object? a. Public b. Updatable c. Private d. Read-only ANS: D 31. Appending the attribute ;create=true to the database URL: a. creates a new database b. creates a new table c. creates a new row d. creates a new column ANS: A 32. By a. b. c. default, ResultSet objects allows you to move the cursor: backward only vertically forward only © 2012 Pearson Education Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e d. © 2012 Pearson Education horizontally ANS: C 33. What is determined by the following code? resultSet.last(); int numRows = resultSet.getRow(); resultSet.first(); a. b. c. d. the number of rows in the result set the number of columns in the result set the value of the cursor’s current position the sum of all rows in the result set ANS: A 34. What term refers to data that describes other data? a. Pseudo-data b. Micro data c. Abstract data d. Meta data ANS: D 35. What Java class is a Swing component that displays data in a two-dimensional table? a. JTable b. JFrame c. JPanel d. JTable2D ANS: A 36. A column in one table that references a primary key in another table is known as what? a. Secondary key b. Foreign key c. Referential key d. Meta key ANS: B 37. In an entity relationship diagram, the primary keys are denoted with: a. (PK) b. (1) c. (KEY) d. (PRIME) ANS: A 38. A qualified column name takes the following form: a. ColumnName.TableName b. TableName.ColumnName Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e c. d. © 2012 Pearson Education RowName.TableName DatabaseURL.ColumnName ANS: B TRUE/FALSE 1. Although SQL is a language, you don’t use it to write applications. ANS: T 2. The columns in a table are assigned SQL data types. ANS: T 3. In SQL, the equal to operator is ==, which is the same as Java. ANS: F 4. SQL does not provide functions for performing calculations. ANS: F 5. System designers commonly use UML diagrams to show the relationships between database tables. ANS: F 6. No two rows in a table can have the same value in the primary key column ANS: T 7. In SQL, the REFERENCES qualifier ensures referential integrity between tables. ANS: T 8. SQL statements that are stored in the DBMS are called resident queries. ANS: F 9. In a transaction, all updates to database must be successfully executed. ANS: T 10. The term commit refers to undoing changes to a database. ANS: F