Introduction to Java Programming and Data Structures, 12th edition Y Daniel Liang Test Bank

Page 1

Introduction to Java Programming and Data Structures, 12th edition By Y Daniel Liang

Email: richard@qwconsultancy.com


Chapter 1 Introduction to Computers, Programs, and Java Section 1.2 What is a Computer? 1. is the physical aspect of the computer that can be seen. a. Hardware b. Software c. Operating system d. Application program Key:a See the first paragraph in Section 1.2. # Section 1.2.1 What is a Computer? 2. is the brain of a computer. a. Hardware b. CPU c. Memory d. Disk Key:b See the first paragraph in Section 1.2.1. # 3. The speed of the CPU may be measured in . a. megabytes b. gigabytes c. megahertz d. gigahertz Key:cd See the third paragraph in Section 1.2.1. 1 megahertz equals 1 million pulses per second and 1 gigahertz is 1000 megahertz. # Section 1.2.2 Bits and Bytes 4. Why do computers use zeros and ones? a. because combinations of zeros and ones can represent any numbers and characters. b. because digital devices have two stable states and it is natural to use one state for 0 and the other for 1. c. because binary numbers are simplest. d. because binary numbers are the bases upon which all other number systems are built. Key:b See the second paragraph in Section 1.2.2. # 5. One byte has bits. a. 4 b. 8 c. 12 d. 16 Key:b See the thrid paragraph in Section 1.2.2. # 5. One gigabyte is approximately bytes. a. 1 million b. 10 million c. 1 billion d. 1 trillion Key:c See the fifth paragraph in Section 1.2.2. ..


# Section 1.2.3 Memory 6. A program and its data must be moved into the computer's a. memory b. hard disk c. CPU d. CD-ROM Key:a See the first paragraph in Section 1.2.3.

before they can be executed by the CPU.

# Section 1.2.4 Storage Devices 6. A computer's is volatile; that is, any information stored in it is lost when the system's power is turned off. a. memory b. hard disk c. flash stick d. CD-ROM Key:a See the first paragraph in Section 1.2.4. # 6. Which of the following are storage devices? a. portable disk b. hard disk c. flash stick d. CD-ROM Key:abcd See the second paragraph in Section 1.2.4. # Section 1.2.5 Input and Output Devices 7. The specifies the number of pixels in horizontal and vertical dimensions of the display device. a. screen resolution b. pixel c. dot pitch d. monitor Key:a See the third last paragraph in Section 1.2.5. # Section 1.2.6 Communications Devices 7. is a device to connect a computer to a local area network (LAN). a. Regular modem b. DSL c. Cable modem d. NIC Key:d See the bullet items in Section 1.2.6. # Section 1.3 Program Languages 8. are instructions to the computer. a. Hardware b. Software c. Programs d. Keyboards Key:bc See the Key Point in Section 1.3. # ..


9. Computer can execute the code in a. machine language b. assembly language c. high-level language d. none of the above Key:a See the first paragraph in Section 1.3.1.

.

# 10. translates high-level language program into machine language program. a. An assembler b. A compiler c. CPU d. The operating system Key:b See the first paragraph after Table 1.1 in Section 1.3.3. # Section 1.4 Operating Systems 11. is an operating system. a. Java b. C++ c. Windows d. Visual Basic e. Ada Key:c See the first paragraph in Section 1.4. # 12. is a program that runs on a computer to manage and control a computer's activities. a. Operating system b. Java c. Modem d. Interpreter e. Compiler Key:a See the first paragraph in Section 1.4. # Section 1.5 Java, World Wide Web, and Beyond 14. Due to security reasons, Java cannot run from a Web browser in the new version of Java. a. applications b. applets c. servlets d. Micro Edition programs Key:b See the last paragraph in Section 1.5. # 15. a. Java b. C++ c. C d. C# e. Python

is not an object-oriented programming language.

Key:c See Table 1.1 in Section 1.3.1. # 16.

is interpreted. ..


a. Java b. C++ c. C d. Ada e. Pascal Key:a See the second paragraph in Section 1.5. # 17. a. Java b. C++ c. C d. Ada e. Pascal

is architecture-neutral.

Key:a See the second paragraph in Section 1.5. # Section 1.6 The Java Language Specification, API, JDK, and IDE 18. is a technical definition of the language that includes the syntax and semantics of the Java programming language. a. Java language specification b. Java API c. Java JDK d. Java IDE Key:a See the last paragraph in Section 1.6. # 19. contains predefined classes and interfaces for developing Java programs. a. Java language specification b. Java API c. Java JDK d. Java IDE Key:b See the last paragraph in Section 1.6. # 20. consists of a set of separate programs for developing and testing Java programs, each of which is invoked from a command line. a. Java language specification b. Java API c. Java JDK d. Java IDE Key:c See the last paragraph in Section 1.6. # 21.

provides an integrated development environment (IDE) for rapidly developing Java programs. Editing,

compiling, building, debugging, and online help are integrated in one graphical user interface. a. Java language specification b. Java API c. Java JDK d. Java IDE Key:d See the last paragraph in Section 1.6. # ..


Section 1.7 A Simple Java Program

..


22. The main method header is written as: a. public static void main(string[] args) b. public static void Main(String[] args) c. public static void main(String[] args) d. public static main(String[] args) e. public void main(String[] args) Key:c In A, string should be spelled String with S in uppercase. In B, Main should be spelled main in lowercase. In D, the keyword void is missing. in D, the keyword static is missing. C is correct. # 23. Which of the following statements is correct? a. Every line in a program must end with a semicolon. b. Every statement in a program must end with a semicolon. c. Every comment line must end with a semicolon. d. Every method must end with a semicolon. e. Every class must end with a semicolon. Key:b Only statements need to be end with a semicolon. # 24. Which of the following statements is correct to display Welcome to Java on the console? a. System.out.println('Welcome to Java'); b. System.out.println("Welcome to Java"); c. System.println('Welcome to Java'); d. System.out.println('Welcome to Java"); e. System.out.println("Welcome to Java'); Key:b In A, a string must be enclosed in double quotation marks. In C, a string must be enclosed in double quotation marks and also the .out is missing. In D, a string must be enclosed in double quotation marks on both sides. In E, a string must be enclosed in double quotation marks. B is correct. # Section 1.8 Creating, Compiling, and Executing a Java Program 25. The JDK command to just compile a class (not run) in the file Test.java is a. java Test b. java Test.java c. javac Test.java d. javac Test e. JAVAC Test.java Key:c In A, java is the command to run a program. In B, java is the command to run a program. In D, java is the command to run a program. In E, The command is case sensitive. C is correct. # 26. Which JDK command is correct to run a Java application in ByteCode.class? a. java ByteCode b. java ByteCode.class c. javac ByteCode.java d. javac ByteCode e. JAVAC ByteCode Key:a A is correct. In B, to compile, use only the class name, not including the extension. In C, javac is the command to compile a class, not to run a class. In D, javac is the command to compile a class, not to run a class. In E, the command is case sensitive and javac is the command to compile a class, not to run a class. # 27. Java compiler translates Java source code into a. Java bytecode ..

.


b. machine code c. assembly code d. another high-level language code Key:a Java bytecode is the end result of compiling a Java source file. Java bytecode is machine-indepedent and can be run on any platform. # 28. is a software that interprets Java bytecode. a. Java virtual machine b. Java compiler c. Java debugger d. Java API Key:a Java virtual machine is a software that runs Java bytecode. Java compiler compiles Java source code into Java bytecode. # 29. Suppose you define a Java class as follows, the source code should be stored in a file named

.

public class Test { } a. Test.class b. Test.doc c. Test.txt d. Test.java e. Any name with extension .java Key:d You have to name the class as ClassName.java. Here the class name is Test. # 30. The extension name of a Java bytecode file is a. .java b. .obj c. .class d. .exe Key:c .java is the Java source code file name and .class is the Java bytecode file name. # 31. The extension name of a Java source code file is a. .java b. .obj c. .class d. .exe Key:a .java is the Java source code file name and .class is the Java bytecode file name. # 32. Which of the following lines is not a Java comment? a. /** comments */ b. // comments c. -- comments d. /* comments */ e. ** comments ** Key:ce The text that begins with // in a line is known as a line comment and the text that is enclosed between /* and */ is known as a paragraph comment. ..


# 33. Which of the following are the reserved words? a. public b. static c. void d. class Key:abcd These are all reserved words with specific meaning to the compiler. # 34. Every statement in Java ends with . a. a semicolon (;) b. a comma (,) c. a period (.) d. an asterisk (*) Key:a You have to tell the compiler where a statement ends using a semicolon. # 35. A block is enclosed inside . a. parentheses b. braces c. brackets d. quotes Key:b A block is enclosed inside a pair of openning and closing braces. # Section 1.9 Programming Style and Documentation 36. Programming style is important, because . a. a program may not compile if it has a bad style b. good programming style can make a program run faster c. good programming style makes a program more readable d. good programming style helps reduce programming errors Key:cd Bad style is a readability issue. The code will still compile. Programming style is a readability issue and it does not effect the performance of the code. D and C are correct. # 37.

Analyze the following code.

I: public class Test { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } II: public class Test { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } a. Both I and II can compile and run and display Welcome to Java, but the code in II has a better style than I. b. Only the code in I can compile and run and display Welcome to Java. c. Only the code in II can compile and run and display Welcome to Java. d. Both I and II can compile and run and display Welcome to Java, but the code in I has a better style than II. Key:d Both I and II are the same except the format is different. Format is a readability issue only. ..


# 38. Which of the following code has the best style? I: public class Test { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } II: public class Test { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } III: public class Test { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } IV: public class Test { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } a. I b. II c. III d. IV Key:d All the code will run fine, but not formatted correctly. Only the code in IV is formatted correctly. # Section 1.10 Programming Errors 39. If a program compiles fine, but it produces incorrect result, then the program suffers . a. a compile error b. a runtime error c. a logic error Key:c If a program has a compile error, it will not run. When a program has a runtime error, it terminates abnormally. C is correct. # 40. If you forget to put a closing quotation mark on a string, what kind of error will be raised? a. a compile error b. a runtime error c. a logic error Key:a This is a syntax error, which will be detected by the compiler.

..


Chapter 2 Elementary Programming Section 2.2 Writing a Simple Program 1. is the code with natural language mixed with Java code. a. Java program b. A Java statement c. Pseudocode d. A flowchart diagram key:c See the second paragraph in this section. # 2.

What is the exact output of the following code?

double area = 3.5; System.out.print("area"); System.out.print(area); a. 3.53.5 b. 3.5 3.5 c. area3.5 d. area 3.5 Key:c The first print statement prints a string followed by the second print statement that prints a number. # Section 2.3 Reading Input from the Console 3. Suppose a Scanner object is created as follows, what method do you use to read a real number? Scanner input = new Scanner(System.in); a. input.nextDouble(); b. input.nextdouble(); c. input.double(); d. input.Double(); Key:a The correct method to read a real number is nextDouble(). # 4. The following code fragment reads in two numbers. What is the incorrect way to enter these two numbers? Scanner input = new Scanner(System.in); int i = input.nextInt(); double d = input.nextDouble(); a. Enter an integer, a space, a double value, and then the Enter key. b. Enter an integer, two spaces, a double value, and then the Enter key. c. Enter an integer, an Enter key, a double value, and then the Enter key. d. Enter a numeric value with a decimal point, a space, an integer, and then the Enter key. Key:d See Listing 2.3. # 5. If you enter 1 2 3, when you run this program, what will be the output? import java.util.Scanner; ..


public class Test1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter three numbers: "); double number1 = input.nextDouble(); double number2 = input.nextDouble(); double number3 = input.nextDouble(); // Compute average double average = (number1 + number2 + number3) / 3; // Display result System.out.println(average); } } a. 1.0 b. 2.0 c. 3.0 d. 4.0 Key:b (1.0 + 2.0 + 3.0) / 3 is 2.0 # Section 2.4 Identifiers 6. Every letter in a Java keyword is in lowercase? a. true b. false Key:a It is true that the keywords in Java are in lowercase. For example, public, static, int, double, and void are the keywords. # 7. Which of the following is a valid identifier? a. $343 b. class c. 9X d. 8+9 e. radius Key:ae class is a keyword, which cannot be used as an identifier. Identifiers cannot start with a number. # Section 2.5 Variables 8. Which of the following are correct names for variables according to Java naming conventions? a. radius b. Radius c. RADIUS d. findArea e. FindArea Key:ad A single-word variable is in lowercase. In a multiple-word variable, the words are concatenated with the first word in lowercase and the first letter of each subsequent word in uppercase. # 9. a. b.

Which of the following are correct ways to declare variables? int length; int width; int length, width; ..


c. int length; width; d. int length, int width; Key:ab Note that a semicolon ends a statement. In B, length and width are both declared as int. # Section 2.6 Assignment Statements and Assignment Expressions 10. is the Java assignment operator. a. == b. := c. = d. =: Key:c See the first paragraph. # 11. To assign a value 1 to variable x, you write a. 1 = x; b. x = 1; c. x := 1; d. 1 := x; e. x == 1; Key:b See the first paragraph. # 12. Which of the following assignment statements is incorrect? a. i = j = k = 1; b. i = 1; j = 1; k = 1; c. i = 1 = j = 1 = k = 1; d. i == j == k == 1; Key:cd Read toward the end of the section. # Section 2.7 Named Constants 13. To declare a constant MAX_LENGTH inside a method with value 99.98, you write a. final MAX_LENGTH = 99.98; b. final float MAX_LENGTH = 99.98; c. double MAX_LENGTH = 99.98; d. final double MAX_LENGTH = 99.98; Key:d See the first paragraph. # 14. Which of the following is a constant, according to Java naming conventions? a. MAX_VALUE b. Test c. read d. ReadInt e. COUNT Key:ae All letters in a constant are in uppercase. In a multiple-word constant, the words are connected using underscores. # 15. To improve readability and maintainability, you should declare a such as 3.14159. a. variable b. method ..

for PI instead of using literal values


c. constant d. class Key:c A constant gives a literal a descriptive name and makes the code more readable. # Section 2.8 Naming Conventions 16. According to Java naming convention, which of the following names can be variables? a. FindArea b. findArea c. totalLength d. TOTAL_LENGTH e. class Key:bc The first word in a variable is in lowercase. So B and C are correct. # Section 2.9 Numeric Data Types and Operations 17. Which of these data types requires the most amount of memory? a. long b. int c. short d. byte Key:a long takes 8 bytes. int 4 bytes. short 2 bytes. byte 1 byte. # Section 2.9.2 Numeric Operators 19. What is the result of 45 / 4? a. 10 b. 11 c. 11.25 d. 12 Key:b The result of the division is the quotient and the fractional part is truncated. So 45 / 4 is 11. 3 / 2 is 1, and so on. # 20. Which of the following expression results in a value 1? a. 2 % 1 b. 15 % 4 c. 25 % 5 d. 37 % 6 Key:d 2 % 1 is 0, 15 % 4 is 3, 25 % 5 is 0, and 37 % 6 is 1 # 21. 25 % 1 is a. 1 b. 2 c. 3 d. 4 e. 0 Key:e The reminder of any integer by 1 is 0. # 22. -25 % 5 is a. 1 b. 2 c. 3 ..


d. 4 e. 0 Key:e # 23. 24 % 5 is a. 1 b. 2 c. 3 d. 4 e. 0 Key:d # 24. -24 % 5 is a. -1 b. -2 c. -3 d. -4 e. 0 Key:d # 25. -24 % -5 is a. 3 b. -3 c. 4 d. -4 e. 0 Key:d # Section 2.9.3 Exponent Operations 26. How do you write 2.5 ^ 3.1 in Java? a. 2.5 * 3.1 b. Math.pow(2.5, 3.1) c. Math.pow(3.1, 2.5) d. 2.5 ** 3.1 e. 3.1 ** 2.5 Key:b See the first paragraph of the section. # 27. Math.pow(2, 3) returns a. 9 b. 8 c. 9.0 d. 8.0 Key:d It returns a double value 8.0. # 28. Math.pow(4, 1 / 2) returns a. 2 b. 2.0 c. 0 ..

.

.


d. 1.0 e. 1 Key:d Note that 1 / 2 is 0. # 29. Math.pow(4, 1.0 / 2) returns . a. 2 b. 2.0 c. 0 d. 1.0 e. 1 Key:b Note that the pow method returns a double value, not an integer. # 30. The method returns a raised to the power of b. a. Math.power(a, b) b. Math.exponent(a, b) c. Math.pow(a, b) d. Math.pow(b, a) Key:c See line 1 in Section 2.9.3. # Section 2.10 Numeric Literals 32. Analyze the following code. public class Test { public static void main(String[] args) { int month = 09; System.out.println("month is " + month); } } a. The program displays month is 09. b. The program displays month is 9. c. The program displays month is 9.0. d. The program has a syntax error, because 09 is an incorrect literal value. Key:d Any numeric literal with the prefix 0 is an octal value. But 9 is not an octal digit. An octal digit is 0, 1, 2, 3, 4, 5, 6, or 7. # 33. Which of the following is incorrect? a. 1_2 b. 0.4_56 c. 1_200_229 d. _4544 Key:d You can use the digit separator _ for integers or floating point numbers. The separator must be placed between the digits. # 34. Which of the following are the same as 1545.534? a. 1.545534e+3 b. 0.1545534e+4 c. 1545534.0e-3 d. 154553.4e-2 Key:abcd See Section 2.10.3. ..


# 31. To declare an int variable number with initial value 2, you write a. int number = 2L; b. int number = 2l; c. int number = 2; d. int number = 2.0; Key:c See Section 2.10.1. # 35. Which of the following is incorrect? a. int x = 9; b. long x = 9; c. float x = 1.0; d. double x = 1.0; Key:c Section 2.10.2. # Section 2.11 Prototyping Using JShell 31. The command to exit JShell is a. \quit b. \exit c. /quit d. /exit Key:d Read toward the end of this section.

.

# 31. The command to view all variables in JShell is a. \vars b. \var c. /vars d. /var Key:c See Figure 2.5.

.

# Section 2.12 Evaluating Expressions and Operator Precedence 36. The expression 4 + 20 / (3 - 1) * 2 is evaluated to a. 4 b. 20 c. 24 d. 9 e. 25 Key:c See the second paragraph in this section. # Section 2.13 Case Study: Displaying the Current Time 37. The System.currentTimeMillis() returns . a. the current time. b. the current time in milliseconds. c. the current time in milliseconds since midnight. d. the current time in milliseconds since midnight, January 1, 1970. e. the current time in milliseconds since midnight, January 1, 1970 GMT (the Unix time). Key:e See Listing 2.7.

..


# 38. To obtain the current second, use . a. System.currentTimeMillis() % 3600 b. System.currentTimeMillis() % 60 c. System.currentTimeMillis() / 1000 % 60 d. System.currentTimeMillis() / 1000 / 60 % 60 e. System.currentTimeMillis() / 1000 / 60 / 60 % 24 Key:c See Listing 2.7. # 39. To obtain the current minute, use . a. System.currentTimeMillis() % 3600 b. System.currentTimeMillis() % 60 c. System.currentTimeMillis() / 1000 % 60 d. System.currentTimeMillis() / 1000 / 60 % 60 e. System.currentTimeMillis() / 1000 / 60 / 60 % 24 Key:d See Listing 2.7. # 40. To obtain the current hour in UTC, use . a. System.currentTimeMillis() % 3600 b. System.currentTimeMillis() % 60 c. System.currentTimeMillis() / 1000 % 60 d. System.currentTimeMillis() / 1000 / 60 % 60 e. System.currentTimeMillis() / 1000 / 60 / 60 % 24 Key:e See Listing 2.7. # Section 2.14 Augmented Assignment Operators 43. Suppose x is 1. What is x after x += 2? a. 0 b. 1 c. 2 d. 3 e. 4 Key:d See Table 2.4 # 44. Suppose x is 1. What is x after x -= 1? a. 0 b. 1 c. 2 d. -1 e. -2 Key:a See Table 2.4 # 45.

What is x after the following statements?

int x = 2; int y = 1; x *= y + 1; a. x is 1. ..


b. x is 2. c. x is 3. d. x is 4. Key:d (y + 1) is executed first and its result is multiplied with x and assigned to x. # 46.

What is x after the following statements?

int x = 1; x *= x + 1; a. x is 1. b. x is 2. c. x is 3. d. x is 4. Key:b See Table 2.4. # 47.

Which of the following statements are the same?

(A) x -= x + 4 (B) x = x + 4 - x (C) x = x - (x + 4) a. (A) and (B) are the same b. (A) and (C) are the same c. (B) and (C) are the same d. (A), (B), and (C) are the same Key:b See Table 2.4. # 41. To add a value 1 to variable x, you write a. 1 + x = x; b. x += 1; c. x := 1; d. x = x + 1; e. x = 1 + x; Key:bde See Table 2.4. # 42. To add number to sum, you write (Note: Java is case-sensitive) a. number += sum; b. number = sum + number; c. sum = Number + sum; d. sum += number; e. sum = sum + number; Key:de See Table 2.4. # Section 2.15 Increment and Decrement Operators 49. What is i printed? public class Test { public static void main(String[] args) { ..


int j = 0; int i = ++j + j * 5; System.out.println("What is i? " + i); } } a. 0 b. 1 c. 5 d. 6 Key:d Operands are evaluated from left to right in Java. The left-hand operand of a binary operator is evaluated before any part of the right-hand operand is evaluated. This rule takes precedence over any other rules that govern expressions. Therefore, ++j is evaluated first, and j is now 1. Then j * 5 is evaluated, returns 5. So, i is 6. # 50. What is i printed in the following code? public class Test { public static void main(String[] args) { int j = 0; int i = j++ + j * 5; System.out.println("What is i? " + i); } } a. 0 b. 1 c. 5 d. 6 Key:c Operands are evaluated from left to right in Java. The left-hand operand of a binary operator is evaluated before any part of the right-hand operand is evaluated. This rule takes precedence over any other rules that govern expressions. Therefore, j++ is evaluated first. j is now 1. Since j++ is postincrement, the old value of j is returned for j++. So j++ + j * 5 equals 0 + 1 * 5. So, the result is 5. # 51. What is y displayed in the following code? public class Test { public static void main(String[] args) { int x = 1; int y = x++ + x; System.out.println("y is " + y); } } a. y is 1. b. y is 2. c. y is 3. d. y is 4. Key:c When evaluating x++ + x, x++ is evaluated first, which does two things: 1. returns 1 since it is post-increment. x becomes 2. Therefore y is 1 + 2. # 52. What is y displayed?

..


public class Test { public static void main(String[] args) { int x = 1; int y = x + x++; System.out.println("y is " + y); } } a. y is 1. b. y is 2. c. y is 3. d. y is 4. Key:b When evaluating x + x++, x is evaluated first, which is 1. X++ returns 1 since it is post-increment and 2. Therefore y is 1 + 1. # 48.

Are the following four statements equivalent?

number += 1; number = number + 1; number++; ++number; a. Yes b. No Key:a See Table 2.5. # Section 2.16 Numeric Type Conversions 53. To assign a double variable d to a float variable x, you write a. x = (long)d b. x = (int)d; c. x = d; d. x = (float)d; Key:d See the second paragraph in this section. # 54. Which of the following expressions will yield 0.5? a. 1 / 2 b. 1.0 / 2 c. (double) (1 / 2) d. (double) 1 / 2 e. 1 / 2.0 Key:bde 1 / 2 is an integer division, which results in 0. # 55. What is the output of the following code: double x = 5.5; int y = (int)x; System.out.println("x is " + x + " and y is " + y); a. x is 5 and y is 6 b. x is 6.0 and y is 6.0 c. x is 6 and y is 6 d. x is 5.5 and y is 5 e. x is 5.5 and y is 5.0 ..


Key:d The value is x is not changed after the casting. # 56. Which of the following assignment statements is illegal? a. float f = -34; b. int t = 23; c. short s = 10; d. int t = 4.5; Key:d See the second paragraph in this section. # 57. What is the value of (double)5/2? a. 2 b. 2.5 c. 3 d. 2.0 e. 3.0 Key:b See the second code box in this section. # 58. What is the value of (double)(5/2)? a. 2 b. 2.5 c. 3 d. 2.0 e. 3.0 Key:d See the second paragraph in this section. # 59. Which of the following expression results in 45.37? a. (int)(45.378 * 100) / 100 b. (int)(45.378 * 100) / 100.0 c. (int)(45.378 * 100 / 100) d. (int)(45.378) * 100 / 100.0 Key:b See Listing 2.8. # 60. The expression (int)(76.0252175 * 100) / 100 evaluates to a. 76.02 b. 76 c. 76.0252175 d. 76.03 Key:b In order to obtain 76.02, you have divide 100.0.

.

# 61. If you attempt to add an int, a byte, a long, and a double, the result will be a(n) a. byte b. int c. long d. double Key:d See the second paragraph in this section. # Section 2.17 Software Life Cycle ..

value.


62. is a formal process that seeks to understand the problem and document in detail what the software system needs to do. a. Requirements specification b. Analysis c. Design d. Implementation e. Testing Key:a See the second paragraph in this section. # 63. seeks to analyze the data flow and to identify the system’s input and output. When you do analysis, it helps to identify what the output is first, and then figure out what input data you need in order to produce the output. a. Requirements specification b. Analysis c. Design d. Implementation e. Testing Key:b See the third paragraph in this section. # Section 2.18 Case Study: Counting Monetary 62. Suppose int x = 3264, what is the output of the following code? int y = x % 10; x = x / 10; System.out.println("x is " + x + " and y is " + y); a. x is 3264 and y is 326.4 b. x is 326 and y is 326 c. x is 326 and y is 4 d. x is 3264 and y is 4 e. x is 4 and y is 326 Key:c 3264 / 10 is 326 and 3264 % 10 is 4. # Section 2.19 Common Errors and Pitfalls 64. Analyze the following code: public class Test { public static void main(String[] args) { int n = 10000 * 10000 * 10000; System.out.println("n is " + n); } } a. The program displays n is 1000000000000. b. The result of 10000 * 10000 * 10000 is too large to be stored in an int variable n. This causes an overflow and the program is aborted. c. The result of 10000 * 10000 * 10000 is too large to be stored in an int variable n. This causes an overflow and the program continues to execute because Java does not report errors on overflow. d. The result of 10000 * 10000 * 10000 is too large to be stored in an int variable n. This causes an underflow and the program is aborted. e. The result of 10000 * 10000 * 10000 is too large to be stored in an int variable n. This causes an underflow and the program continues to execute because Java does not report errors on underflow. ..


Key:c See Common Error 2: Integer Overflow. # 18. When assigning a literal to a variable of the byte type, if the literal is too large to be stored as a byte value, it . a. causes overflow b. causes underflow c. causes no error d. cannot happen in Java e. receives a compile error Key:e For example, byte b = 23232 will cause a compile error.

..


Chapter 3 Selections Section 3.2 boolean Data Type 1. The "less than or equal to" comparison operator in Java is . a. < b. <= c. =< d. << e. != Key:b It reads less than or equal to. So write the less than symbol before the equal sign. Note that there is no space separating the two symbols. # 2. The equal comparison operator in Java is . a. <> b. != c. == d. ^= Key:c Note that there is no space separating the double equal signs. # 3. What is 1 + 1 + 1 + 1 + 1 == 5? a. true b. false c. There is no guarantee that 1 + 1 + 1 + 1 + 1 == 5 is true. Key:a These are all integers. Integer arithmetic is accurate. # 4. What is 1 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1 == 0.5? a. true b. false c. There is no guarantee that 1 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1 == 0.5 is true. Key:c This epression involves floating-point number. Floating-point numbers are approximated. The correct answer is C. # 5. In Java, the word true is . a. a Java keyword b. a Boolean literal c. same as value 1 d. same as value 0 Key:b true is a Boolean literal just like integer literal 10. # Section 3.3 if Statements 6. Which of the following code displays the area of a circle if the radius is positive? a. if (radius != 0) System.out.println(radius * radius * 3.14159); b. if (radius >= 0) System.out.println(radius * radius * 3.14159); c. if (radius > 0) System.out.println(radius * radius * 3.14159); d. if (radius <= 0) System.out.println(radius * radius * 3.14159); key:c Positive means > 0. # ..


7. What is the output of the following code? int x = 0; if (x < 4) { x = x + 1; } System.out.println("x is " + x); a. x is 0 b. x is 1 c. x is 2 d. x is 3 e. x is 4 Key:b Since x is 0 before the if statement, x < 4 is true, x becomes 1 after the statement x = x + 1. The correct answer is B. # Section 3.4 Two-Way if-else Statements 8. Suppose income is 4001, what is the output of the following code? if (income > 3000) { System.out.println("Income is greater than 3000"); } else if (income > 4000) { System.out.println("Income is greater than 4000"); } a. no output b. Income is greater than 3000 c. Income is greater than 3000 followed by Income is greater than 4000 d. Income is greater than 4000 e. Income is greater than 4000 followed by Income is greater than 3000 Key:b Since income is 4001, the condition (income > 3000) is true. So statement for the true case is executed. # Section 3.5 Nested if and Multi-Way if-else Statements 9. The following code displays . double temperature = 50; if (temperature >= 100) System.out.println("too hot"); else if (temperature <= 40) System.out.println("too cold"); else System.out.println("just right"); a. too hot b. too cold c. just right d. too hot too cold just right Key:c The statement first test if (temperature >= 100). It is false. Then it tests if (temperature <= 4). It is false. So, it falls to the last else clause. The correct answer is C. # ..


Section 3.6 Common Errors and Pitfalls 10. Suppose x = 1, y = -1, and z = 1. What is the output of the following statement? (Please indent the statement correctly first.) if (x > 0) if (y > 0) System.out.println("x > 0 and y > 0"); else if (z > 0) System.out.println("x < 0 and z > 0"); a. x > 0 and y > 0; b. x < 0 and z > 0; c. x < 0 and z < 0; d. no output. Key:b You may copy the code to an IDE such as NetBeans or Eclipse and reformat it to see how it is correctly indented. The else clause matches the most recent if clause. So, it actually displays x < 0 and z > 0. # 11.

Analyze the following code:

boolean even = false; if (even = true) { System.out.println("It is even"); } a. The program has a compile error. b. The program has a runtime error. c. The program runs fine, but displays nothing. d. The program runs fine and displays It is even. Key:d It is a common mistake to use the = operator in the condition test. What happens is that true is assigned to even when you write even = true. So even is true. The program compiles and runs fine and displays "It is even". # 12. Suppose isPrime is a boolean variable, which of the following is the correct and best statement for testing if isPrime is true? a. if (isPrime = true) b. if (isPrime == true) c. if (isPrime) d. if (!isPrime = false) e. if (!isPrime == false) Key:c A and D are incorrect. B, C, and E are correct. But C is the simplest and thus the best. # 13. Analyze the following code. boolean even = false; if (even) { System.out.println("It is even!"); } a. The code displays It is even! b. The code displays nothing. c. The code is wrong. You should replace if (even) with if (even == true). d. The code is wrong. You should replace if (even) with if (even = true). Key:b Since even is false, the if statement body is not executed. So, the correct answer is B.

..


# 14.

Analyze the following code:

Code 1: int number = 45; boolean even; if (number % 2 == 0) even = true; else even = false; Code 2: int number = 45; boolean even = (number % 2 == 0); a. Code 1 has compile errors. b. Code 2 has compile errors. c. Both Code 1 and Code 2 have compile errors. d. Both Code 1 and Code 2 are correct, but Code 2 is better. Key:d Both Code 1 and Code 2 are correct. Clearly Code 2 is shorter and better. # Section 3.7 Generating Random Numbers 15. Which of the following is a possible output from invoking Math.random()? a. 3.43 b. 0.5 c. 0.0 d. 1.0 Key:bc Math.random() returns a real value between 0.0 and 1.0, excluding 1.0. # 16. What is the output from System.out.println((int)Math.random() * 4)? a. 0 b. 1 c. 2 d. 3 e. 4 Key:a Casting is performed before the * operator in (int)Math.random() * 4. So, it returns 0. # 17. What is the possible output from System.out.println((int)(Math.random() * 4))? a. 0 b. 1 c. 2 d. 3 e. 4 Key:abcd Math.random() returns a real value between 0.0 and 1.0, excluding 1.0. Math.random() * 4 yields a real value between 0.0 and 4.0, excluding 4.0. After casting, the resulting integer may be 0, 1, 2, or 3. # Section 3.8 Case Study: Computing Body Mass Index 18. Suppose you write the code to display "Cannot get a driver's license" if age is less than 16 and "Can get a driver's ..


license" if age is greater than or equal to 16. Which of the following code is correct? I: if (age < 16) System.out.println("Cannot get a driver's license"); if (age >= 16) System.out.println("Can get a driver's license"); II: if (age < 16) System.out.println("Cannot get a driver's license"); else System.out.println("Can get a driver's license"); III: if (age < 16) System.out.println("Cannot get a driver's license"); else if (age >= 16) System.out.println("Can get a driver's license"); IV: if (age < 16) System.out.println("Cannot get a driver's license"); else if (age > 16) System.out.println("Can get a driver's license"); else if (age == 16) System.out.println("Can get a driver's license"); a. I b. II c. III d. IV Key:abcd All the statements are correct. II is the best. # 19. Suppose you write the code to display "Cannot get a driver's license" if age is less than 16 and "Can get a driver's license" if age is greater than or equal to 16. Which of the following code is the best? I: if (age < 16) System.out.println("Cannot get a driver's license"); if (age >= 16) System.out.println("Can get a driver's license"); II: if (age < 16) System.out.println("Cannot get a driver's license"); else System.out.println("Can get a driver's license"); III: if (age < 16) System.out.println("Cannot get a driver's license"); else if (age >= 16) ..


System.out.println("Can get a driver's license"); IV: if (age < 16) System.out.println("Cannot get a driver's license"); else if (age > 16) System.out.println("Can get a driver's license"); else if (age == 16) System.out.println("Can get a driver's license"); a. I b. II c. III d. IV Key:b All the statements are correct. II is the best. # Section 3.9 Case Study: Computing Taxes 20. The method immediately terminates the program. a. System.terminate(0); b. System.halt(0); c. System.exit(0); d. System.quit(0); e. System.stop(0); Key:c System.exit(0) method can be used to terminate a program. # Section 3.10 Logical Operators 21. Which of the Boolean expressions below is incorrect? a. (true) && (3 => 4) b. !(x > 0) && (x > 0) c. (x > 0) || (x < 0) d. (x != 0) || (x = 0) e. (-10 < x < 0) Key:ade a: (3 => 4) should be (3 >= 4), d: (x = 0) should be (x == 0), and e: should be (-10 < x) && (x < 0) # 22. Which of the following is the correct expression that evaluates to true if the number x is between 1 and 100 or the number is negative? a. 1 < x < 100 && x < 0 b. ((x < 100) && (x > 1)) || (x < 0) c. ((x < 100) && (x > 1)) && (x < 0) d. (1 > x > 100) || (x < 0) Key:b A and D have syntax errors. B uses || for the OR operator. The correct answer is B. # 23. Assume x = 4 and y = 5, which of the following is true? a. x < 5 && y < 5 b. x < 5 || y < 5 c. x > 5 && y > 5 d. x > 5 || y > 5 Key:b x < 5 is true, but y < 5 is false. So A is false. B is true. C and D are both false, because x > 5 is false and y > 5 is false. The correct answer is B.

..


# 24. Assume x = 4, which of the following is true? a. !(x == 4) b. x != 4 c. x == 5 d. x != 5 Key:d D is true. All others are false. # 25. Assume x = 4 and y = 5, which of the following is true? a. !(x == 4) ^ y != 5 b. x != 4 ^ y == 5 c. x == 5 ^ y == 4 d. x != 5 ^ y != 4 Key:b x != 4 is false and y == 5 is true. So B is correct. # Section 3.11 Determining Leap Year 26. Given |x| <= 4, which of the following is true? a. x <= 4 && x >= 4 b. x <= 4 && x > -4 c. x <= 4 && x >= -4 d. x <= 4 || x >= -4 Key:c |x| <= 4 means -4 <= x <= 4. That is x <= 4 and x >= -4. |x| <= 4 is true for x being -4, -3, 0, 2, 4, etc. So the correct answer is C. # 27. Given |x| >= 4, which of the following is true? a. x >= 4 && x <= -4 b. x >= 4 || x <= -4 c. x >= 4 && x < -4 d. x >= 4 || x < -4 Key:b |x| >= 4 means x >= 4 or x <= -4. |x| >= 4 is true for x being -4, -5, -6, 4, 5, 6, etc. So B is correct. # 28. Which of the following is equivalent to x != y? a. ! (x == y) b. x > y && x < y c. x > y || x < y d. x >= y || x <= y Key:ac x != y means !(x == y) and x > y || x < y. # Section 3.12 Lottery 29. Suppose x=10 and y=10. What is x after evaluating the expression (y > 10) && (x-- > 10)? a. 9 b. 10 c. 11 Key:b For the && operator, the right operand is not evaluated, if the left operand is evaluated as false. # 30. a. b. ..

Suppose x=10 and y=10. What is x after evaluating the expression (y > 10) && (x++ > 10). 9 10


c. 11 Key:b For the && operator, the right operand is not evaluated, if the left operand is evaluated as false. # 31. Suppose x=10 and y=10. What is x after evaluating the expression (y >= 10) || (x-- > 10). a. 9 b. 10 c. 11 Key:b For the || operator, the right operand is not evaluated, if the left operand is evaluated as true. # 32. Suppose x=10 and y=10. What is x after evaluating the expression (y >= 10) || (x++ > 10). a. 9 b. 10 c. 11 Key:b For the || operator, the right operand is not evaluated, if the left operand is evaluated as true. # 33. Analyze the following code: if (x < 100) && (x > 10) System.out.println("x is between 10 and 100"); a. The statement has compile errors because (x<100) & (x > 10) must be enclosed inside parentheses. b.The statement has compile errors because (x<100) & (x > 10) must be enclosed inside parentheses and the println(…) statement must be put inside a block. c.The statement compiles fine. d.The statement compiles fine, but has a runtime error. Key:a The condition for an if statement must be enclosed in the parentheses. The correct answer is A. # 34. Which of the following are so called short-circuit operators? a. && b. & c. || d. | Key:ac && and || are short-circuit operator, meaning that if the left operand can determine the result of the operation, the right operand will be skipped. # Section 3.13 switch Statements 35. What is y after the following switch statement is executed? int x = 3; int y = 4; switch (x + 3) { case 6: y = 0; case 7: y = 1; default: y += 1; } a. 1 b. 2 c. 3 d. 4 e. 0 Key:b Since x is 3, x + 3 is 6. So, case 6 is executed. Since there is no break statement, the statement in the next case is ..


executed. y is now 1. Finally y += 1 adds 1 to y. So y is 2. The correct answer is B. # 36.

Analyze the following program fragment:

int x; double d = 1.5; switch (d) { case 1.0: x = 1; case 1.5: x = 2; case 2.0: x = 3; } a. The program has a compile error because the required break statement is missing in the switch statement. b. The program has a compile error because the required default case is missing in the switch statement. c. The switch control variable cannot be double. d. No errors. Key:c The switch value cannot be a floating-point number. So the correct answer is C. # Section 3.14 Conditional Expressions 37. What is y after the following statement is executed? x = 0; y = (x > 0) ? 10 : -10; a. -10 b. 0 c. 10 d. 20 e. Illegal expression Key:a This conditional operator is correct. It assigns -10 to y since x > 0 is false. # 38.

Analyze the following code fragments that assign a boolean value to the variable even.

Code 1: if (number % 2 == 0) even = true; else even = false; Code 2: even = (number % 2 == 0) ? true: false; Code 3: even = number % 2 == 0; a. Code 2 has a compile error, because you cannot have true and false literals in the conditional expression. b. Code 3 has a compile error, because you attempt to assign number to even. c. All three are correct, but Code 1 is preferred. d. All three are correct, but Code 2 is preferred. e. All three are correct, but Code 3 is preferred. Key:e Code 3 is the simplest. Code 1 and Code 2 contain redundant code. # ..


39. What is the output of the following code? boolean even = false; System.out.println((even ? "true" : "false")); a. true b. false c. nothing d. true false Key:b Since even is false, the conditional expression yields false. The correct answer is B. # Section 3.15 Operator Precedence and Associativity 40. The order of the precedence (from high to low) of the operators binary +, *, &&, ||, ^ is: a. &&, ||, ^, *, + b. *, +, &&, ||, ^ c. *, +, ^, &&, || d. *, +, ^, ||, && e. ^, ||, &&, *, + Key:c See the table for the operator precedence order. The correct answer is C. # 41. What is y displayed in the following code? public class Test1 { public static void main(String[] args) { int x = 1; int y = x = x + 1; System.out.println("y is " + y); } } a. y is 0. b. y is 1 because x is assigned to y first. c. y is 2 because x + 1 is assigned to x and then x is assigned to y. d. The program has a compile error since x is redeclared in the statement int y = x = x + 1. Key:c The = operator is right-associative. # 42. Which of the following operators are right-associative. a. * b. + (binary +) c. % d. && e. = Key:e Assignment operators including augmented assignment operators are right-associative. The correct answer is E. # 43. What is the value of the following expression? true || true && false a. true b. false Key:a && has higher precedence than ||, so && is evaluated first. # ..


44. Which of the following statements are true? a. (x > 0 && x < 10) is same as ((x > 0) && (x < 10)) b. (x > 0 || x < 10) is same as ((x > 0) || (x < 10)) c. (x > 0 || x < 10 && y < 0) is same as (x > 0 || (x < 10 && y < 0)) d. (x > 0 || x < 10 && y < 0) is same as ((x > 0 || x < 10) && y < 0) Key:abc In D, && is evaluated before the || operator. So (x > 0 || x < 10 && y < 0) is not same as ((x > 0 || x < 10) && y < 0).

..


Chapter 4 Mathematical Functions, Characters, and Strings Section 4.2 Common Mathematical Functions Section 4.2.1 Trigonometric Methods 1. To obtain the sine of 35 degrees, use . a. Math.sin(35) b. Math.sin(Math.toRadians(35)) c. Math.sin(Math.toDegrees(35)) d. Math.sin(Math.toRadian(35)) e. Math.sin(Math.toDegree(35)) Key:b Note the trig methods use the radians for angles. # 2. To obtain the arc sine of 0.5, use . a. Math.asin(0.5) b. Math.asin(Math.toDegrees(0.5)) c. Math.sin(Math.toRadians(0.5)) d. Math.sin(0.5) Key:a Note the trig methods use the radians for angles. # 3. Math.asin(0.5) returns . a. 30 b. Math.toRadians(30) c. Math.PI / 4 d. Math.PI / 2 Key:b Note that Math.asin returns an angle in radians. # 4. Math.sin(Math.PI) returns . a. 0.0 b. 1.0 c. 0.5 d. 0.4 Key:a Note that Math.PI is 180 degrees. # 5. Math.cos(Math.PI) returns . a. 0.0 b. 1.0 c. -1.0 d. 0.5 Key:c Note that Math.PI is 180 degrees. # Section 4.2.2 Exponent Methods 1. Which of the following is correct to obtain the square of 5? a. Math.sqrt(5) b. Math.sqrt(5.0) c. Math.pow(5, 0.5) d. Math.pow(5.0, 0.5) Key:abcd All choices are correct. © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


# Section 4.2.3 The Rounding Methods 6. What is Math.rint(3.6)? a. 3.0 b. 3 c. 4.0 d. 5.0 Key:c Note that rint returns a double value # 5. What is Math.round(3.6)? a. 3.0 b. 3 c. 4 d. 4.0 Key:c Note that round returns an int value # 7. What is Math.rint(3.5)? a. 3.0 b. 3 c. 4 d. 4.0 e. 5.0 Key:d rint returns the nearest even integer as a double since 3.5 is equally close to 3.0 and 4.0. # 8. What is Math.ceil(3.6)? a. 3.0 b. 3 c. 4.0 d. 5.0 Key:c Note that ceil returns a double value # 9. What is Math.floor(3.6)? a. 3.0 b. 3 c. 4 d. 5.0 Key:a Note that floor returns a double value # Section 4.2.4 The min, max, and abs Methods 1. Which of the following is correct to obtain the min of x, y, z? a. Math.min(x, Math.min(y, z)) b. Math.min(Math.min(x, y), z) c. Math.min(Math.min(y, z), x) d. Math.min(z, Math.min(x, y)) Key:abcd All choices are correct. # Section 4.2.5 The random Method 1. Which of the following is correct to obtain a random integer between 5 and 10? © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


..

a. 5 + Math.random() * 6 b. 5 + (int)(Math.random() * 6) c. 5 + Math.random() * 5 d. 5 + (int)(Math.random() * 5) Key:b In A, 5 + Math.random() * 6 returns a double value from 5.0 to 11.0 (excluding 11.0). In C, 5 + Math.random() * 5 returns a double value from 5.0 to 10.0 (excluding 10.0). In D, 5 + (int)(Math.random() * 5) returns an integer from 5 to 10. B is correct. # Section 4.3 Character Data Type and Operations Section 4.3.1 Unicode and ASCII Code 10. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4' Key:d You have to write '4'. # 11. A Java character is stored in . a. one byte b. two bytes c. three bytes d. four bytes Key:b Java characters use Unicode encoding. # 12. The Unicode of 'a' is 97. What is the Unicode for 'c'? a. 96 b. 97 c. 98 d. 99 Key:d The Unicode for letters and numbers are allocated in a natural order. So b is after a and c is after b, and so on. # Section 4.3.2 Escape Sequences for Special Characters 13. Which of the following statement prints smith\exam1\test.txt? a. System.out.println("smith\exam1\test.txt"); b. System.out.println("smith\\exam1\\test.txt"); c. System.out.println("smith\"exam1\"test.txt"); d. System.out.println("smith"\exam1"\test.txt"); Key:b To represent the \ character, use \\, because it is an escape character. # Section 4.3.3 Casting between char and Numeric Types 14. Suppose x is a char variable with a value 'b'. What is the output of the statement System.out.println(++x)? a. a b. b c. c d. d Key:c The ++ and -- operators can be applied to a char variable. ++x is preincrement. x is 'b' before ++x. After ++x, x becomes c. #


..

15. Suppose i is an int type variable. Which of the following statements display the character whose Unicode is stored in variable i? a. System.out.println(i); b. System.out.println((char)i); c. System.out.println((int)i); d. System.out.println(i + " "); Key:b (char)i casts a number into a character. # 16. Will System.out.println((char)4) display 4? a. Yes b. No Key:b The character whose Unicode is \u0004 is to be displayed, not number 4. # 17. What is the output of System.out.println('z' - 'a')? a. 25 b. 26 c. a d. z Key:a The Unicode offset between z and a is 25. # 18. An int variable can hold . a. 'x' b. 120 c. 120.0 d. "x" e. "120" Key:ab Choice A is also correct, because a character can be implicitly cast into an int variable. The Unicode value of character is assignment to the int variable. In this case, the code is 120 (see Appendix B). # 19. Which of the following assignment statements is correct? a. char c = 'd'; b. char c = 100; c. char c = "d"; d. char c = "100"; Key:ab Choice B is also correct, because an int value can be implicitly cast into a char variable. The Unicode of the character is the int value. In this case, the character is d (see Appendix B). # 20. '3' - '2' + 'm' / 'n' is . a. 0 b. 1 c. 2 d. 3 Key:b When an operand is a character in an arithmetic expression, the character is casted to an int value. # Section 4.3.4 Comparing and Testing Characters 21. To check whether a char variable ch is an uppercase letter, you write a. (ch >= 'A' && ch >= 'Z') b. (ch >= 'A' && ch <= 'Z')

.


..

c. (ch >= 'A' || ch <= 'Z') d. ('A' <= ch <= 'Z') Key:b A is wrong because ch >= 'Z'. C is wrong because of using ||. D is wrong because of incorrect syntax. The correct answer is B. # 22. Which of the following is not a correct method in the Character class? a. isLetterOrDigit(char) b. isLetter(char) c. isDigit() d. toLowerCase(char) e. toUpperCase() Key:ce isDigit() should be isDigit(char) and toUpperCase() should be toUpperCase(char) # Section 4.4 The String Type Section 4.4.2 Gettiing Characters from a String 24. Suppose s is a string with the value "java". What will be assigned to x if you execute the following code? char x = s.charAt(4); a. 'a' b. 'v' c. Nothing will be assigned to x, because the execution causes the runtime error StringIndexOutofBoundsException. Key:c The string index starts from 0 and the last index is s.length() - 1. s.charAt(4) is out of bounds. # Section 4.4.3 Concatenating Strings 25. The expression "Java " + 1 + 2 + 3 evaluates to . a. Java123 b. Java6 c. Java 123 d. java 123 e. Illegal expression key:c The + operator is evaluated from left to right. When a string adds with a number, the number is converted into a string. The correct answer is C. # 26. Note that the Unicode for character A is 65. The expression "A" + 1 evaluates to . a. 66 b. B c. A1 d. Illegal expression key:c When a string adds with a number, the number is converted into a string. The correct answer is C. # 27. Note that the Unicode for character A is 65. The expression 'A' + 1 evaluates to . a. 66 b. B c. A1 d. Illegal expression key:a When a character adds with a number, the character is converted into a int. The correct answer is A. # Section 4.4.4 Converting Strings


..

28. Which of the following is the correct statement to return JAVA? a. toUpperCase("Java") b. "Java".toUpperCase("Java") c. "Java".toUpperCase() d. String.toUpperCase("Java") Key:c The correct method is toUpperCase(). So C is correct. # Section 4.4.7 Comparing Strings 29. Suppose s1 and s2 are two strings. Which of the following statements or expressions is incorrect? a. String s3 = s1 - s2; b. boolean b = s1.compareTo(s2); c. char c = s1[0]; d. char c = s1.charAt(s1.length()); Key:abcd A is wrong because the - operator cannot be used for strings. B is wrong because the compareTo method returns an int, not a boolean. C is wrong because the [] cannot be used for accessing string elements. D is wrong because of index out of bounds. # 30.

Suppose s1 and s2 are two strings. What is the result of the following code?

s1.equals(s2) == s2.equals(s1) a. true b. false Key:a s1.equals(s2) and s2.equals(s1) are the same. # 31. "abc".compareTo("aba") returns . a. 1 b. 2 c. -1 d. -2 e. 0 Key:b The first two characters in the two strings are the same. The different between the last two characters is 2. The correct answer is B. # 32. "AbA".compareToIgnoreCase("abC") returns . a. 1 b. 2 c. -1 d. -2 e. 0 Key:d Ignoring case, you compare aba with abc. The first two characters in the two strings are the same. The different between the last two characters is -2. The correct answer is D. # 33. returns true. a. "peter".compareToIgnoreCase("Peter") b. "peter".compareToIgnoreCase("peter") c. "peter".equalsIgnoreCase("Peter") d. "peter".equalsIgnoreCase("peter") e. "peter".equals("peter") Key:cde The compareToIgnoreCase return an int. So, A and B are wrong. Ignoring case, C, D, and E all return true.


..

# Section 4.4.8 Obtaining Substrings 34. What is the return value of "SELECT".substring(0, 5)? a. "SELECT" b. "SELEC" c. "SELE" d. "ELECT" Key:b Note that the substring is from index 0 to 4, which is 5 - 1. The correct answer is B. # 35. What is the return value of "SELECT".substring(4, 4)? a. an empty string b. C c. T d. E Key:a If beginIndex is endIndex, substring(beginIndex, endIndex) returns an empty string with length 0. It would be a runtime error, if beginIndex > endIndex. # Section 4.4.9 Finding a Character or a Substring in a String 36. To check if a string s contains the prefix "Java", you may write a. if (s.startsWith("Java")) ... b. if (s.indexOf("Java") == 0) ... c. if (s.substring(0, 4).equals("Java")) ... d. if (s.charAt(0) == 'J' && s.charAt(1) == 'a' && s.charAt(2) == 'v' && s.charAt(3) == 'a') ... Key:abcd They are all correct. # 37. To check if a string s contains the suffix "Java", you may write a. if (s.endsWith("Java")) ... b. if (s.lastIndexOf("Java") >= 0) ... c. if (s.substring(s.length() - 4).equals("Java")) ... d. if (s.substring(s.length() - 5).equals("Java")) ... e. if (s.charAt(s.length() - 4) == 'J' && s.charAt(s.length() - 3) == 'a' && s.charAt(s.length() - 2) == 'v' && s.charAt(s.length() - 1) == 'a') ... Key:ace s.lastIndexOf("Java") >= 0 does not indicate that Java is the suffix of the string. # Section 4.4.10 Conversions between Strings and Numbers 38. The method parses a string s to an int value. a. integer.parseInt(s); b. Integer.parseInt(s); c. integer.parseInteger(s); d. Integer.parseInteger(s); Key:b The parseInt method is defined in the Integer class. B is correct. # 39. The method parses a string s to a double value. a. double.parseDouble(s); b. Double.parsedouble(s); c. double.parse(s); d. Double.parseDouble(s);


..

Key:d The parseDouble method is defined in the Double class. D is correct. # Section 4.6 Formatting Console Output 40. Which of the following are valid specifiers for the printf statement? a. %4c b. %10b c. %6d d. %8.2d e. %10.2e Key:abce All correct. D is wrong because the specifier d is for decimal integer. # 41. The statement System.out.printf("%3.1f", 1234.56) outputs . a. 123.4 b. 123.5 c. 1234.5 d. 1234.56 e. 1234.6 Key:e .1 specifies one digit after the decimal point. The rest is rounded up. So 1234.56 is displayed 1234.6. # 42. The statement System.out.printf("%3.1e", 1234.56) outputs . a. 0.1e+04 b. 0.123456e+04 c. 0.123e+04 d. 1.2e+03 e. 1.23+03 Key:d %3.1e specifies a scientific notation with one digit after the decimal point. So, the correct answer is D. # 43. The statement System.out.printf("%5d", 123456) outputs . a. 12345 b. 23456 c. 123456 d. 12345.6 Key:c %5d specifies an integer with width 5. The width is automatically expanded if the number is larger than the specified width. So, the correct answer is C. # 44. The statement System.out.printf("%10s", 123456) outputs . (Note: * represents a space) a. 123456**** b. 23456***** c. 12345***** d. ****123456 Key:d %10s specifies to display a string with width 10. By default, it is right justified. So, the correct answer is D. # 45. Analyze the following code: int i = 3434; double d = 3434; System.out.printf("%5.1f %5.1f", i, d); a. The code compiles and runs fine to display 3434.0 3434.0.


..

b. The code compiles and runs fine to display 3434 3434.0. c. i is an integer, but the format specifier %5.1f specifies a format for double value. The code has an error. Key:c i is an integer, but the format specifier %5.1f specifies a format for double value. Type does not match. So, the correct answer is C.


Chapter 5 Loops Section 5.2 The while Loop 1. How many times will the following code print "Welcome to Java"? int count = 0; while (count < 10) { System.out.println("Welcome to Java"); count++; } a. 8 b. 9 c. 10 d. 11 e. 0 Key:c The count is initialized to 0 before the loop. The loop is executed 10 times for count from 1 to 9. When count is 10, the loop continuation condition becomes false. The loop is finished. So, the correct answer is C. # 2. Analyze the following code. int count = 0; while (count < 100) { // Point A System.out.println("Welcome to Java!"); count++; // Point B } // Point C a. count < 100 is always true at Point A b. count < 100 is always true at Point B c. count < 100 is always false at Point B d. count < 100 is always true at Point C e. count < 100 is always false at Point C Key:ae The count is initialized to 0 before the loop. The loop is executed 100 times for count from 0 to 99. Inside the loop body, at Point A, count < 100 is true. After executing count++, count < 100 in Point B may become false. After the loop is exited, count < 100 is false at Point C. So, the correct answer is AE. # Section 5.3 Case Study: Guessing Numbers 3. How many times will the following code print "Welcome to Java"? int count = 0; while (count++ < 10) { System.out.println("Welcome to Java"); } a. 8 b. 9 c. 10 d. 11 e. 0 Key:c The count is initialized to 0 before the loop. (count++ < 10) increments count by 1 and uses the old count value ..


to check if count < 10. So, the loop is executed 10 times for count from 0 to 9. The correct answer is C. # 4. What is the output of the following code? int x = 0; while (x < 4) { x = x + 1; } System.out.println("x is " + x); a. x is 0 b. x is 1 c. x is 2 d. x is 3 e. x is 4 Key:e x is 0 before the loop. The loop is executed 4 times for x from 0 to 3. When x is 4 the loop exits. So, the correct answer is E. # Section 5.5 Controlling a Loop with User Confirmation or a Sentinel Value 5. What will be displayed when the following code is executed? int number = 6; while (number > 0) { number -= 3; System.out.print(number + " "); } a. 630 b. 6 3 c. 30 d. 3 0 -3 e. 0 -3 Key:c number is 6 before the loop. In the first iteration, number is reduced to 3. In the second iteration, number is reduced to 0. The loop is now finished. The loop body is executed 2 times for number 6 and 3. Since number is reduced by 3 before the print statement. 3 and 0 and displayed. So, the correct answer is C. # Section 5.6 The do-while Loop 6. How many times will the following code print "Welcome to Java"? int count = 0; do { System.out.println("Welcome to Java"); count++; } while (count < 10); a. 8 b. 9 c. 10 d. 11 e. 0 Key:c The count is initialized to 0 before the loop. The loop is executed 10 times for count from 0 to 9. When count is 10, the loop continuation condition becomes false. The loop is finished. So, the correct answer is C.

..


# 7.

How many times will the following code print "Welcome to Java"?

int count = 0; do { System.out.println("Welcome to Java"); } while (count++ < 10); a. 8 b. 9 c. 10 d. 11 e. 0 Key:d The count is initialized to 0 before the loop. The loop is executed for the first time when count is 0. (count++ < 10) increments count by 1 and uses the old count value to check if count < 10. So, the loop is executed 11 times for count from 0 to 10. Note that when count is 10, the loop body is executed before the loop is exited. The correct answer is D. # 8.

How many times will the following code print "Welcome to Java"?

int count = 0; do { System.out.println("Welcome to Java"); } while (++count < 10); a. 8 b. 9 c. 10 d. 11 e. 0 Key:c The count is initialized to 0 before the loop. The loop is executed for the first time when count is 0. (++count < 10) increments count by 1 and uses the new count value to check if count < 10. So, the loop is executed 10 times for count from 0 to 9. Note that when count is 9, ++count becomes 10, the loop exits. The correct answer is C. # 9.

What is the value in count after the following loop is executed?

int count = 0; do { System.out.println("Welcome to Java"); } while (count++ < 9); System.out.println(count); a. 8 b. 9 c. 10 d. 11 e. 0 Key:c The count is initialized to 0 before the loop. The loop is executed for the first time when count is 0. (count++ < 9) increments count by 1 and uses the old count value to check if count < 9. So, the loop is executed 10 times for count from 0 to 9. Note that when count is 9, the loop body is executed and then count++ increments count to 10. The previous count value 9 < 9 is false. So the loop is finished. Now count becomes 10 after the loop exits. The correct answer is C. # Section 5.7 The for Loop ..


10.

Analyze the following statement:

double sum = 0; for (double d = 0; d < 10;) { d += 0.1; sum += sum + d; } a. The program has a compile error because the adjustment is missing in the for loop. b. The program has a compile error because the control variable in the for loop cannot be of the double type. c. The program runs in an infinite loop because d < 10 would always be true. d. The program compiles and runs fine. Key:d In this loop, the loop initial action is d = 0, the continuation condition is d < 10, and the action-after-eachiteration is blank. Note that any of these three parts in the loop can be omitted. So, the loop is correct. The correction answer is (D). # 11. Which of the following loops prints "Welcome to Java" 10 times? A: for (int count = 1; count <= 10; count++) { System.out.println("Welcome to Java"); } B: for (int count = 0; count < 10; count++) { System.out.println("Welcome to Java"); } C: for (int count = 1; count < 10; count++) { System.out.println("Welcome to Java"); } D: for (int count = 0; count <= 10; count++) { System.out.println("Welcome to Java"); } a. BD b. ABC c. AC d. BC e. AB Key:e In (A), the loop displays Welcome to Java 10 times for count from 1 to 10. In (B), the loop displays Welcome to Java 10 times for count from 0 to 9. In (C), the loop displays Welcome to Java 9 times for count from 1 to 9. In (D), the loop displays Welcome to Java 11 times for count from 0 to 10. Therefore, the correct answer is AB. # 12. Which of the following loops correctly computes 1/2 + 2/3 + 3/4 + ... + 99/100? A: double sum = 0; for (int i = 1; i <= 99; i++) { sum = i / (i + 1); } ..


System.out.println("Sum is " + sum); B: double sum = 0; for (int i = 1; i < 99; i++) { sum += i / (i + 1); } System.out.println("Sum is " + sum); C: double sum = 0; for (int i = 1; i <= 99; i++) { sum += 1.0 * i / (i + 1); } System.out.println("Sum is " + sum); D: double sum = 0; for (int i = 1; i <= 99; i++) { sum += i / (i + 1.0); } System.out.println("Sum is " + sum); E: double sum = 0; for (int i = 1; i < 99; i++) { sum += i / (i + 1.0); } System.out.println("Sum is " + sum); a. BCD b. ABCD c. B d. CDE e. CD Key:e Note that 1 / 2 is 0.5 in a math expression. In Java, however, integer division yields an integer. The fraction part is truncated. Therefore, i / (i + 1) is 0. (A) and (B) are incorrect. (E) is incorrect because the last i in the loop is 98. So the last item 99 / 100.0 is not added to sum. So, the correct answer is CD. # 13. The following loop displays

.

for (int i = 1; i <= 10; i++) { System.out.print(i + " "); i++; } a. 1 2 3 4 5 6 7 8 9 b. 1 2 3 4 5 6 7 8 9 10 c. 1 2 3 4 5 d. 1 3 5 7 9 e. 2 4 6 8 10 Key:d In this for loop, i is initialized to 1. i++ adds 1 to i at the end of the iteration. In the action-after-each-iteration, i is again incremented by 1. So, i is in effect incremented twice. So, i is 1, then 3, 5, 7, and 9. The correct answer is D. ..


# 14.

Do the following two statements in (I) and (II) result in the same value in sum?

(I): for (int i = 0; i < 10; ++i) { sum += i; } (II): for (int i = 0; i < 10; i++) { sum += i; } a. Yes b. No Key:a In this case, ++i and i++ are used standalone with no side-effect. So, (I) and (II) are equivalent. The correct answer is A. # 15.

What is the output for y?

int y = 0; for (int i = 0; i < 10; ++i) { y += i; } System.out.println(y); a. 10 b. 11 c. 12 d. 13 e. 45 Key:e The loop is executed 10 times for i from 0 to 9. Each time, i is added to y. So y = 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9, which 45. The correct answer is E. # 16.

What is i after the following for loop?

int y = 0; for (int i = 0; i < 10; ++i) { y += i; } a. 9 b. 10 c. 11 d. undefined Key:d The scope for i is inside the loop. After the loop, i is not defined. So, the correct answer is D. # 17.

Is the following loop correct?

for ( ; ; ); a. Yes b. No ..


Key:a Yes. This is equivalent to for (; true; ). # Section 5.8 Which Loop to Use? 18. Analyze the following fragment: double sum = 0; double d = 0; while (d != 10.0) { d += 0.1; sum += sum + d; } a. The program does not compile because sum and d are declared double, but assigned with integer value 0. b. The program never stops because d is always 0.1 inside the loop. c. The program may not stop because of the phenomenon referred to as numerical inaccuracy for operating with floating-point numbers. d. After the loop, sum is 0 + 0.1 + 0.2 + 0.3 + ... + 1.9 Key:c The correct answer is C. There is no guarantee that d will be exactly 10.0 because real numbers are represented using approximation in a computer system. # 19. Analyze the following code: public class Test { public static void main (String[] args) { int i = 0; for (i = 0; i < 10; i++); System.out.println(i + 4); } } a. The program has a compile error because of the semicolon (;) on the for loop line. b. The program compiles despite the semicolon (;) on the for loop line, and displays 4. c. The program compiles despite the semicolon (;) on the for loop line, and displays 14. d. The for loop in this program is same as for (i = 0; i < 10; i++) { }; System.out.println(i + 4); Key:cd This is a logic error. System.out.println(i + 4) is not a part the for loop because the for loop ends with the last semicolon at for (i=0; i < 10; i++); # Section 5.9 Nested Loops 20. How many times is the println statement executed? for (int i = 0; i < 10; i++) for (int j = 0; j < i; j++) System.out.println(i * j) a. 100 b. 20 c. 10 d. 45 Key:d When i is 0, the println statement is not executed. When i is 1, the println is executed 1 time. When i is 2, the println is executed 2 times. When i is 9, the println is executed 9 times. So, the total time for the println to be executed is 1 + 2 + ... + 9 = 45. # ..


21. Which pattern is produced by the following code? for (int i = 1; i <= 6; i++) { for (int j = 6; j >= 1; j--) System.out.print(j <= i ? j + " " : " " + " "); System.out.println(); } Pattern A Pattern B Pattern C Pattern D 1 123456 1 123456 12 12345 21 12345 123 1234 321 1234 1234 123 4321 123 12345 12 54321 12 123456 1 654321 1 a. Pattern A b. Pattern B c. Pattern C d. Pattern D Key:c The outer loop displays a line. The inner loop displays all the numbers in the line. The outer loop is repeated 6 times for i from 1 to 6. For each i, the inner loops displays i as the first number in the line since j is from 6 to 1. j is printed for j <= i. Otherwise, a space is printed. Clearly, this code will print Pattern C. # 22.

How many times is the println statement executed?

for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) System.out.println(i * j); a. 100 b. 20 c. 10 d. 45 Key:a The outer loop is executed 10 times for i from 0 to 9 and the inner loop is executed 10 times from j from 0 to 9. So the print statement is executed 100 times. The correct answer is A. # Section 5.10 Minimizing Numerical Errors 23. To add 0.01 + 0.02 + ... + 1.00, what order should you use to add the numbers to get better accuracy? a. add 0.01, 0.02, ..., 1.00 in this order to a sum variable whose initial value is 0. b. add 1.00, 0.99, 0.98, ..., 0.02, 0.01 in this order to a sum variable whose initial value is 0. Key:a Adding the numbers in the order specified in A will result in a more accurate result than in B, because two numbers to be added will be about the same size. # 24.

Analyze the following code.

double sum = 0; for (double d = 0; d < 10; sum += sum + d) { d += 0.1; } ..


A. The program has a syntax error because the adjustment statement is incorrect in the for loop. B. The program has a syntax error because the control variable in the for loop cannot be of the double type. C. The program compiles but does not stop because d would always be less than 10. D. The program compiles and runs fine. Key:d In this loop, the loop initial action is d = 0, the continuation condition is d < 10, and the action-after-eachiteration is sum += sum + d. The loop body is d += 1. This code is correct in syntax. d is initially 0 and d += 0.1 adds 0.1 to d in each iteration. Eventually d will be greater than or equal to 10. So the loop will terminate. The correct answer for this question is (D) The program compiles and runs fine. # Section 5.11 Case Studies 25. What is y after the following for loop statement is executed? int y = 0; for (int i = 0; i < 10; ++i) { y += 1; } A. 9 B. 10 C. 11 D. 12 Key:b Before the loop, y is 0. The loop is executed 10 times. Each time, 1 is added to y. So, after the loop is finished, y is 10. The correct answer is (B). # Section 5.12 Keywords break and continue 26. Will the following program terminate? int balance = 10; while (true) { if (balance < 9) break; balance = balance - 9; } a. Yes b. No Key:a Yes. Before the loop, balance is 10. The loop-continuation-condition is always true. In the first iteration, balance is reduced to 1. In the second iteration, the break statement is executed since (balance < 9) is now true. The correct answer for this question is A. # 27.

What is sum after the following loop terminates?

int sum = 0; int item = 0; do { item++; sum += item; if (sum > 4) break; } while (item < 5); a. 5 ..


b. 6 c. 7 d. 8 e. 9 Key:b sum and item are initialized to 0 before the loop. In the loop, item++ increments item by 1 and item is then added to sum. If sum > 4, the break statement exits the loop. item is initially 0, then 1, 2, 3 and sum is initially 0, and then 1, 3, and 6. When sum is 6, (sum > 4) is true, which causes the break statement to be executed. So, the correct answer is B. # 28.

What is the output after the following loop terminates?

int number = 25; int i; boolean isPrime = true; for (i = 2; i < number && isPrime; i++) { if (number % i == 0) { isPrime = false; } } System.out.println("i is " + i + " isPrime is " + isPrime); a. i is 5 isPrime is true b. i is 5 isPrime is false c. i is 6 isPrime is true d. i is 6 isPrime is false Key:d The code tests if number is prime by dividing the number with possible divisors 2, 3, 4, and so on. Initially, isPrime is set to true. Once a divisor is found (i.e., number % i == 0 is true), isPrime is set to false. The loop continuation condition now becomes false. The loop ends. If no divisor is found after the loop is finished, isPrime remains true. Since number is 25, number % i == 0 is true when i is 5. In this case, isPrime is set to false and i++ increments i by 1 in the action-after-each-iteration. So, the output is that i is 6 and isPrime is false. The correct anwer is D. # 29.

What is the output after the following loop terminates?

int number = 25; int i; boolean isPrime = true; for (i = 2; i < number; i++) { if (number % i == 0) { isPrime = false; break; } } System.out.println("i is " + i + " isPrime is " + isPrime); a. b. c.

i is 5 isPrime is true i is 5 isPrime is false i is 6 isPrime is true ..


d. i is 6 isPrime is false Key:b The code tests if number is prime by dividing the number with possible divisors 2, 3, 4, and so on. Initially, isPrime is set to true. Once a divisor is found (i.e., number % i == 0 is true), isPrime is set to false and the break statement is then executed to exit the loop. If no divisor is found after the loop is finished, isPrime remains true. Since number is 25, number % i == 0 is true when i is 5. In this case, isPrime is set to false and the loop exits. So, the output is that i is 5 and isPrime is true. The correct answer is B. # 30.

What is sum after the following loop terminates?

int sum = 0; int item = 0; do { item++; if (sum >= 4) continue; sum += item; } while (item < 5); a. 6 b. 7 c. 8 d. 9 e. 10 Key:a In this loop, when sum >= 4, the continue statement is executed to exit the current iteration so the next statement sum += item after the if statement will not be executed. The loop keeps adding item to sum for item 1, 2, 3, and so on. So sum is 1, 2, and 6. When sum is 6, sum >=4 is true, the continue statement is executed to skip the rest of the iteration. When the loop ends, sum is still 6. So, the correct answer is A. # 31.

Will the following program terminate?

int balance = 10; while (true) { if (balance < 9) continue; balance = balance - 9; } a. Yes b. No Key:b Before the loop, balance is 10. In the loop, balance becomes 1. The loop-continuation-condition is always true. When balance < 9 is true, the continue statement is executed to skip the rest statement in the iteration. So the loop continues in an infinite loop. So, the correct answer is B. # 32.

What balance after the following code is executed?

int balance = 10; while (balance >= 1) { if (balance < 9) continue; balance = balance - 9; ..


} A. -1 B. 0 C. 1 D. 2 E. The loop does not end Key:e Before the loop, balance is 10. The loop-continuation-condition is true (10 >= 1). In the first iteration, balance is reduced to 1. Since 1 >= 1 is true, the loop body is executed. Since balance < 9 is true, the continue statement is executed to skip the rest statement in the iteration. balance continues to be 1 and the continue statement is executed to skip the rest statement in the iteration. So the loop runs infinitely. So the correct answer to this question is E. # 33.

What is the value of balance after the following code is executed?

int balance = 10; while (balance >= 1) { if (balance < 9) break; balance = balance - 9; } A. -1 B. 0 C. 1 D. 2 Key:c Before the loop, balance is 10. The loop-continuation-condition is true (10 >= 1). In the first iteration, balance is reduced to 1. Since 1 >= 1 is true, the loop body is executed. Since balance < 9 is true, the break statement is executed to exit the loop. So, balance is 1 after the loop is finished. The correct answer for this question is C. # Section 5.13 Case Study: Checking Palindromes 34. What is the number of iterations in the following loop? for (int i = 1; i < n; i++) { // iteration } a. 2*n b. n c. n - 1 d. n + 1 Key:c The loop is executed n – 1 times for i from 1 to n – 1. So, the correct answer is C. # 35. What is the number of iterations in the following loop? for (int i = 1; i <= n; i++) { // iteration } a. 2*n b. n c. n - 1 d. n + 1 ..


Key:b The loop is executed n times for i from 1 to n. So, the correct answer is B. # Section 5.14 Case Study: Displaying Prime Numbers 36. Suppose the input for number is 9. What is the output from running the following program? import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer: "); int number = input.nextInt(); int i; boolean isPrime = true; for (i = 2; i < number && isPrime; i++) { if (number % i == 0) { isPrime = false; } } System.out.println("i is " + i); if (isPrime) System.out.println(number + " is prime"); else System.out.println(number + " is not prime"); } } a. i is 3 followed by 9 is prime b. i is 3 followed by 9 is not prime c. i is 4 followed by 9 is prime d. i is 4 followed by 9 is not prime Key:d The input number is 9. isPrime is initialized to true. The loop tests if number is divisible by i for i from 2, 3, and so on. When i is 3, isPrime is false. The loop continuation condition becomes false. The loop is not finished. Before the loop continuation condition is checked, i++ increments i by 1. So, output is that i is 4 and following by 9 is not prime. So, the correct answer is is executed n times for i from 1 to n. So, the correct answer is D. # 37. Analyze the following code: import java.util.Scanner; public class Test { public static void main(String[] args) { int sum = 0; for (int i = 0; i < 100000; i++) { Scanner input = new Scanner(System.in); sum += input.nextInt(); } } ..


} a. The program does not compile because the Scanner input = new Scanner(System.in); statement is inside the loop. b. The program compiles, but does not run because the Scanner input = new Scanner(System.in); statement is inside the loop. c. The program compiles and runs, but it is not efficient and unnecessary to execute the Scanner input = new Scanner(System.in); statement inside the loop. You should move the statement before the loop. d. The program compiles, but does not run because there is not prompting message for entering the input. Key:c To receive input from the keyboard, you need to create an input object from the Scanner class. You should create this object only once in the program. Placing the statement Scanner input = new Scanner(System.in) in the loop causes it to be created multiple times, which is a bad practice and could lead to potential errors. So, the correct answer is C.

..


Chapter 6 Methods Sections 6.2 Defining a Method 1. Suppose your method does not return any value, which of the following keywords can be used as a return type? a. void b. int c. double d. public e. None of the above Key:a See the third paragraph in this section. # 2. The signature of a method consists of . a. method name b. method name and parameter list c. return type, method name, and parameter list d. parameter list Key:b By definition, a method signature consists of method name and parameter list. # 3. All Java applications must have a method . a. public static Main(String[] args) b. public static Main(String args[]) c. public static void main(String[] args) d. public void main(String[] args) e. public static main(String[] args) Key:c Java application's starting method is the main method. # Sections 6.3 Calling a Method 4. Arguments to methods always appear within a. brackets b. parentheses c. curly braces d. quotation marks Key:b See Listing 6.1. # 6.

.

Does the method call in the following method cause compile errors?

public static void main(String[] args) { Math.pow(2, 4); } a. Yes b. No Key:b A value-returning method can also be invoked as a statement in Java. In this case, the caller simply ignores the return value. This is rare, but permissible if the caller is not interested in the return value. # 7. Each time a method is invoked, the system stores parameters and local variables in an area of memory, known as , which stores elements in last-in first-out fashion. a. a heap b. storage area c. a stack © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


d. an array key:c See the discussion on the activation record. # Sections 6.4 void vs. Value-Returning Methods 8. Which of the following should be defined as a void method? a. Write a method that prints integers from 1 to 100. b. Write a method that returns a random integer from 1 to 100. c. Write a method that checks whether a number is from 1 to 100. d. Write a method that converts an uppercase letter to lowercase. key:a A method that does not return a value should be defined void. # 9. You should fill in the blank in the following code with

.

public class Test { public static void main(String[] args) { System.out.print("The grade is "); printGrade(78.5); System.out.print("The grade is "); printGrade(59.5); } public static printGrade(double score) { if (score >= 90.0) { System.out.println('A'); } else if (score >= 80.0) { System.out.println('B'); } else if (score >= 70.0) { System.out.println('C'); } else if (score >= 60.0) { System.out.println('D'); } else { System.out.println('F'); } } } a. int b. double c. boolean d. char e. void key:e void should to be used here because the method does not return any value. # 10. You should fill in the blank in the following code with

.

public class Test { © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


public static void main(String[] args) { System.out.print("The grade is " + getGrade(78.5)); System.out.print("\nThe grade is " + getGrade(59.5)); } public static getGrade(double score) { if (score >= 90.0) return 'A'; else if (score >= 80.0) return 'B'; else if (score >= 70.0) return 'C'; else if (score >= 60.0) return 'D'; else return 'F'; } } a. int b. double c. boolean d. char e. void key:d char should be placed here because the method returns a character. # 5.

Does the return statement in the following method cause compile errors?

public static void main(String[] args) { int max = 0; if (max != 0) System.out.println(max); else return; } a. Yes b. No Key:b See the Caution box. It is rare, but sometimes useful to have a return statement for circumventing the normal flow of control in a void method. # 11. Consider the following incomplete code. The missing method body should be

.

public class Test { public static void main(String[] args) { System.out.println(f(5)); } public static int f(int number) { // Missing body } } © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


a. return "number"; b. System.out.println(number); c. System.out.println("number"); d. return number; Key:d The method returns and int. So D is correct. # Sections 6.5 Passing Parameters by Values 12. When you invoke a method with a parameter, the value of the argument is passed to the parameter. This is referred to as . a. method invocation b. pass by value c. pass by reference d. pass by name key:b See the third paragraph in this section. # 13. Given the following method, what is the output of the call nPrint('a', 4)? static void nPrint(String message, int n) { while (n > 0) { System.out.print(message); n--; } } a. aaaaa b. aaaa c. aaa d. invalid call Key:d Invalid call because char 'a' cannot be passed to string message # 14. Given the following method static void nPrint(String message, int n) { while (n > 0) { System.out.print(message); n--; } } What is k after invoking nPrint("A message", k)? int k = 2; nPrint("A message", k); a. 0 b. 1 c. 2 d. 3 Key:c See Listing 6.4. # Section 6.8 Overloading Methods © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


15. Analyze the following code: public class Test { public static void main(String[] args) { System.out.println(xMethod(5, 500L)); } public static int xMethod(int n, long l) { System.out.println("int, long"); return n; } public static long xMethod(long n, long l) { System.out.println("long, long"); return n; } } a. The program displays int, long followed by 5. b. The program displays long, long followed by 5. c. The program runs fine but displays things other than 5. d. The program does not compile because the compiler cannot distinguish which xmethod to invoke. Key:a See Listing 6.9. # 16.

Analyze the following code:

class Test { public static void main(String[] args) { System.out.println(xmethod(5)); } public static int xmethod(int n, long t) { System.out.println("int"); return n; } public static long xmethod(long n) { System.out.println("long"); return n; } } a. The program displays int followed by 5. b. The program displays long followed by 5. c. The program runs fine but displays things other than 5. d. The program does not compile because the compiler cannot distinguish which xmethod to invoke. Key:b See Listing 6.9. # 17. Analyze the following code. public class Test { public static void main(String[] args) { System.out.println(max(1, 2)); } © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


public static double max(int num1, double num2) { System.out.println("max(int, double) is invoked"); if (num1 > num2) return num1; else return num2; } public static double max(double num1, int num2) { System.out.println("max(double, int) is invoked"); if (num1 > num2) return num1; else return num2; } } a. The program cannot compile because you cannot have the print statement in a non-void method. b. The program cannot compile because the compiler cannot determine which max method should be invoked. c. The program runs and prints 2 followed by "max(int, double)" is invoked. d. The program runs and prints 2 followed by "max(double, int)" is invoked. e. The program runs and prints "max(int, double) is invoked" followed by 2. Key:b This is known as ambiguous method invocation. See the last Note box in this section. # 18. Analyze the following code. public class Test { public static void main(String[] args) { System.out.println(m(2)); } public static int m(int num) { return num; } public static void m(int num) { System.out.println(num); } } a. The program has a compile error because the two methods m have the same signature. b. The program has a compile error because the second m method is defined, but not invoked in the main method. c. The program runs and prints 2 once. d. The program runs and prints 2 twice. Key:a You cannot overload the methods based on the type returned. See the first Note box in this section. # Section 6.9 The Scope of Variables 19. A variable defined inside a method is referred to as a. a global variable b. a method variable c. a block variable

.

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


d. a local variable key:d See the first paragraph. # 20. What is k after the following block executes? { int k = 2; nPrint("A message", k); } System.out.println(k); a. 0 b. 1 c. 2 d. k is not defined outside the block. So, the program has a compile error Key:d k is defined inside the block. Outside the block, k is not defined. # Section 6.10 Case Study: Generating Random Characters 21. (int)(Math.random() * (65535 + 1)) returns a random number a. between 1 and 65536 b. between 1 and 65535 c. between 0 and 65535 d. between 0 and 65536 key:c See the second paragraph in this section. # 22. (int)('a' + Math.random() * ('z' - 'a' + 1)) returns a random number a. between 0 and (int)'z' b. between (int)'a' and (int)'z' c. between 'a' and 'z' d. between 'a' and 'y' key:b See LiveExample 6.10. # 23. (char)('a' + Math.random() * ('z' - 'a' + 1)) returns a random character a. between 'a' and 'z' b. between 'a' and 'y' c. between 'b' and 'z' d. between 'b' and 'y' key:a See LiveExample 6.10.

.

.

.

# 24. Which of the following is the best for generating random integer 0 or 1? a. (int)Math.random() b. (int)Math.random() + 1 c. (int)(Math.random() + 0.5) d. (int)(Math.random() + 0.2) e. (int)(Math.random() + 0.8) key:c 50% of (Math.random() + 0.5) is <= 1 and 50% of (Math.random() + 0.5) is > 1. So, C is the correct. # Section 6.11 Method Abstraction and Stepwise Refinement 25. The client can use a method without knowing how it is implemented. The details of the implementation are © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


encapsulated in the method and hidden from the client who invokes the method. This is known as a. information hiding b. encapsulation c. method hiding d. simplifying method key:ab See the first paragraph.

.

# 26. is to implement one method in the structure chart at a time from the top to the bottom. a. Bottom-up approach b. Top-down approach c. Bottom-up and top-down approach d. Stepwise refinement key:b See Section 6.11.2. # 27. is a simple but incomplete version of a method. a. A stub b. A main method c. A non-main method d. A method developed using top-down approach key:a See Section 6.11.2.

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


Chapter 7 Single-Dimensional Arrays Section 7.2 Array Basics 3. Once an array is created, its size a. can be changed b. is fixed c. is not determined Key:b See the Key Point.

.

# Section 7.2.1 Declaring Array Variables 3. Which of the following are correct to declare an array of int values? a. int[] a; b. int a[]; c. int a; d. double[] a; Key:ab See the first paragraph. # Section 7.2.2 Creating Arrays 3. Which of the following are incorrect? a. int[] a = new int[2]; b. int a[] = new int[2]; c. int[] a = new int(2); d. int a = new int[2]; e. int a() = new int[2]; Key:cde See Sections 7.2.1 and 7.2.2. # 4. If you declare an array double[] list = new double[5], the highest index in array list is a. 0 b. 1 c. 2 d. 3 e. 4 Key:e See Figure 7.1. # Section 7.2.3 Array Size and Default Values 5. How many elements are in array double[] list = new double[5]? a. 4 b. 5 c. 6 d. 0 Key:b See Figure 7.1. # 8.

Analyze the following code.

public class Test { public static void main(String[] args) { © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.

.


..

int[] x = new int[3]; System.out.println("x[0] is " + x[0]); } } a. The program has a compile error because the size of the array wasn't specified when declaring the array. b. The program has a runtime error because the array elements are not initialized. c. The program runs fine and displays x[0] is 0. d. The program has a runtime error because the array element x[0] is not defined. Key:c The default value for an int array element is 0. # Section 7.2.4 Accessing Array Elements 6. What is the correct term for numbers[99]? a. index b. index variable c. indexed variable d. array variable e. array Key:c See Section 7.2.4. # 1. What is the representation of the third element in an array called a? a. a[2] b. a(2) c. a[3] d. a(3) Key:a See Section 7.2.4. # 7. Suppose int i = 5, which of the following can be used as an index for array double[] t = new double[100]? a. i b. (int)(Math.random() * 100)) c. i + 10 d. i + 6.5 e. Math.random() * 100 Key:abc The array t has 100 elements and its index is an integer from 0 to 99. So, A, B, C are all correct. D and E are double values, not integers. # Section 7.2.5 Array Initializers 2. If you declare an array double[] list = {3.4, 2.0, 3.5, 5.5}, list[1] is a. 3.4 b. 2.0 c. 3.5 d. 5.5 e. undefined Key:b See Section 7.2.5. # 9. a. b. c. d.

Which of the following statements are valid? int i = new int(30); double d[] = new double[30]; int[] i = {3, 4, 3, 2}; char[] c = new char();

.


e. char[] c = new char[4]{'a', 'b', 'c', 'd'}; Key:bc e would be corrected if it is char[] c = new char[]{'a', 'b', 'c', 'd'}; # 10. How can you initialize an array of two characters to 'a' and 'b'? a. char[] charArray = new char[2]; charArray = {'a', 'b'}; b. char[2] charArray = {'a', 'b'}; c. char[] charArray = {'a', 'b'}; d. char[] charArray = new char[2]; charArray[0] = 'a'; charArray[1] = 'b'; Key:cd See Section 7.2.5. # 12. Assume int[] t = {1, 2, 3, 4}. What is t.length? a. 0 b. 3 c. 4 d. 5 Key:c See Section 7.2.5. # Section 7.2.6 Processing Arrays 13. What is the output of the following code? double[] myList = {1, 5, 5, 5, 5, 1}; double max = myList[0]; int indexOfMax = 0; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) { max = myList[i]; indexOfMax = i; } } System.out.println(indexOfMax); a. 0 b. 1 c. 2 d. 3 e. 4 Key:b The code displays the index of the first max value in the array. # 14. Analyze the following code: public class Test { public static void main(String[] args) { int[] x = new int[5]; int i; for (i = 0; i < x.length; i++) x[i] = i; System.out.println(x[i]); } } a. The program displays 0 1 2 3 4. b. The program displays 4. © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


..

c. The program has a runtime error because the last statement in the main method causes ArrayIndexOutOfBoundsException. d. The program has a compile error because i is not defined in the last statement in the main method. Key:c After the for loop i is 5. x[5] is out of bounds. # 16. What is the output of the following code? int[] myList = {1, 2, 3, 4, 5, 6}; for (int i = myList.length - 2; i >= 0; i--) { myList[i + 1] = myList[i]; } for (int e: myList) System.out.print(e + " "); a. 123456 b. 6 1 2 3 4 5 c. 623451 d. 1 1 2 3 4 5 e. 234561 Key:d See Shifting elements in Item #8. # Section 7.2.7 Foreach Loops 15. Analyze the following code: public class Test { public static void main(String[] args) { double[] x = {2.5, 3, 4}; for (double value: x) System.out.print(value + " "); } } a. The program displays 2.5, 3, 4 b. The program displays 2.5 3 4 c. The program displays 2.5 3.0 4.0 d. The program displays 2.5, 3.0 4.0 e. The program has a syntax error because value is undefined. Key:c See the first paragraph. # Section 7.3 Case Study: Analyzing Numbers 17. What is output of the following code: public class Test { public static void main(String[] args) { int[] x = {120, 200, 016}; for (int i = 0; i < x.length; i++) System.out.print(x[i] + " "); } } a. 120 200 16


b. 120 200 14 c. 120 200 20 d. 016 is a compile error. It should be written as 16. Key:b 016 is an octal number. The prefix 0 indicates that a number is in octal. # Section 7.4 Case Study: Deck of Cards 18. What is output of the following code: public class Test { public static void main(String[] args) { int list[] = {1, 2, 3, 4, 5, 6}; for (int i = 1; i < list.length; i++) list[i] = list[i - 1]; for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); } } a. 123456 b. 234566 c. 234561 d. 111111 Key:d The first element is copied to the second, the second is then copied to the third, and so on. # Section 7.5 Copying Arrays 20. In the following code, what is the output for list2? public class Test { public static void main(String[] args) { int[] list1 = {1, 2, 3}; int[] list2 = {1, 2, 3}; list2 = list1; list1[0] = 0; list1[1] = 1; list2[2] = 2; for (int i = 0; i < list2.length; i++) System.out.print(list2[i] + " "); } } a. 1 2 3 b. 1 1 1 c. 0 1 2 d. 0 1 3 Key:c list2 = list1 makes list2 point to the same array as list1. See Figure 7.4. # 22. Analyze the following code: public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4}; int[] y = x; © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


..

x = new int[2]; for (int i = 0; i < y.length; i++) System.out.print(y[i] + " "); } } a. The program displays 1 2 3 4 b. The program displays 0 0 c. The program displays 0 0 3 4 d. The program displays 0 0 0 0 Key:a y is {1, 2, 3, 4} and x is {0, 0}. # 24. Analyze the following code: public class Test { public static void main(String[] args) { final int[] x = {1, 2, 3, 4}; int[] y = x; x = new int[2]; for (int i = 0; i < y.length; i++) System.out.print(y[i] + " "); } } a. The program displays 1 2 3 4. b. The program displays 0 0. c. The program has a compile error on the statement x = new int[2], because x is final and cannot be changed. d. The elements in the array x cannot be changed, because x is final. Key:c The value stored in x is final, but the values in the array are not final. x is a constant reference variable that points to an array with four elements Because it is a constant, you cannot create a new reference variable x that points to a different array, but you can change the value of the elements in the array, e.g. x[1] could be changed to 10 instead of 2. # 25. Analyze the following code. int[] list = new int[5]; list = new int[6]; a. The code has compile errors because the variable list cannot be changed once it is assigned. b. The code has runtime errors because the variable list cannot be changed once it is assigned. c. The code can compile and run fine. The second line assigns a new array to list. d. The code has compile errors because you cannot assign a different size array to list. Key:c See Figure 7.4. # 26. Analyze the following code: public class Test { public static void main(String[] args) { int[] a = new int[4]; a[1] = 1;


a = new int[2]; System.out.println("a[1] is " + a[1]); } } a. The program has a compile error because new int[2] is assigned to a. b. The program has a runtime error because a[1] is not initialized. c. The program displays a[1] is 0. d. The program displays a[1] is 1. Key:c After executing the statement a = new int[2], a refers to int[2]. The default value for a[0] and a[1] is 0. # 27. The method copies the sourceArray to the targetArray. a. System.copyArrays(sourceArray, 0, targetArray, 0, sourceArray.length); b. System.copyarrays(sourceArray, 0, targetArray, 0, sourceArray.length); c. System.arrayCopy(sourceArray, 0, targetArray, 0, sourceArray.length); d. System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length); Key:d See the discussion on the arraycopy method in this section. # 21. In the following code, what is the output for list1? public class Test { public static void main(String[] args) { int[] list1 = {1, 2, 3}; int[] list2 = {1, 2, 3}; list2 = list1; list1[0] = 0; list1[1] = 1; list2[2] = 2; for (int i = 0; i < list1.length; i++) System.out.print(list1[i] + " "); } } a. 1 2 3 b. 1 1 1 c. 0 1 2 d. 0 1 3 Key:c list2 = list1 makes list2 point to the same array as list1. See Figure 7.4. # 23. Analyze the following code: public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4}; int[] y = x; x = new int[2]; for (int i = 0; i < x.length; i++) System.out.print(x[i] + " "); } } a. b.

The program displays 1 2 3 4 The program displays 0 0

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


..

c. The program displays 0 0 3 4 d. The program displays 0 0 0 0 Key:b y is {1, 2, 3, 4} and x is {0, 0} # Section 7.6 Passing Arrays to Methods 29. Show the output of the following code: public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4, 5}; increase(x); int[] y = {1, 2, 3, 4, 5}; increase(y[0]); System.out.println(x[0] + " " + y[0]); } public static void increase(int[] x) { for (int i = 0; i < x.length; i++) x[i]++; } public static void increase(int y) { y++; } } a. 00 b. 11 c. 22 d. 21 e. 12 Key:d Invoking increase(x) passes the reference of the array to the method. Invoking increase(y[0]) passes the value 1 to the method. The value y[0] outside the method is not changed. # 31.

Analyze the following code:

public class Test { public static void main(String[] args) { int[] oldList = {1, 2, 3, 4, 5}; reverse(oldList); for (int i = 0; i < oldList.length; i++) System.out.print(oldList[i] + " "); } public static void reverse(int[] list) { int[] newList = new int[list.length]; for (int i = 0; i < list.length; i++) newList[i] = list[list.length - 1 - i]; list = newList;


..

} } a. The program displays 1 2 3 4 5. b. The program displays 1 2 3 4 5 and then raises an ArrayIndexOutOfBoundsException. c. The program displays 5 4 3 2 1. d. The program displays 5 4 3 2 1 and then raises an ArrayIndexOutOfBoundsException. Key:a The contents of the array oldList have not been changed as result of invoking the reverse method. # 32. Analyze the following code: public class Test1 { public static void main(String[] args) { xMethod(new double[]{3, 3}); xMethod(new double[5]); xMethod(new double[3]{1, 2, 3}); } public static void xMethod(double[] a) { System.out.println(a.length); } } a. The program has a compile error because xMethod(new double[]{3, 3}) is incorrect. b. The program has a compile error because xMethod(new double[5]) is incorrect. c. The program has a compile error because xMethod(new double[3]{1, 2, 3}) is incorrect. d. The program has a runtime error because a is null. Key:c new double[3]{1, 2, 3} should be replaced by new double[]{1, 2, 3}) (anonymous array). # 11.

What would be the result of attempting to compile and run the following code?

public class Test { public static void main(String[] args) { double[] x = new double[]{1, 2, 3}; System.out.println("Value is " + x[1]); } } a. The program has a compile error because the syntax new double[]{1, 2, 3} is wrong and it should be replaced by {1, 2, 3}. b. The program has a compile error because the syntax new double[]{1, 2, 3} is wrong and it should be replaced by new double[3]{1, 2, 3}; c. The program has a compile error because the syntax new double[]{1, 2, 3} is wrong and it should be replaced by new double[]{1.0, 2.0, 3.0}; d. The program compiles and runs fine and the output "Value is 1.0" is printed. e. The program compiles and runs fine and the output "Value is 2.0" is printed. Key:e new double[]{1, 2, 3} is correct. double[] x = new double[]{1, 2, 3} is equivalent to double[] x = {1, 2, 3}; # 30.

Do the following two programs produce the same result?

Program I: public class Test { public static void main(String[] args) {


..

int[] list = {1, 2, 3, 4, 5}; for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); } } Program II: public class Test { public static void main(String[] args) { int[] oldList = {1, 2, 3, 4, 5}; reverse(oldList); for (int i = 0; i < oldList.length; i++) System.out.print(oldList[i] + " "); } public static void reverse(int[] list) { int[] newList = new int[list.length]; for (int i = 0; i < list.length; i++) newList[i] = list[list.length - 1 - i]; list = newList; } } a. Yes b. No Key:a In Program II, the reference of newList is assigned to list. This does not change the reference for list after calling reverse. So, list is not changed after the call. # 28. When you pass an array to a method, the method receives a. a copy of the array b. a copy of the first element c. the reference of the array d. the length of the array Key:c See the code animation for TestArrayArguments.

.

# 33. The JVM stores the array in an area of memory, called , which is used for dynamic memory allocation where blocks of memory are allocated and freed in an arbitrary order. a. stack b. heap c. memory block d. dynamic memory key:b See the Note after Figure 5.7. # 19. Which of the following is correct? a. String[] list = new String{"red", "yellow", "green"}; b. String[] list = new String[]{"red", "yellow", "green"}; c. String[] list = {"red", "yellow", "green"}; d. String list = {"red", "yellow", "green"}; e. String list = new String{"red", "yellow", "green"}; Key:bc See the note before CodeAnimation TestArrayArguments.


..

# Section 7.7 Returning an Array from a Method 34. When you return an array from a method, the method returns a. a copy of the array b. a copy of the first element c. the reference of the array d. the length of the array Key:c See the Key Point of this section.

.

# 35. Suppose a method p has the following heading: public static int[] p() What return statement may be used in p()? a. return 1; b. return {1, 2, 3}; c. return int[]{1, 2, 3}; d. return new int[]{1, 2, 3}; Key:d The correct syntax to create an array is new int[]{1, 2, 3}. # 36. The reverse method is defined in the textbook. What is list1 after executing the following statements? int[] list1 = {1, 2, 3, 4, 5, 6}; list1 = reverse(list1); a. list1 is 1 2 3 4 5 6 b. list1 is 6 5 4 3 2 1 c. list1 is 0 0 0 0 0 0 d. list1 is 6 6 6 6 6 6 key:b The reverse method in this section returns a new array that is the reversal of the source. # 37. The reverse method is defined in this section. What is list1 after executing the following statements? int[] list1 = {1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); a. list1 is 1 2 3 4 5 6 b. list1 is 6 5 4 3 2 1 c. list1 is 0 0 0 0 0 0 d. list1 is 6 6 6 6 6 6 key:a See the reverse method in this section. # Section 7.9 Variable-Length Argument Lists 38. Which of the following declarations are correct? a. public static void print(String... strings, double... numbers) b. public static void print(double... numbers, String name) c. public static double... print(double d1, double d2)


..

d. public static void print(double... numbers) e. public static void print(int n, double... numbers) Key:de Only one variable-length parameter may be specified in a method and this parameter must be the last parameter. The method return type cannot be a variable-length parameter. # 39. Which of the following statements are correct to invoke the printMax method in Listing 7.5 in the textbook? a. printMax(1, 2, 2, 1, 4); b. printMax(new double[]{1, 2, 3}); c. printMax(1.0, 2.0, 2.0, 1.0, 4.0); d. printMax(new int[]{1, 2, 3}); Key:abc The last one printMax(new int[]{1, 2, 3}); is incorrect, because the array must of the double[] type. # Section 7.10 Searching Arrays 40. For the binarySearch method in Section 7.10.2, what is low and high after the first iteration of the while loop when invoking binarySearch(new int[]{1, 4, 6, 8, 10, 15, 20}, 11)? a. low is 0 and high is 6 b. low is 5 and high is 5 c. low is 3 and high is 6 d. low is 4 and high is 6 e. low is 6 and high is 5 key:d See Listing 7.7. # 41. If a key is not in the list, the binarySearch method returns a. insertion point b. insertion point - 1 c. -(insertion point + 1) d. -insertion point key:c See Listing 7.7.

.

# Section 7.11 Sorting Arrays 42. Use the selectionSort method presented in this section to answer this question. Assume list is {3.1, 3.1, 2.5, 6.4, 2.1}, what is the content of list after the first iteration of the outer loop in the method? a. 3.1, 3.1, 2.5, 6.4, 2.1 b. 2.5, 3.1, 3.1, 6.4, 2.1 c. 2.1, 2.5, 3.1, 3.1, 6.4 d. 3.1, 3.1, 2.5, 2.1, 6.4 e. 2.1, 3.1, 2.5, 6.4, 3.1 Key:e See Listing 7.8. # 43. Use the selectionSort method presented in this section to answer this question. What is list1 after executing the following statements? double[] list1 = {3.1, 3.1, 2.5, 6.4}; selectionSort(list1); a. b.

list1 is 3.1, 3.1, 2.5, 6.4 list1 is 2.5, 3.1, 3.1, 6.4


..

c. list1 is 6.4, 3.1, 3.1, 2.5 d. list1 is 3.1, 2.5, 3.1, 6.4 Key:b See Listing 7.7. # Section 7.12 The Arrays Class 44. The method sorts the array scores of the double[] type. a. java.util.Arrays(scores) b. java.util.Arrays.sorts(scores) c. java.util.Arrays.sort(scores) d. java.util.Arrays.sortArray(scores) Key:c See the second paragraph in this section. # 45. Assume int[] scores = {1, 20, 30, 40, 50}, what value does java.util.Arrays.binarySearch(scores, 30) return? a. 0 b. -1 c. 1 d. 2 e. -2 Key:d See the fourth paragraph in this section. # 46. Assume int[] scores = {1, 20, 30, 40, 50}, what value does java.util.Arrays.binarySearch(scores, 3) return? a. 0 b. -1 c. 1 d. 2 e. -2 Key:e The binarySearch method returns the index of the search key if it is contained in the list. Otherwise, it returns insertionPoint - 1. The insertion point is the point at which the key would be inserted into the list. In this case the insertion point is 1. Note that the array index starts from 0. # 47. Assume int[] scores = {1, 20, 30, 40, 50}, what is the output of System.out.println(java.util.Arrays.toString(scores))? a. {1, 20, 30, 40, 50} b. [1, 20, 30, 40, 50] c. {1 20 30 40 50} d. [1 20 30 40 50] Key:b See the toString method in this section. # Section 7.13 Command-Line Arguments 48. How can you get the word "abc" in the main method from the following call? java Test "+" 3 "abc" 2 a. args[0] b. args[1] c. args[2] d. args[3] Key:c See Section 7.13.2. #


..

49. Given the following program: public class Test { public static void main(String[] args) { for (int i = 0; i < args.length; i++) { System.out.print(args[i] + " "); } } } What is the output, if you run the program using java Test 1 2 3 a. 3 b. 1 c. 123 d. 1 2 Key:c See Section 7.13.2. # 50. Which code fragment would correctly identify the number of arguments passed via the command line to a Java application, excluding the name of the class that is being invoked? a. int count = args.length; b. int count = args.length - 1; c. int count = 0; while (args[count] != null) count ++; d. int count=0; while (!(args[count].equals(""))) count ++; Key:a See LiveExample 7.9. # 51. Which correctly creates an array of five empty Strings? a. String[] a = new String [5]; b. String[] a = {"", "", "", "", ""}; c. String[5] a; d. String[ ] a = new String [5]; for (int i = 0; i < 5; a[i++] = null); Key:b See LiveExample 7.9. # 52. Analyze the following code: public class Test { public static void main(String argv[]) { System.out.println("argv.length is " + argv.length); } } a. The program has a compile error because String argv[] is wrong and it should be replaced by String[] args. b. The program has a compile error because String argv[] is wrong and it should be replaced by String args[]. c. If you run this program without passing any arguments, the program would have a runtime error because argv is null. d. If you run this program without passing any arguments, the program would display argv.length is 0. Key:d The parameter for the main method is an array of String. The declaration String argv[] is correct. When you run the program without passing arguments, argv is new String[0]. Thus, argv.length is 0. See the NOTE box in the section, "Passing Arguments to Java Programs."


# 53. Which of the following is the correct header of the main method? a. public static void main(String[] args) b. public static void main(String args[]) c. public static void main(String[] x) d. public static void main(String x[]) e. static void main(String[] args) Key:abcd e is incorrect because the main method must be public.

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


Chapter 8 Multidimensional Arrays Section 8.2 Two-Dimensional Array Basics Section 8.2.1 Declaring Variables of Two-Dimensional Arrays and Creating Two-Dimensional Arrays 1. Which of the following statements are correct? a. char[][] charArray = {'a', 'b'}; b. char[2][2] charArray = {{'a', 'b'}, {'c', 'd'}}; c. char[2][] charArray = {{'a', 'b'}, {'c', 'd'}}; d. char[][] charArray = {{'a', 'b'}, {'c', 'd'}}; Key:d See Section 8.2.1. # 3. What is the index variable for the element at the first row and first column in array a? a. a[0][0] b. a[1][1] c. a[0][1] d. a[1][0] Key:a Array index starts from 0. # 4.

When you create an array using the following statement, the element values are automatically initialized to 0.

int[][] matrix = new int[5][5]; a. True b. False Key:a For a number array, the default value is 0. # Section 8.2.2 Obtaining the Lengths of Two-Dimensional Arrays 2. Assume double[][] x = new double[4][5], what are x.length and x[2].length? a. 4 and 4 b. 4 and 5 c. 5 and 4 d. 5 and 5 Key:b See Section 8.2.2. # 5. How many elements are in array matrix (int[][] matrix = new int[5][5])? a. 14 b. 20 c. 25 d. 30 Key:c It is a square matrix 5 by 5. # 7. a. b. c. d. e.

Assume int[][] x = {{1, 2}, {3, 4}, {5, 6}}, what are x.length are x[0].length? 2 and 1 2 and 2 3 and 2 2 and 3 3 and 3 ..


Key:c x.length is the number of the rows. x[0].length is the number of the elements in the first row. # Section 8.2.3 Ragged Arrays 6. Analyze the following code: public class Test { public static void main(String[] args) { boolean[][] x = new boolean[3][]; x[0] = new boolean[1]; x[1] = new boolean[2]; x[2] = new boolean[3]; System.out.println("x[2][2] is " + x[2][2]); } } a. The program has a compile error because new boolean[3][] is wrong. b. The program has a runtime error because x[2][2] is null. c. The program runs and displays x[2][2] is null. d. The program runs and displays x[2][2] is true. e. The program runs and displays x[2][2] is false. Key:e x is a ragged array. (See the section on Ragged Array) x[2] has three elements with default value false. # 8. Assume int[][] x = {{1, 2}, {3, 4, 5}, {5, 6, 5, 9}}, what are x[0].length, x[1].length, and x[2].length? a. 2, 3, and 3 b. 2, 3, and 4 c. 3, 3, and 3 d. 3, 3, and 4 e. 2, 2, and 2 Key:b x[0].length, x[1].length, and x[2].length are the number of the elements in the first, second, and third rows. # Section 8.3 Processing Two-Dimensional Arrays 12. What is the output of the following code? public class Test { public static void main(String[] args) { int[][] matrix = {{1, 2, 3, 4}, {4, 5, 6, 7}, {8, 9, 10, 11}, {12, 13, 14, 15}}; for (int i = 0; i < 4; i++) System.out.print(matrix[i][1] + " "); } } a. 1234 b. 4567 c. 1 3 8 12 d. 2 5 9 13 e. 3 6 10 14 Key:d The code displays the second column in matrix. ..


# 9.

What is the output of the following program?

public class Test { public static void main(String[] args) { int[][] values = {{3, 4, 5, 1}, {33, 6, 1, 2}}; int v = values[0][0]; for (int row = 0; row < values.length; row++) for (int column = 0; column < values[row].length; column++) if (v < values[row][column]) v = values[row][column]; System.out.print(v); } } a. 1 b. 3 c. 5 d. 6 e. 33 Key:e The code finds the largest element in the values array. # 11.

What is the output of the following program?

public class Test { public static void main(String[] args) { int[][] values = {{3, 4, 5, 1 }, {33, 6, 1, 2}}; for (int row = 0; row < values.length; row++) { java.util.Arrays.sort(values[row]); for (int column = 0; column < values[row].length; column++) System.out.print(values[row][column] + " "); System.out.println(); } } } a. The program prints two rows 3 4 5 1 followed by 33 6 1 2 b. The program prints on row 3 4 5 1 33 6 1 2 c. The program prints two rows 3 4 5 1 followed by 2 1 6 33 d. The program prints two rows 1 3 4 5 followed by 1 2 6 33 e. The program prints one row 1 3 4 5 1 2 6 33 Key:d The code sorts each row. # 13. What is the output of the following code? public class Test5 { public static void main(String[] args) { int[][] matrix = {{1, 2, 3, 4}, ..


{4, 5, 6, 7}, {8, 9, 10, 11}, {12, 13, 14, 15}}; for (int i = 0; i < 4; i++) System.out.print(matrix[1][i] + " "); } } a. 1 2 3 4 b. 4 5 6 7 c. 1 3 8 12 d. 2 5 9 13 e. 3 6 10 14 Key:b The code displays the second row. # 10.

What is the output of the following program?

public class Test { public static void main(String[] args) { int[][] values = {{3, 4, 5, 1}, {33, 6, 1, 2}}; int v = values[0][0]; for (int[] list : values) for (int element : list) if (v > element) v = element; System.out.print(v); } } a. 1 b. 3 c. 5 d. 6 e. 33 Key:a The code finds the smallest element in the values array. # Section 8.4 Passing Two-Dimensional Arrays to Methods 14. Suppose a method p has the following heading. What return statement may be used in p()? public static int[][] p() a. return 1; b. return {1, 2, 3}; c. return int[]{1, 2, 3}; d. return new int[]{1, 2, 3}; e. return new int[][]{{1, 2, 3}, {2, 4, 5}}; Key:e The return type is int[][]. new int[][]{{1, 2, 3}, {2, 4, 5}} creates an array of the int[][] type. # 15. ..

What is the output of the following program?


public class Test { public static void main(String[] args) { int[][] values = {{3, 4, 5, 1}, {33, 6, 1, 2}}; for (int row = 0; row < values.length; row++) { System.out.print(m(values[row]) + " "); } } public static int m(int[] list) { int v = list[0]; for (int i = 1; i < list.length; i++) if (v < list[i]) v = list[i]; return v; } } a. 3 33 b. 11 c. 56 d. 5 33 e. 33 5 Key:d The method m returns the largest element in a one-dimensional array. # Section 8.8 Multidimensional Arrays 16. Assume double[][][] x = new double[4][5][6], what are x.length, x[2].length, and x[0][0].length? a. 4, 5, and 6 b. 6, 5, and 4 c. 5, 5, and 5 d. 4, 5, and 4 Key:a See the first part in this section. # 18. What is the output of the following code? public class Test { public static void main(String[] args) { int[][][] data = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}; System.out.print(data[1][0][0]); } } a. 1 b. 2 c. 4 d. 5 e. 6 Key:d See the first part in this section. # 19. What is the output of the following code? ..


public class Test { public static void main(String[] args) { int[][][] data = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}; System.out.print(ttt(data[0])); } public static int ttt(int[][] m) { int v = m[0][0]; for (int i = 0; i < m.length; i++) for (int j = 0; j < m[i].length; j++) if (v < m[i][j]) v = m[i][j]; return v; } } a. 1 b. 2 c. 4 d. 5 e. 6 Key:c The ttt method returns the largest element in a tw-dimensional array. data[0] is {{1, 2}, {3, 4}}. # 17. Which of the following statements are correct? a. char[][][] charArray = new char[2][2][]; b. char[2][2][] charArray = {'a', 'b'}; c. char[][][] charArray = {{'a', 'b'}, {'c', 'd'}, {'e', 'f'}}; d. char[][][] charArray = {{{'a', 'b'}, {'c', 'd'}, {'e', 'f'}}}; Key:ad In A, a three-dimensionaly array is created with the last dimensional undetermined. In D, a three dimensional array is created. The charArray.length is 1, charArray[0].length is 1, and charArray[0] contains a two-dimensional array.

..


Chapter 9 Objects and Classes Section 9.2 Defining Classes for Objects 1. represents an entity in the real world that can be distinctly identified. a. A class b. An object c. A method d. A data field Key:b See the first part of this section. # 2. is a template that defines objects of the same type. a. A class b. An object c. A method d. A data field Key:a See the first part of this section. # 3. An object is an instance of a a. program b. class c. method d. data Key:b See the first part of this section. # 4. The keyword a. public b. private c. class d. All of the above. Key:c See Figure 9.3.

.

is required to declare a class.

# Section 9.3 Example: Defining Classes and Creating Objects 16. If TestCircle.java in Listing 9.1 is compiled successfully, a. TestCircle.class is created. b. Circle.class is created. c. TestCircle.class and Circle.class are created. d. No class files are created. Key:c See Figure 9.5. # Section 9.4 Constructing Objects Using Constructors 5. is invoked to create an object. a. A constructor b. The main method c. A method with a return type d. A method with the void return type Key:a See the Key Point. # ..

.


7. Which of the following statements are true? a. Multiple constructors can be defined in a class. b. Constructors do not have a return type, not even void. c. Constructors must have the same name as the class itself. d. Constructors are invoked using the new operator when an object is created. Key:abcd Read this short section. # 9.

Analyze the following code.

class TempClass { int i; public void TempClass(int j) { int i = j; } } public class C { public static void main(String[] args) { TempClass temp = new TempClass(2); } } a. The program has a compile error because TempClass does not have a default constructor. b. The program has a compile error because TempClass does not have a constructor with an int argument. c. The program compiles fine, but it does not run because class C is not public. d. The program compiles and runs fine. Key:b The program would be fine if the void keyword is removed from public void TempClass(int j). # 6. Which of the following statements are true? a. A default constructor is provided automatically if no constructors are explicitly declared in the class. b. At least one constructor must always be defined explicitly. c. Every class has a default constructor. d. The default constructor is a no-arg constructor. Key:ad See this short section. # 8.

Analyze the following code:

public class Test { public static void main(String[] args) { A a = new A(); a.print(); } } class A { String s; A(String s) { this.s = s; } void print() { ..


System.out.println(s); } } a. The program has a compile error because class A is not a public class. b. The program has a compile error because class A does not have a default constructor. c. The program compiles and runs fine and prints nothing. d. The program would compile and run if you change A a = new A() to A a = new A("5"). Key:bd Class A does not have a no-arg constructor, so, new A() causes a compile error. If new A() is changed to new A("5"), the program will compile fine. # Section 9.5 Accessing Objects via Reference Variables 10. Given the declaration Circle x = new Circle(), which of the following statement is most accurate. a. x contains an int value. b. x contains an object of the Circle type. c. x contains a reference to a Circle object. d. You can assign an int value to x. Key:c x is a reference variable that can reference a Circle object or null if it does not reference any object. # 17. Which of the following statements are correct? a. A reference variable is an object. b. A reference variable references to an object. c. A data field in a class must be of a primitive type. d. A data field in a class can be of an object type. Key:bd (a) is wrong because a reference variable is not an object, it is a reference that points to an object. (c) is incorrect because a class may have a data field of an object type such as String. # Section 9.5.1 Accessing an Object's Data and Methods 15. Analyze the following code. public class Test { int x; public Test(String t) { System.out.println("Test"); } public static void main(String[] args) { Test test = new Test(); System.out.println(test.x); } } a. The program has a compile error because System.out.println method cannot be invoked from the constructor. b. The program has a compile error because x has not been initialized. c. The program has a compile error because you cannot create an object from the class that defines the object. d. The program has a compile error because Test does not have a default constructor. Key:d Note that a default no-arg constructor is provided only if no constructors are explicitly defined in the class. In this case, a constructor Test(String t) is already defined. So, there is no default no-arg constructor in the Test class. # Section 9.5.2 Reference Data Fields and the null Value 11. Analyze the following code. ..


public class Test { int x; public Test(String t) { System.out.println("Test"); } public static void main(String[] args) { Test test = null; System.out.println(test.x); } } a. The program has a compile error because test is not initialized. b. The program has a compile error because x has not been initialized. c. The program has a compile error because you cannot create an object from the class that defines the object. d. The program has a compile error because Test does not have a default constructor. e. The program has a runtime NullPointerException because test is null while executing test.x. Key:e test.x will raise NullPointerException, because test is null. # 12. The default value for data field of a boolean type, numeric type, object type is a. true, 1, Null b. false, 0, null c. true, 0, null d. true, 1, null e. false, 1, null Key:b See the second and third paragraph.

, respectively.

# 13. Which of the following statements are true? a. Local variables do not have default values. b. Data fields have default values. c. A variable of a primitive type holds a value of the primitive type. d. A variable of a reference type holds a reference to where an object is stored in the memory. e. You may assign an int value to a reference variable. Key:abcd See the second and third paragraph. # Section 9.5.3 Differences between Variables of Primitive Types and Reference Types 14. Analyze the following code: public class Test { public static void main(String[] args) { double radius; final double PI = 3.15169; double area = radius * radius * PI; System.out.println("Area is " + area); } } a. The program has compile errors because the variable radius is not initialized. b. The program has a compile error because a constant PI is defined inside a method. c. The program has no compile errors but will get a runtime error because radius is not initialized. d. The program compiles and runs fine. ..


Key:a radius is a local variable. It is used in radius * radius * PI, but not initialized. # Section 9.6 Using Classes From the Java Library 18. Which of the following creates an object of the Date class: A: public class Test { public Test() { new java.util.Date(); } } B: public class Test { public Test() { java.util.Date date = new java.util.Date(); } } a. A. b. B. c. Neither d. Both A and B Key:d Both (A) and (B) are fine. In A, an object is created without explicit reference. This is known as anonymous object. # 19. Which of the following statements are correct? a. When creating a Random object, you have to specify the seed or use the default seed. b. If two Random objects have the same seed, the sequence of the random numbers obtained from these two objects are identical. c. The nextInt() method in the Random class returns the next random int value. d. The nextDouble() method in the Random class returns the next random double value. Key:abcd See Figure 9.11. # 20. To obtain the distance between the points (40, 50) and (5.5, 4.4), use a. distance(40, 50, 5.5, 4.4) b. new Point2D(40, 50).distance(5.5, 4.4) c. new Point2D(40, 50).distance(new Point2D(5.5, 4.4)) d. new Point2D(5.5, 4.4).distance(40, 50) e. new Point2D(5.5, 4.4).distance(new Point2D(40, 50)) Key:bcde See Figure 9.12. # Section 9.7 Static Variables, Constants, and Methods 22. You should add the static keyword in the place of ? in Line Line 1 public class Test { Line 2 private int age; Line 3 Line 4 public ? int square(int n) { Line 5 return n * n; Line 6 } ..

.

in the following code:


Line 7 Line 8 public ? int getAge() { Line 9 return age; Line 10 } Line 11 } a. in line 4 b. in line 8 c. in both line 4 and line 8 d. none Key:a The square method should be static because it does not reference any instance data or invoke any instance method. # 26. What is the output of the second println statement in the main method? public class Foo { int i; static int s; public static void main(String[] args) { Foo f1 = new Foo(); System.out.println("f1.i is " + f1.i + " f1.s is " + f1.s); Foo f2 = new Foo(); System.out.println("f2.i is " + f2.i + " f2.s is " + f2.s); Foo f3 = new Foo(); System.out.println("f3.i is " + f3.i + " f3.s is " + f3.s); } public Foo() { i++; s++; } } a. f2.i is 1 f2.s is 1 b. f2.i is 1 f2.s is 2 c. f2.i is 2 f2.s is 2 d. f2.i is 2 f2.s is 1 Key:b Every Foo object has its own instance variable i, so f2.i is 1. The static variable j is shared by all Foo objects. When f1 is created, j becomes 1. When f2 is created, j becomes 2. # 28. What code may be filled in the blank without causing syntax or runtime errors: public class Test { java.util.Date date; public static void main(String[] args) { Test test = new Test(); System.out.println( } } a. test.date b. date c. test.date.toString() ..

);


d. date.toString() Key:a b and d cause compile errors because date is an instance variable and cannot be accessed from static context. c is wrong because test.date is null, causing NullPointerException. # 23. A method that is associated with an individual object is called a. a static method b. a class method c. an instance method d. an object method Key:c See the third paragraph.

.

# 24. To declare a constant MAX_LENGTH as a member of the class, you write a. final static MAX_LENGTH = 99.98; b. final static float MAX_LENGTH = 99.98; c. static double MAX_LENGTH = 99.98; d. final double MAX_LENGTH = 99.98; e. final static double MAX_LENGTH = 99.98; Key:e Constants are shared by all objects. # 25.

Analyze the following code.

public class Test { public static void main(String[] args) { int n = 2; xMethod(n); System.out.println("n is " + n); } void xMethod(int n) { n++; } } a. The code has a compile error because xMethod does not return a value. b. The code has a compile error because xMethod is not declared static. c. The code prints n is 1. d. The code prints n is 2. e. The code prints n is 3. Key:b xMethod is declared an instance method. It must be called from an object. So, the program has a compile error in line 4. # 27. What is the output of the third println statement in the main method? public class Foo { int i; static int s; public static void main(String[] args) { Foo f1 = new Foo(); System.out.println("f1.i is " + f1.i + " f1.s is " + f1.s); Foo f2 = new Foo(); ..


System.out.println("f2.i is " + f2.i + " f2.s is " + f2.s); Foo f3 = new Foo(); System.out.println("f3.i is " + f3.i + " f3.s is " + f3.s); } public Foo() { i++; s++; } } a. f3.i is 1 f3.s is 1 b. f3.i is 1 f3.s is 2 c. f3.i is 1 f3.s is 3 d. f3.i is 3 f3.s is 1 e. f3.i is 3 f3.s is 3 Key:c i is an instance variable and s is static, shared by all objects of the Foo class. # 29.

Suppose the xMethod() is invoked in the following constructor in a class, xMethod() is

in the class.

public MyClass() { xMethod(); } a. a static method b. an instance method c. a static method or an instance method Key:c Since xMethod() is not invoked from an object, it must be a static method. # 30. Suppose the xMethod() is invoked from a main method in a class as follows, xMethod() is class. public static void main(String[] args) { xMethod(); } a. a static method b. an instance method c. a static method or an instance method Key:a Since xMethod() is not invoked from an object, it must be a static method. # 21. Variables that are shared by every instance of a class are a. public variables b. private variables c. instance variables d. class variables Key:d See the third paragraph. # Section 9.8 Visibility Modifiers 32. Analyze the following code:

..

.

in the


public class Test { public static void main(String args[]) { NClass nc = new NClass(); nc.t = nc.t++; } } class NClass { int t; private NClass() { } } a. The program has a compile error because the NClass class has a private constructor. b. The program does not compile because the parameter list of the main method is wrong. c. The program compiles, but has a runtime error because t has no initial value. d. The program compiles and runs fine. Key:a You cannot use the private constructor to create an object. # 33.

Analyze the following code:

public class Test { private int t; public static void main(String[] args) { int x; System.out.println(t); } } a. The variable t is not initialized and therefore causes errors. b. The variable t is private and therefore cannot be accessed in the main method. c. t is non-static and it cannot be referenced in a static context in the main method. d. The variable x is not initialized and therefore causes errors. e. The program compiles and runs fine. Key:c t is an instance data field. The main method is static. You cannot access t directly from the main method. # 34. Analyze the following code and choose the best answer: public class Foo { private int x; public static void main(String[] args) { Foo foo = new Foo(); System.out.println(foo.x); } } a. Since x is private, it cannot be accessed from an object foo. b. Since x is defined in the class Foo, it can be accessed by any method inside the class without using an object. You can write the code to access x without creating an object such as foo in this code. c. Since x is an instance variable, it cannot be directly used inside a main method. However, it can be accessed through an object such as foo in this code. d. You cannot create a self-referenced object; that is, foo is created inside the class Foo. Key:c (A) is incorrect, since x can be accessed by an object of Foo inside the Foo class. (B) is incorrect because x is ..


non-static, it cannot be accessed in the main method without creating an object. (D) is incorrect, since it is permissible to create an instance of the class within the class. The best choice is (C). # 31. To prevent a class from being instantiated, a. don't use any modifiers on the constructor. b. use the public modifier on the constructor. c. use the private modifier on the constructor. d. use the static modifier on the constructor. Key:c See the last note in this section. # Section 9.9 Data Field Encapsulation 37. Which is the advantage of encapsulation? a. Only public methods are needed. b. Making the class final causes no consequential changes to other code. c. It enables changes to the implementation without changing a class's contract and causes no consequential changes to other code. d. It enables changes to a class's contract without changing the implementation and causes no consequential changes to other code. Key:c See the bullet items at the beginning of this section. # 35. Which of the following statements are true? a. Use the private modifier to encapsulate data fields. b. Encapsulating data fields makes the program easy to maintain. c. Encapsulating data fields makes the program short. d. Encapsulating data fields helps prevent programming errors. Key:abd Read the text in this section. # 36. Suppose you wish to provide an accessor method for a boolean property finished, what should the signature of this method? a. public void getFinished() b. public boolean getFinished() c. public boolean isFinished() d. public void isFinished() Key:c See the signature for a boolean getter method in this section. # 65. Encapsulation means . a. that data fields should be declared private b. that a class can extend another class c. that a variable of supertype can refer to a subtype object d. that a class can contain another class Key:a See the paragraph after the bullet items. # Section 9.10 Passing Objects to Methods 39. What is the value of myCount.count displayed? public class Test { public static void main(String[] args) { Count myCount = new Count(); ..


int times = 0; for (int i = 0; i < 100; i++) increment(myCount, times); System.out.println( "myCount.count = " + myCount.count); System.out.println("times = "+ times); } public static void increment(Count c, int times) { c.count++; times++; } } class Count { int count; Count(int c) { count = c; } Count() { count = 1; } } a. 101 b. 100 c. 99 d. 98 Key:a See Listing 9.10. # 40.

What is the value of times displayed?

public class Test { public static void main(String[] args) { Count myCount = new Count(); int times = 0; for (int i = 0; i < 100; i++) increment(myCount, times); System.out.println( "myCount.count = " + myCount.count); System.out.println("times = "+ times); } public static void increment(Count c, int times) { c.count++; times++; } } ..


class Count { int count; Count(int c) { count = c; } Count() { count = 1; } } a. 101 b. 100 c. 99 d. 98 e. 0 Key:e See Listing 9.10. # 41. What is the output of the following program? import java.util.Date; public class Test { public static void main(String[] args) { Date date = new Date(1234567); m1(date); System.out.print(date.getTime() + " "); m2(date); System.out.println(date.getTime()); } public static void m1(Date date) { date = new Date(7654321); } public static void m2(Date date) { date.setTime(7654321); } } a. 1234567 1234567 b. 1234567 7654321 c. 7654321 1234567 d. 7654321 7654321 Key:b See Listing 9.10. # 38. When invoking a method with an object argument, a. the contents of the object b. a copy of the object c. the reference of the object d. the object is copied, then the reference of the copied object ..

is passed.


Key: c See the Key Point. # Section 9.11 Array of Objects 42. Given the declaration Circle[] x = new Circle[10], which of the following statement is most accurate? a. x contains an array of ten int values. b. x contains an array of ten objects of the Circle type. c. x contains a reference to an array and each element in the array can hold a reference to a Circle object. d. x contains a reference to an array and each element in the array can hold a Circle object. Key:c See the second paragraph of this section. # 43. Assume java.util.Date[] dates = new java.util.Date[10], which of the following statements are true? a. dates is null. b. dates[0] is null. c. dates = new java.util.Date[5] is fine, which assigns a new array to dates. d. dates = new Date() is fine, which creates a new Date object and assigns to dates. Key:bc In A, An array is assigned to dates. So dates is not null. In D, dates is of the type Date[]. You cannot assign a Date object to it. B and C are correct. # Section 9.12 Immutable Objects and Classes 44. Which of the following statements are true about an immutable object? a. The contents of an immutable object cannot be modified. b. All properties of an immutable object must be private. c. All properties of an immutable object must be of primitive types. d. A readable object type property in an immutable object must also be immutable. e. An immutable object contains no mutator methods. Key:abde Read this short section. # Section 9.13 Scope of Variables 45. What is the output for the first print statement in the main method? public class Foo { static int i = 0; static int j = 0; public static void main(String[] args) { int i = 2; int k = 3; { int j = 3; System.out.println("i + j is " + i + j); } k = i + j; System.out.println("k is " + k); System.out.println("j is " + j); } } a. b. c. ..

i + j is 5 i + j is 6 i + j is 22


d. i + j is 23 Key:d The first + operator in the expression "i + j is " + i + j is evaluated. # 46.

What is the output for the second print statement in the main method?

public class Foo { static int i = 0; static int j = 0; public static void main(String[] args) { int i = 2; int k = 3; { int j = 3; System.out.println("i + j is " + i + j); } k = i + j; System.out.println("k is " + k); System.out.println("j is " + j); } } a. k is 0 b. k is 1 c. k is 2 d. k is 3 Key:c When computing k = i + j, i is 2 and j is 0. # 47. What is the output for the third print statement in the main method? public class Foo { static int i = 0; static int j = 0; public static void main(String[] args) { int i = 2; int k = 3; { int j = 3; System.out.println("i + j is " + i + j); } k = i + j; System.out.println("k is " + k); System.out.println("j is " + j); } } a. j is 0 b. j is 1 c. j is 2 d. j is 3 Key:a j is declared and assigned 0 as a static variable. It is redeclared and assigned 3 as a local variable. The scope of ..


the local variable ends at the end of the block before it is printed. So, when it is printed in the third print statement, the static variable j is used. # 48. You can declare two variables with the same name in . a. a method, one as a formal parameter and the other as a local variable b. a block c. two nested blocks in a method (two nested blocks means one being inside the other) d. different methods in a class Key:d Local variables in different methods are complete unrelated. # Section 9.14 The this Keyword 49. Analyze the following code: class Circle { private double radius; public Circle(double radius) { radius = radius; } } a. The program has a compile error because it does not have a main method. b. The program will compile, but you cannot create an object of Circle with a specified radius. The object will always have radius 0. c. The program has a compile error because you cannot assign radius to radius. d. The program does not compile because Circle does not have a default constructor. Key:b You have replaced radius = radius by this.radius = radius # Section 9.14.1 Using this to Reference Data Fileds 51. Which of the following can be placed in the blank line in the following code? public class Test { private int id; public void m1() { .id = 45; } } a. this b. Test c. self d. This Key:a id is an instance data field. # Section 9.14.2 Using this to Invoke a Constructor 50. Analyze the following code: class Test { private double i;

..


public Test(double i) { this.t(); this.i = i; } public Test() { System.out.println("Default constructor"); this(1); } public void t() { System.out.println("Invoking t"); } } a. this.t() may be replaced by t(). b. this.i may be replaced by i. c. this(1) must be called before System.out.println("Default constructor"). d. this(1) must be replaced by this(1.0). Key:ac In A, See Section 9.14.1. Correct. There are total two correct choices. In B, See Section 9.14.1. In C, See Section 9.14.2. Correct. There are total two correct choices. In D, this(1.0) will be same as this(1) in this case.

..


Chapter 10 Object-Oriented Thinking Section 10.4 Class Relationships 1. is attached to the class of the composing class to denote the aggregation relationship with the composed object. a. An empty diamond b. A solid diamond c. An empty oval d. A solid oval Key:a See Figure 10.6. # 2. An aggregation relationship is usually represented as a. a data field/the aggregating class b. a data field/the aggregated class c. a method/the aggregating class d. a method/the aggregated class Key:a See Figure 10.7.

in

.

# 67. Composition means . a. that data fields should be declared private a. that data fields should be declared private b. that a class extends another class c. that a variable of supertype refers to a subtype object d. that a class contains a data field that references another object Key:d See Section 10.4.2. # Section 10.7 Processing Primitive Data Type Values as Objects 3. Which of the following statements will convert a string s into i of int type? a. i = Integer.parseInt(s); b. i = (new Integer(s)).intValue(); c. i = Integer.valueOf(s).intValue(); d. i = Integer.valueOf(s); e. i = (int)(Double.parseDouble(s)); Key:abcde All fine. d performs an auto conversion from an Integer object to int. # 4. Which of the following statements will convert a string s into a double value d? a. d = Double.parseDouble(s); b. d = (new Double(s)).doubleValue(); c. d = Double.valueOf(s).doubleValue(); d. All of the above. Key:d All are fine. a is preferred because it does not have to create an object. # 6. Which of the following statements are correct? a. Integer.parseInt("12", 2); b. Integer.parseInt(100); c. Integer.parseInt("100"); d. Integer.parseInt(100, 16); e. Integer.parseInt("345", 8); ..


Key:ce A is incorrect because 12 is not a binary number. (B) and (D) are incorrect because the first argument in the parseInt method must be a string. # 7. What is the output of Integer.parseInt("10", 2)? a. 1; b. 2; c. 10; d. Invalid statement; Key:b Based on 2, 10 is 2 in decimal. # 5. Which of the following statements convert a double value d into a string s? a. s = Double.valueOf(d).toString(); b. s = d; c. s = Double.valueOf(d).stringOf(); d. s = String.stringOf(d); e. s = d + ""; Key:ae In a, Double.valueOf(d) creates a Double object for d and the toString() method returns the string representation for the object. In E, d is concatenated with "". # Section 10.8 Automatic Conversion Between Primitive Types and Wrapper Class Types 8. You may directly assign a primitive data type value to a wrapper object. This is called a. auto boxing b. auto unboxing c. auto conversion d. auto casting Key:a See the first paragraph. # 9. Analyze the following code. Line 1: Integer[] intArray = {1, 2, 3}; Line 2: int i = intArray[0] + intArray[1]; Line 3: int j = i + intArray[2]; Line 4: double d = intArray[0]; a. It is OK to assign 1, 2, 3 to an array of Integer objects in JDK 1.5. b. It is OK to automatically convert an Integer object to an int value in Line 2. c. It is OK to mix an int value with an Integer object in an expression in Line 3. d. Line 4 is OK. An int value from intArray[0] object is assigned to a double variable d. Key:abcd See the diagram in this section. # Section 10.9 The BigInteger and BigDecimal Classes 10. To create an instance of BigInteger for 454, use a. BigInteger(454); b. new BigInteger(454); c. BigInteger("454"); d. new BigInteger("454"); Key:ad See the first paragraph. # 13. To add BigInteger b1 to b2, you write ..

.

.


a. b1.add(b2); b. b2.add(b1); c. b2 = b1.add(b2); d. b2 = b2.add(b1); e. b1 = b2.add(b1); Key:cd Please note that b2.add(b1) returns a new BigInteger. b2 is not changed. Only (C) and (D) will assign the new big integer to b2. # 14. What is the output of the following code? public class Test { public static void main(String[] args) { java.math.BigInteger x = new java.math.BigInteger("3"); java.math.BigInteger y = new java.math.BigInteger("7"); x.add(y); System.out.println(x); } } a. 3 b. 4 c. 10 d. 11 Key:a Note taht x.add(y) does not change the content of x. # 11. To create an instance of BigDecimal for 454.45, use a. BigDecimal(454.45); b. new BigDecimal(454.45); c. BigDecimal("454.45"); d. new BigDecimal("454.45"); Key:bd # 12. BigInteger and BigDecimal are immutable. a. true b. false Key:a See the first paragraph in this section. # 15. To divide BigDecimal b1 by b2 and assign the result to b1, you write a. b1.divide(b2); b. b2.divide(b1); c. b1 = b1.divide(b2, 20, RoundingMode.HALF_UP); d. b1 = b2.divide(b1, 20, RoundingMode.HALF_UP); e. b2 = b2.divide(b1, 20, RoundingMode.HALF_UP); Key:c See the first paragraph in this section. # 16. Which of the following classes are immutable? a. Integer b. Double c. BigInteger d. BigDecimal ..

.


e. String Key:abcde All the number classes and the String class are immutable. # 17. Which of the following statements are correct? a. new java.math.BigInteger("343"); b. new java.math.BigDecimal("343.445"); c. new java.math.BigInteger(343); d. new java.math.BigDecimal(343.445); Key:abd The constructor for BigDecimal has to be new BigDecimal("number_string"). # Section 10.10 The String Class 18. Which of the following statements is preferred to create a string "Welcome to Java"? a. String s = "Welcome to Java"; b. String s = new String("Welcome to Java"); c. String s; s = "Welcome to Java"; d. String s; s = new String("Welcome to Java"); Key:a (a) is better than (b) because the string created in (a) is interned. Since strings are immutable and are ubiquitous in programming, to improve efficiency and save memory, the JVM uses a unique instance for string literals with the same character sequence. Such an instance is called interned. The JVM (a) is simpler than (c). # 27.

Analyze the following code.

class Test { public static void main(String[] args) { String s; System.out.println("s is " + s); } } a. The program has a compile error because s is not initialized, but it is referenced in the println statement. b. The program has a runtime error because s is not initialized, but it is referenced in the println statement. c. The program has a runtime error because s is null in the println statement. d. The program compiles and runs fine. Key:a s is a local variable. Before its use, a value must be assigned to it. # Section 10.10.1 Immutable Strings and Interned Strings 19. What is the output of the following code? public class Test { public static void main(String[] args) { String s1 = "Welcome to Java!"; String s2 = s1; if (s1 == s2) System.out.println( "s1 and s2 reference to the same String object"); else System.out.println( "s1 and s2 reference to different String objects"); } } ..


a. s1 and s2 reference to the same String object b. s1 and s2 reference to different String objects Key:a s2 = s1 assigns s1 to s2. Now s1 and s2 have the same references. # 20.

What is the output of the following code?

public class Test { public static void main(String[] args) { String s1 = "Welcome to Java!"; String s2 = "Welcome to Java!"; if (s1 == s2) System.out.println( "s1 and s2 reference to the same String object"); else System.out.println( "s1 and s2 reference to different String objects"); } } a. s1 and s2 reference to the same String object b. s1 and s2 reference to different String objects Key:a Since strings are immutable and are ubiquitous in programming, to improve efficiency and save memory, the JVM uses a unique instance for string literals with the same character sequence. Such an instance is called interned. # 21.

What is the output of the following code?

public class Test { public static void main(String[] args) { String s1 = new String("Welcome to Java!"); String s2 = new String("Welcome to Java!"); if (s1 == s2) System.out.println( "s1 and s2 reference to the same String object"); else System.out.println( "s1 and s2 reference to different String objects"); } } a. s1 and s2 reference to the same String object b. s1 and s2 reference to different String objects Key:b s1 and s2 are two difference objects. They have the same content, but are created using the new operator. # 22.

What is the output of the following code?

public class Test { public static void main(String[] args) { String s1 = new String("Welcome to Java!"); String s2 = new String("Welcome to Java!"); if (s1.equals(s2)) ..


System.out.println("s1 and s2 have the same contents"); else System.out.println("s1 and s2 have different contents"); } } a. s1 and s2 have the same contents b. s1 and s2 have different contents Key:a s1 and s2 are two difference objects, but they have the same content. # 23.

What is the output of the following code?

public class Test { public static void main(String[] args) { String s1 = new String("Welcome to Java!"); String s2 = s1.toUpperCase(); if (s1 == s2) System.out.println("s1 and s2 reference to the same String object"); else if (s1.equals(s2)) System.out.println("s1 and s2 have the same contents"); else System.out.println("s1 and s2 are of different objects"); } } a. s1 and s2 reference to the same String object b. s1 and s2 have the same contents c. s1 and s2 are of different objects Key:c s1.toUpperCase() returns a new object. # 24.

What is the output of the following code?

public class Test { public static void main(String[] args) { String s1 = new String("Welcome to Java"); String s2 = s1; s1 += "and Welcome to HTML"; if (s1 == s2) System.out.println( "s1 and s2 reference to the same String object"); else System.out.println( "s1 and s2 reference to different String objects"); } } a. s1 and s2 reference to the same String object b. s1 and s2 reference to different String objects Key:b s1 += "and Welcome to HTML"; obtains a new object in s1. So, s1 and s2 are two objects. # 25. Suppose s1 and s2 are two strings. Which of the following statements or expressions are incorrect? ..


a. String s = new String("new string"); b. String s3 = s1 + s2 c. s1 >= s2 d. int i = s1.length e. s1.charAt(0) = '5' Key:cde Strings cannot be compared using relational operators (<, ≤, >, ≥). The length() is a method for strings. Cannot set a character in a string. So, C, D, and E are incorrect. # Section 10.10.2 Replacing and Splitting Strings 26. What is the output of the following code? String s = "University"; s.replace("i", "ABC"); System.out.println(s); a. UnABCversity b. UnABCversABCty c. UniversABCty d. University Key:d No method in the String class can change the content of the string. String is an immutable class. # 30. Assume s is "ABCABC", the method returns a new string "aBCaBC". a. s.toLowerCase(s) b. s.toLowerCase() c. s.replace('A', 'a') d. s.replace('a', 'A') e. s.replace("ABCABC", "aBCaBC") Key:ce In (C), 'A' is replaced by a. In (E), "ABCABC" is replaced by "aBCaBC". # 35. What is displayed by the following code? public static void main(String[] args) { String[] tokens = "Welcome to Java".split("o"); for (int i = 0; i < tokens.length; i++) { System.out.print(tokens[i] + " "); } } a. Welcome to Java b. Welc me to Java c. Welc me t Java d. Welcome t Java Key:c "Welcome to Java".split("o") splits the string into {"Welc", "me t", " Java"}. # 34. What is displayed by the following statement? System.out.println("Java is neat".replaceAll("is", "AAA")); a. JavaAAAneat b. JavaAAA neat c. Java AAA neat d. Java AAAneat ..


Key:c "is" replaced by "AAA" in "Java is neat". So "Java is neat".replaceAll("is", "AAA") returns "Java AAA neat". # Section 10.10.3 Matching, Replacing, and Splitting by Patterns 36. What is displayed by the following code? System.out.print("Hi, ABC, good".matches("ABC ") + " "); System.out.println("Hi, ABC, good".matches(".*ABC.*")); a. false false b. true false c. true true d. false true Key:d "Hi, ABC, good" does not match "ABC ". "Hi, ABC, good" matches the regex ".*ABC.*". The regex .* means zero or more any characters. # 37. What is displayed by the following code? System.out.print("A,B;C".replaceAll(",;", "#") + " "); System.out.println("A,B;C".replaceAll("[,;]", "#")); a. A B C A#B#C b. A#B#C A#B#C c. A,B;C A#B#C d. ABCABC Key:c The regex [,;] means character , or ;. "A,B;C".replaceAll("[,;]", "#") returns "A#B#C". # 38. What is displayed by the following code? String[] tokens = "A,B;C;D".split("[,;]"); for (int i = 0; i < tokens.length; i++) System.out.print(tokens[i] + " "); a. A,B;C;D b. ABCD c. A B C;D d. A B;C;D Key:b "A,B;C;D".split("[,;]") splits it into {"A", "B", "C", "D"}. # Section 10.10.4 Conversion between Strings and Arrays 28. Which of the following is the correct statement to return a string from an array a of characters? a. toString(a) b. new String(a) c. convertToString(a) d. String.toString(a) Key:b See the String constructor in Section 10.10. # 29. Assume s is " abc ", the method a. s.trim(s) b. trim(s) c. String.trim(s) d. s.trim() ..

returns a new string "abc".


Key:d The trim() method trims the whitespace characters from both the left and right sides of the string. # 31. Assume s is "ABCABC", the method returns an array of characters. a. toChars(s) b. s.toCharArray() c. String.toChars() d. String.toCharArray() e. s.toChars() Key:b The toCharArray() returns an array of characters from the string. # Section 10.10.5 Converting Characters and Numeric Values 32. returns a string. a. String.valueOf(123) b. String.valueOf(12.53) c. String.valueOf(false) d. String.valueOf(new char[]{'a', 'b', 'c'}) Key:abcd See Figure 10.17. # Section 10.11 The StringBuilder/StringBuffer Class 33. The following program displays . public class Test { public static void main(String[] args) { String s = "Java"; StringBuilder builder = new StringBuilder(s); change(s); System.out.println(s); } private static void change(String s) { s = s + " and HTML"; } } a. Java b. Java and HTML c. and HTML d. nothing is displayed Key:a Inside the method, the statement s = s + " and HTML" creates a new String object s, which is different from the original String object passed to the change(s) method. The original String object has not been changed. Therefore, the output from the original string is Java. # Section 10.11.1 Modifying Strings in the StringBuilder 39. Analyze the following code. class Test { public static void main(String[] args) { StringBuilder strBuilder = new StringBuilder(4); strBuilder.append("ABCDE"); System.out.println("What's strBuilder.charAt(5)? " ..


+ strBuilder.charAt(5)); } } a. The program has a compile error because you cannot specify initial capacity in the StringBuilder constructor. b. The program has a runtime error because because the builder's capacity is 4, but five characters "ABCDE" are appended into the builder. c. The program has a runtime error because the length of the string in the builder is 5 after "ABCDE" is appended into the builder. Therefore, strBuilder.charAt(5) is out of range. d. The program compiles and runs fine. Key:c The charAt method returns the character at a specific index in the string builder. The first character of a string builder is at index 0, the next at index 1, and so on. The index argument must be greater than or equal to 0, and less than the length of the string builder. # 46. The following program displays

.

public class Test { public static void main(String[] args) { String s = "Java"; StringBuilder builder = new StringBuilder(s); change(builder); System.out.println(builder); } private static void change(StringBuilder builder) { builder.append(" and HTML"); } } a. Java b. Java and HTML c. and HTML d. nothing is displayed Key:b Inside the method, the content of the StringBuilder object is changed to Java and HTML. Therefore, the output from builder is Java and HTML. # 40. Which of the following is true? a. You can add characters into a string builder. b. You can delete characters from a string builder. c. You can reverse the characters in a string buffer. d. The capacity of a string buffer can be automatically adjusted. Key:abcd Read toward the end of this section. # 42. Assume StringBuilder strBuilder is "ABCDEFG", after invoking a. strBuilder.delete(0, 3) b. strBuilder.delete(1, 3) c. strBuilder.delete(1, 4) d. strBuilder.delete(2, 4) Key:c See the discussion of the delete method in this section. # 43. Assume StringBuilder strBuilder is "ABCDEFG", after invoking ..

, strBuilder contains "AEFG".

, strBuilder contains


"ABCRRRRDEFG". a. strBuilder.insert(1, "RRRR") b. strBuilder.insert(2, "RRRR") c. strBuilder.insert(3, "RRRR") d. strBuilder.insert(4, "RRRR") Key:c See the discussion of the insert method in this section. # 44. Assume StringBuilder strBuilder is "ABCCEFC", after invoking a. strBuilder.replace('C', 'T') b. strBuilder.replace("C", "T") c. strBuilder.replace("CC", "TT") d. strBuilder.replace('C', "TT") e. strBuilder.replace(2, 7, "TTEFT") Key:e See the discussion of the replace method in this section.

, strBuilder contains "ABTTEFT".

# 45. The StringBuilder methods not only change the contents of a string builder, but also returns a reference to the string builder. a. delete b. append c. insert d. reverse e. replace Key:abcde All the modification methods in the StringBuilder class modify the StringBuilder content and also returns the reference of the StringBuilder. # Section 10.11.2 The toString, capacity, length, setLength, and charAt Methods 41. returns the last character in a StringBuilder variable named strBuilder? a. strBuilder.charAt(strBuilder.length() - 1) b. strBuilder.charAt(strBuilder.capacity() - 1) c. StringBuilder.charAt(strBuilder.length() - 1) d. StringBuilder.charAt(strBuilder.capacity() - 1) Key:a See Figure 10.20.

..


Chapter 11 Inheritance and Polymorphism Section 11.2 Superclasses and Subclasses 1. Object-oriented programming allows you to derive new classes from existing classes. This is called a. encapsulation b. inheritance c. abstraction d. generalization Key:b See the first paragraph.

.

# 2. Which of the following statements are true? a. A subclass is a subset of a superclass. b. A subclass is usually extended to contain more functions and more detailed information than its superclass. c. "class A extends B" means A is a subclass of B. d. "class A extends B" means B is a subclass of A. Key:bc Read toward the end of this section. # 66. Inheritance means . a. that data fields should be declared private b. that a class can extend another class c. that a variable of supertype can refer to a subtype object d. that a class can contain another class Key:b See the Key Point. # Section 11.3 Using the super Keyword Section 11.3.1 Calling Superclass Constructors 3. Suppose you create a class Square to be a subclass of GeometricObject. Analyze the following code: class Square extends GeometricObject { double length; Square(double length) { GeometricObject(length); } } a. The program compiles fine, but you cannot create an instance of Square because the constructor does not specify the length of the Square. b. The program has a compile error because you attempted to invoke the GeometricObject class's constructor illegally. c. The program compiles fine, but it has a runtime error because of invoking the Square class's constructor illegally. Key:b You have to use super() or super(withapproriatearguments) to invoke a super class constructor explicitly. # 4. Analyze the following code: public class A extends B { } class B { public B(String s) { } © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


} a. The program has a compile error because A does not have a default constructor. b. The program has a compile error because the default constructor of A invokes the default constructor of B, but B does not have a default constructor. c. The program would compile fine if you add the following constructor into A: A(String s) { } d. The program would compile fine if you add the following constructor into A: A(String s) { super(s); } Key:bd The class A has a default constructor, which invokes the superclass B's no-arg constructor. But B has no noarg constructor. This causes an error. # 5.

Analyze the following code:

public class Test extends A { public static void main(String[] args) { Test t = new Test(); t.print(); } } class A { String s; A(String s) { this.s = s; } public void print() { System.out.println(s); } } a. The program does not compile because Test does not have a default constructor Test(). b. The program has an implicit default constructor Test(), but it cannot be compiled, because its super class does not have a default constructor. The program would compile if the constructor in the class A were removed. c. The program would compile if a default constructor A(){ } is added to class A explicitly. d. The program compiles, but it has a runtime error due to the conflict on the method name print. Key:bc The class Test has a default constructor, which invokes the superclass A's no-arg constructor. But A has no noarg constructor. This causes an error. # Section 11.3.2 Constructor Chaining 6. What is the output of running class C? class A { public A() { System.out.println( "The default constructor of A is invoked"); } } class B extends A { public B() { System.out.println( "The default constructor of B is invoked"); } © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


} public class C { public static void main(String[] args) { B b = new B(); } } a. Nothing displayed b. "The default constructor of B is invoked" c. "The default constructor of A is invoked" followed by "The default constructor of B is invoked" d. "The default constructor of B is invoked" followed by "The default constructor of A is invoked" e. "The default constructor of A is invoked" Key:c Superclass's constructor is called before executing the statements in the subclass constructor. # 7. Which of the following is incorrect? a. A constructor may be static. b. A constructor may be private. c. A constructor may invoke a static method. d. A constructor may invoke an overloaded constructor. e. A constructor invokes its superclass no-arg constructor by default if a constructor does not invoke an overloaded constructor or its superclass’s constructor. Key:a A constructor cannot be static, because you use a constructor to create a specific instance. A constructor may be private. In this case, the use cannot create an instance using this constructor. For example, the constructor in the Math class is private. A constructor may invoke a static method just like any method can invoke a static method. A constructor can invoke an overloaded constructor using the this keyword. So, the correct answer is A. # Section 11.3.3 Calling Superclass Methods 8. Which of the statements regarding the super keyword is incorrect? a. You can use super to invoke a super class constructor. b. You can use super to invoke a super class method. c. You can use super.super.p to invoke a method in superclass's parent class. d. You cannot invoke a method in superclass's parent class. Key:c Using super.super is not allowed in Java. So, the answer to this question is C. # Section 11.4 Overriding Methods 9. Analyze the following code: public class Test { public static void main(String[] args) { B b = new B(); b.m(5); System.out.println("i is " + b.i); } } class A { int i; public void m(int i) { this.i = i; } © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


} class B extends A { public void m(String s) { } } a. The program has a compile error, because m is overridden with a different signature in B. b. The program has a compile error, because b.m(5) cannot be invoked since the method m(int) is hidden in B. c. The program has a runtime error on b.i, because i is not accessible from b. d. The method m is not overridden in B. B inherits the method m from A and defines an overloaded method m in B. Key:d See the Key Point in this section. # 10. The getValue() method is overridden in two ways. Which one is correct? I: public class Test { public static void main(String[] args) { A a = new A(); System.out.println(a.getValue()); } } class B { public String getValue() { return "Any object"; } } class A extends B { public Object getValue() { return "A string"; } } II: public class Test { public static void main(String[] args) { A a = new A(); System.out.println(a.getValue()); } } class B { public Object getValue() { return "Any object"; } } class A extends B { public String getValue() { return "A string"; } } file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


a. I b. II c. Both I and II d. Neither Key:b See the text at the end of the section. # Section 11.5 Overriding vs. Overloading 11. Which of the following statements are true? a. To override a method, the method must be defined in the subclass using the same signature and compatible return type as in its superclass. b. Overloading a method is to provide more than one method with the same name but with different signatures to distinguish them. c. It is a compile error if two methods differ only in return type in the same class. d. A private method cannot be overridden. If a method defined in a subclass is private in its superclass, the two methods are completely unrelated. e. A static method cannot be overridden. If a static method defined in the superclass is redefined in a subclass, the method defined in the superclass is hidden. Key:abcde See the text at the end of the section. # 13. Analyze the following code: public class Test { public static void main(String[] args) { new B(); } } class A { int i = 7; public A() { System.out.println("i from A is " + i); } public void setI(int i) { this.i = 2 * i; } } class B extends A { public B() { setI(20); // System.out.println("i from B is " + i); } @Override public void setI(int i) { this.i = 3 * i; } } a. The constructor of class A is not called. file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


b. The constructor of class A is called and it displays "i from A is 7". c. The constructor of class A is called and it displays "i from A is 40". d. The constructor of class A is called and it displays "i from A is 60". Key:b When invoking new B(), B's superclass A's constructor is invoked first. So it displays i from A is 7. # 14. Analyze the following code: public class Test { public static void main(String[] args) { new B(); } } class A { int i = 7; public A() { setI(20); System.out.println("i from A is " + i); } public void setI(int i) { this.i = 2 * i; } } class B extends A { public B() { // System.out.println("i from B is " + i); } @Override public void setI(int i) { this.i = 3 * i; } } a. The constructor of class A is not called. b. The constructor of class A is called and it displays "i from A is 7". c. The constructor of class A is called and it displays "i from A is 40". d. The constructor of class A is called and it displays "i from A is 60". Key:d When invoking new B(), B's superclass A's constructor is invoked first. It invokes setI(20). The setI method in B is used because object created is new B(). The setI method in B assigns 3 * 20 to i. So it displays i from A is 60. # 12. Which of the following statements are true? a. A method can be overloaded in the same class. b. A method can be overridden in the same class. c. If a method overloads another method, these two methods must have the same signature. d. If a method overrides another method, these two methods must have the same signature. e. A method in a subclass can overload a method in the superclass. Key:ade See the text at the end of the section. # file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


Section 11.6 The Object Class and Its toString() Method 15. Analyze the following code: public class Test { public static void main(String[] args) { Object a1 = new A(); Object a2 = new Object(); System.out.println(a1); System.out.println(a2); } } class A { int x; @Override public String toString() { return "A's x is " + x; } } a. The program cannot be compiled, because System.out.println(a1) is wrong and it should be replaced by System.out.println(a1.toString()); b. When executing System.out.println(a1), the toString() method in the Object class is invoked. c. When executing System.out.println(a2), the toString() method in the Object class is invoked. d. When executing System.out.println(a1), the toString() method in the A class is invoked. Key:cd Since a1 is an instance of A, the toString() method in the A class is invoked at runtime. # Section 11.7 Polymorphism 17. Given the following code, find the compile error. public class Test { public static void main(String[] args) { m(new GraduateStudent()); m(new Student()); m(new Person()); m(new Object()); } public static void m(Student x) { System.out.println(x.toString()); } } class GraduateStudent extends Student { } class Student extends Person { @Override public String toString() { return "Student"; } }

file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


class Person extends Object { @Override public String toString() { return "Person"; } } a. m(new GraduateStudent()) causes an error b. m(new Student()) causes an error c. m(new Person()) causes an error d. m(new Object()) causes an error Key:cd You cannot pass a supertype variable to a subtype without explicit casting. # 64. Polymorphism means . a. that data fields should be declared private b. that a class can extend another class c. that a variable of supertype can refer to a subtype object d. that a class can contain another class Key:c See the Key Point. # Section 11.8 Dynamic Binding 18. What is the output of the following code? public class Test { public static void main(String[] args) { new Person().printPerson(); new Student().printPerson(); } } class Student extends Person { @Override public String getInfo() { return "Student"; } } class Person { public String getInfo() { return "Person"; } public void printPerson() { System.out.println(getInfo()); } } a. Person Person b. Person Student c. Student Student d. Student Person Key:b See LiveExample 11.6.

file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


# 19. What is the output of the following code? public class Test { public static void main(String[] args) { new Person().printPerson(); new Student().printPerson(); } } class Student extends Person { private String getInfo() { return "Student"; } } class Person { private String getInfo() { return "Person"; } public void printPerson() { System.out.println(getInfo()); } } a. Person Person b. Person Student c. Student Student d. Student Person Key:a Note that the getInfo method is private in Person. It is not known to the outside of the class. This is the method invoked from the printPerson() method. # 16. Which of the following statements is false? a. You can always pass an instance of a subclass to a parameter of its superclass type. This feature is known as polymorphism. b. The compiler finds a matching method according to parameter type, number of parameters, and order of the parameters at compile time. c. A method may be implemented in several subclasses. The Java Virtual Machine dynamically binds the implementation of the method at runtime. d. Dynamic binding can apply to static methods. e. Dynamic binding can apply to instance methods. Key:d Dynamic binding is applied to instance methods, not static methods. Static methods are bound in the compile time. # Section 11.9 Casting Objects and the instanceof Operator 20. Which of the following are Java keywords? a. instanceOf b. instanceof c. cast d. casting Key:b A simple rule: the keywords are all in lowercase. file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


# 25. Analyze the following code: public class Test { public static void main(String[] args) { String s = new String("Welcome to Java"); Object o = s; String d = (String)o; } } a. When assigning s to o in Object o = s, a new object is created. b. When casting o to s in String d = (String)o, a new object is created. c. When casting o to s in String d = (String)o, the contents of o is changed. d. s, o, and d reference the same String object. Key:d Casting object reference variable does not affect the contents of the object. # 22.

Assume Cylinder is a subtype of Circle. Analyze the following code:

Circle c = new Circle (5); Cylinder c = cy; a. The code has a compile error. b. The code has a runtime error. c. The code is fine. Key:a You cannot assign a variable of a supertype to a subtype without explicit casting. # 23.

Given the following classes and their objects:

class C1 {}; class C2 extends C1 {}; class C3 extends C1 {}; C2 c2 = new C2(); C3 c3 = new C3(); Analyze the following statement: c2 = (C2)((C1)c3); a. c3 is cast into c2 successfully. b. You will get a runtime error because you cannot cast objects from sibling classes. c. You will get a runtime error because the Java runtime system cannot perform multiple casting in nested form. d. The statement is correct. Key:b c3 can be casted to C1, but not to C2. # 24.

Given the following code, which of the following expressions evaluates to false?

class C1 {} class C2 extends C1 { } class C3 extends C2 { } class C4 extends C1 {}

file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


C1 c1 = new C1(); C2 c2 = new C2(); C3 c3 = new C3(); C4 c4 = new C4(); a. c1 instanceof C1 b. c2 instanceof C1 c. c3 instanceof C1 d. c4 instanceof C2 Key:d c4 is not an instace of C2. # 26. You can assign to a variable of Object[] type. a. new char[100] b. new int[100] c. new double[100] d. new String[100] e. new java.util.Date[100] Key:de Primitive data type array is not compatible with Object[]. # 21.

Assume Cylinder is a subtype of Circle. Analyze the following code:

Cylinder cy = new Cylinder(1, 1); Circle c = cy; a. The code has a compile error. b. The code has a runtime error. c. The code is fine. Key:c You can assign a variable of a subtype to a supertype. # Section 11.10 The Object’s equals() Method 33. Analyze the following code. // Program 1: public class Test { public static void main(String[] args) { Object a1 = new A(); Object a2 = new A(); System.out.println(a1.equals(a2)); } } class A { int x; public boolean equals(Object a) { return this.x == ((A)a).x; } } // Program 2: public class Test { file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


public static void main(String[] args) { Object a1 = new A(); Object a2 = new A(); System.out.println(a1.equals(a2)); } } class A { int x; public boolean equals(A a) { return this.x == a.x; } } a. Program 1 displays true and Program 2 displays true b. Program 1 displays false and Program 2 displays true c. Program 1 displays true and Program 2 displays false d. Program 1 displays false and Program 2 displays false Key:c In Program 1, the equals method in the Object class is overridden. a1.equals(a2) invokes this method. It returns true. In Program 2, the equals method in the Object class is not overridden. a1.equals(a2) invokes the equals method defined in the Object class, which returns false in this case. # 34. Analyze the following code. // Program 1: public class Test { public static void main(String[] args) { Object a1 = new A(); Object a2 = new A(); System.out.println(a1.equals(a2)); } } class A { int x; public boolean equals(A a) { return this.x == a.x; } } // Program 2: public class Test { public static void main(String[] args) { A a1 = new A(); A a2 = new A(); System.out.println(a1.equals(a2)); } } class A { int x; file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


public boolean equals(A a) { return this.x == a.x; } } a. Program 1 displays true and Program 2 displays true b. Program 1 displays false and Program 2 displays true c. Program 1 displays true and Program 2 displays false d. Program 1 displays false and Program 2 displays false Key:b In Program 1, the equals method in the Object class is invoked. In Program 2, the equals method in the class A is invoked. There are now two overloaded methods available in the class A. i.e. public boolean equals(Object a) and public boolean equals(A a). Which of the two is used by a1.equals(a2) is determined at compile time. a1.equals(a2) in Program 1 matches the equals method defined in Object and a1.equals(a2) in Program 2 matches the equals method defined in the class A. # 35. Analyze the following code. // Program 1 public class Test { public static void main(String[] args) { Object a1 = new A(); Object a2 = new A(); System.out.println(((A)a1).equals((A)a2)); } } class A { int x; public boolean equals(A a) { return this.x == a.x; } } // Program 2 public class Test { public static void main(String[] args) { A a1 = new A(); A a2 = new A(); System.out.println(a1.equals(a2)); } } class A { int x; public boolean equals(A a) { return this.x == a.x; } } a. Program 1 displays true and Program 2 displays true b. Program 1 displays false and Program 2 displays true file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


c. Program 1 displays true and Program 2 displays false d. Program 1 displays false and Program 2 displays false Key:a In Program 1, ((A)a1).equals((A)a2) matches the equals(A a) method in the class A. # 27. The equals method is defined in the Object class. Which of the following is correct to override it in the String class? a. public boolean equals(String other) b. public boolean equals(Object other) c. public static boolean equals(String other) d. public static boolean equals(Object other) Key:b B is the correct signature for the equals method. # 28. Which of the following statements are true? a. Override the equals(Object) method in the Object class whenever possible. b. Override the toString() method in the Object class whenever possible. c. A public default no-arg constructor is assumed if no constructors are defined explicitly. d. You should follow standard Java programming style and naming conventions. Choose informative names for classes, data fields, and methods. Key:abcd These statements are all correct. # 29. What is the output of the following code? public class Test { public static void main(String[] args) { Object o1 = new Object(); Object o2 = new Object(); System.out.print((o1 == o2) + " " + (o1.equals(o2))); } } a. false false b. true true c. false true d. true false Key:a o1 == o2 is false, since o1 and o2 are two different objects. o1.equals(o2) is false since the equals method returns o1 == o2 in the Object class. # 30. What is the output of the following code? public class Test { public static void main(String[] args) { String s1 = new String("Java"); String s2 = new String("Java"); System.out.print((s1 == s2) + " " + (s1.equals(s2))); } } a. false false b. true true c. false true d. true false Key:c s1 == s2 is false, since s1 and s2 are two different objects. s1.equals(s2) is true since the equals method returns file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


true if two strings have the same content. # 31. Given two reference variables t1 and t2, if t1 == t2 is true, t1.equals(t2) must be a. true b. false Key:a t1 and t2 refer to the same object. # 32. Given two reference variables t1 and t2, if t1.equals(t2) is true, t1 == t2 a. is always true b. is always false c. may be true or false Key:c Two different objects may be equal with the same contents.

.

.

# Section 11.11 The ArrayList Class 43. Analyze the following code: ArrayList<String> list = new ArrayList<>(); list.add("Beijing"); list.add("Tokyo"); list.add("Shanghai"); list.set(3, "Hong Kong"); a. The last line in the code causes a runtime error because there is no element at index 3 in the array list. b. The last line in the code has a compile error because there is no element at index 3 in the array list. c. If you replace the last line by list.add(3, "Hong Kong"), the code will compile and run fine. d. If you replace the last line by list.add(4, "Hong Kong"), the code will compile and run fine. Key:ac There is no element at index 3. # 44. What is the output of the following code? ArrayList<java.util.Date> list = new ArrayList<>(); java.util.Date d = new java.util.Date(); list.add(d); list.add(d); System.out.println((list.get(0) == list.get(1)) + " " + (list.get(0)).equals(list.get(1))); a. true false b. false true c. true true d. false false Key:c list.get(0) and list.get(1) point to the same object. # 45. What is the output of the following code? ArrayList<String> list = new ArrayList<>(); String s1 = new String("Java"); String s2 = new String("Java"); list.add(s1); file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


list.add(s2); System.out.println((list.get(0) == list.get(1)) + " " + (list.get(0)).equals(list.get(1))); a. true false b. false true c. true true d. false false Key:b list.get(0) and list.get(1) point to two different objects with the same string contents. # 36. You can create an ArrayList using . a. new ArrayList[] b. new ArrayList[100] c. new ArrayList<>() d. ArrayList() Key:c You can create an ArrayListing using its no-arg constructor. Since ArrayList is a generic type, new ArrayList<>() automatically discovers the type in the defining type. For example, ArrayList<String> list = new ArrayList<>(); # 37. Invoking removes all elements in an ArrayList x. a. x.remove() b. x.clean() c. x.delete() d. x.empty() e. x.clear() Key:e See Figure 11.3. # 38. Suppose ArrayList x contains two strings [Beijing, Singapore]. Which of the following methods will cause the list to become [Beijing, Chicago, Singapore]? a. x.add("Chicago") b. x.add(0, "Chicago") c. x.add(1, "Chicago") d. x.add(2, "Chicago") Key:c See Figure 11.3. # 39. Suppose ArrayList x contains two strings [Beijing, Singapore]. Which of the following method will cause the list to become [Beijing]? a. x.remove("Singapore") b. x.remove(0) c. x.remove(1) d. x.remove(2) Key:ac See Figure 11.3. # 40. Suppose ArrayList x contains two strings [Beijing, Singapore]. Which of the following method will cause runtime errors? a. x.get(1) b. x.set(2, "New York"); c. x.get(2) d. x.remove(2) file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


e. x.size() Key:bcd There is no element at index 2. # 41. Invoking returns the first element in an ArrayList x. a. x.first() b. x.get(0) c. x.get(1) d. x.get() Key:b See Figure 11.3. # 42. Invoking returns the number of the elements in an ArrayList x. a. x.getSize() b. x.getLength(0) c. x.length(1) d. x.size() Key:d See Figure 11.3. # 46. Suppose an ArrayList list contains {"red", "green", "red", "green"}. What is the list after the following code? list.remove("red"); a. {"red", "green", "red", "green"} b. {"green", "red", "green"} c. {"green", "green"} d. {"red", "green", "green"} Key:b See Figure 11.3. # 47. Suppose an ArrayList list contains {"red", "red", "green"}. What is the list after the following code? String element = "red"; for (int i = 0; i < list.size(); i++) if (list.get(i).equals(element)) list.remove(element); a. {"red", "red", "green"} b. {"red", "green"} c. {"green"} d. {} Key:b See Figure 11.3. # 48. Suppose an ArrayList list contains {"red", "red", "green"}. What is the list after the following code? String element = "red"; for (int i = 0; i < list.size(); i++) if (list.get(i).equals(element)) { list.remove(element); i--; }

file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


a. {"red", "red", "green"} b. {"red", "green"} c. {"green"} d. {} Key:c See Figure 11.3. # 49. Suppose an ArrayList list contains {"red", "red", "green"}. What is the list after the following code? String element = "red"; for (int i = list.size() - 1; i >= 0; i--) if (list.get(i).equals(element)) list.remove(element); a. {"red", "red", "green"} b. {"red", "green"} c. {"green"} d. {} Key:c See Figure 11.3. # 50. The output from the following code is

.

java.util.ArrayList<String> list = new java.util.ArrayList<>(); list.add("New York"); java.util.ArrayList<String> list1 = list; list.add("Atlanta"); list1.add("Dallas"); System.out.println(list1); a. [New York] b. [New York, Atlanta] c. [New York, Atlanta, Dallas] d. [New York, Dallas] Key:c Listing 11.8. # Section 11.12 Useful Methods for Lists 51. Show the output of the following code: String[] array = {"red", "green", "blue"}; ArrayList<String> list = new ArrayList<>(Arrays.asList(array)); list.add(0, "red"); System.out.println(list); a. ["red", "green", "blue", "red"] b. ["red", "green", "blue"] c. ["red", "red", "green", "blue"] d. ["red", "green", "red", "blue"] Key:c See the discussion of the asList method in this section. # 52.

Analyze the following code:

file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


Double[] array = {1, 2, 3}; ArrayList<Double> list = new ArrayList<>(Arrays.asList(array)); System.out.println(list); a. The code is correct and displays [1, 2, 3]. b. The code is correct and displays [1.0, 2.0, 3.0]. c. The code has a compile error because an integer such as 1 is automatically converted into an Integer object, but the array element type is Double. d. The code has a compile error because asList(array) requires that the array elements are objects. Key:c See the discussion of the asList method in this section. # 53.

Analyze the following code:

double[] array = {1, 2, 3}; ArrayList<Double> list = new ArrayList<>(Arrays.asList(array)); System.out.println(list); a. The code is correct and displays [1, 2, 3]. b. The code is correct and displays [1.0, 2.0, 3.0]. c. The code has a compile error because an integer such as 1 is automatically converted into an Integer object, but the array element type is Double. d. The code has a compile error because asList(array) requires that the array elements are objects. Key:d See the discussion of the asList method in this section. # 54.

Analyze the following code:

double[] c = {1, 2, 3}; System.out.println(java.util.Collections.max(c)); a. The code is correct and displays 3. b. The code is correct and displays 3.0. c. The code has a compile error on Collections.max(c). c cannot be an array. d. The code has a compile error on double[] c = {1, 2, 3}. Key:c See the discussion of the max method in this section. # 55.

Analyze the following code:

Integer[] c = {3, 5}; java.util.Collections.shuffle(c); System.out.println(java.util.Arrays.toString(c)); a. The code is correct and displays [3, 5]. b. The code is correct and displays [5, 3]. c. The code has a compile error on Collections.shuffle(c). c cannot be an array. d. The code has a compile error on Integer[] c = {3, 5}. Key:c See the discussion of the shuffle method in this section. # Section 11.14 The protected Data and Methods 59. A class design requires that a particular member variable must be accessible by any subclasses of this class, but file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


otherwise not by classes which are not members of the same package. What should be done to achieve this? a. The variable should be marked public. b. The variable should be marked private. c. The variable should be marked protected. d. The variable should have no special access modifier. e. The variable should be marked private and an accessor method provided. Key:c See Table 11.2. # 61. Which statements are most accurate regarding the following classes? class A { private int i; protected int j; } class B extends A { private int k; protected int m; } a. An object of B contains data fields i, j, k, m. b. An object of B contains data fields j, k, m. c. An object of B contains data fields j, m. d. An object of B contains data fields k, m. Key:a The data fields in a superclass are contained in a subclass. Whether the data fields in a superclass can be accessed in a subclass is a visibility issue. A private data field in a superclass cannot be directly accessed in a subclass, but the data field may have the getter or setter methods, which can be used to get or set a data field value. # 62. Which statements are most accurate regarding the following classes? class A { private int i; protected int j; } class B extends A { private int k; protected int m; // some methods omitted } a. In the class B, an instance method can only access i, j, k, m. b. In the class B, an instance method can only access j, k, m. c. In the class B, an instance method can only access j, m. d. In the class B, an instance method can only access k, m. Key:b See Table 11.2. # 60. Which of the following statements is false? a. A public class can be accessed by a class from a different package. b. A private method cannot be accessed by a class in a different package. file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


c. A protected method can be accessed by a subclass in a different package. d. A method with no visibility modifier can be accessed by a class in a different package. Key:d See Table 11.2. # 56. What modifier should you use on a class so that a class in the same package can access it but a class (including a subclass) in a different package cannot access it? a. public b. private c. protected d. Use the default modifier. Key:d See Table 11.2. # 57. What modifier should you use on the members of a class so that they are not accessible to another class in a different package, but are accessible to any subclasses in any package? a. public b. private c. protected d. Use the default modifier. Key:c See Table 11.2. # 58. The visibility of these modifiers increases in this order: a. private, protected, none (if no modifier is used), and public. b. private, none (if no modifier is used), protected, and public. c. none (if no modifier is used), private, protected, and public. d. none (if no modifier is used), protected, private, and public. Key:b See Table 11.2. # Section 11.15 Preventing Extending and Overriding 63. Which of the following classes cannot be extended? a. class A { } b. class A {   private A() {  }} c. final class A { } d. class A {   protected A() {  }} Key:c See the Key Point.

file:///C|/Users/usuller/Downloads/chapter11.txt[12/4/2019 3:47:54 PM]


Chapter 12 Exception Handling and Text I/O Section 12.2 Exception-Handling Overview 5. The following code causes Java to throw

.

int number = Integer.MAX_VALUE + 1; a. RuntimeException b. Exception c. Error d. Throwable e. no exceptions Key:e At present, Java does not throw integer overflow exceptions. The future version of Java may fix this problem to throw an overflow exception. # 7. What exception type does the following program throw? public class Test { public static void main(String[] args) { System.out.println(1 / 0); } } a. ArithmeticException b. ArrayIndexOutOfBoundsException c. StringIndexOutOfBoundsException d. ClassCastException e. No exception Key:a Integer division by 0 throws ArithmeticException. # Section 12.3 Exception Types 1. A Java exception is an instance of a. RuntimeException b. Exception c. Error d. Throwable e. NumberFormatException Key:d See Figure 12.1.

.

# 2. An instance of describes system errors. If this type of error occurs, there is little you can do beyond notifying the user and trying to terminate the program gracefully. a. RuntimeException b. Exception c. Error d. Throwable e. NumberFormatException Key:c See the bullet items. # 3. An instance of describes the errors caused by your program and external circumstances. These errors can be caught and handled by your program. a. RuntimeException ..


b. Exception c. Error d. Throwable e. NumberFormatException Key:b See the bullet items. # 6. Instances of are unchecked exceptions. a. RuntimeException b. Exception c. Error d. Throwable e. NumberFormatException Key:ace NumberFormatException is a subclass of RuntimeException # 8. What exception type does the following program throw? public class Test { public static void main(String[] args) { int[] list = new int[5]; System.out.println(list[5]); } } a. ArithmeticException b. ArrayIndexOutOfBoundsException c. StringIndexOutOfBoundsException d. ClassCastException e. No exception Key:b The array size is 5. list[5] causes ArrayIndexOutOfBoundsException. # 9. What exception type does the following program throw? public class Test { public static void main(String[] args) { String s = "abc"; System.out.println(s.charAt(3)); } } a. ArithmeticException b. ArrayIndexOutOfBoundsException c. StringIndexOutOfBoundsException d. ClassCastException e. No exception Key:c The array size is 3. s.charAt(3) causes ArrayIndexOutOfBoundsException. # Section 12.4 Declaring, Throwing, and Catching Exceptions Section 12.4.1 Declaring Exceptions 13. A method must declare to throw . a. unchecked exceptions b. checked exceptions c. Error © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


d. RuntimeException Key:b See th end of Section 12.3. # 11. What exception type does the following program throw? public class Test { public static void main(String[] args) { Object o = null; System.out.println(o.toString()); } } a. ArithmeticException b. ArrayIndexOutOfBoundsException c. StringIndexOutOfBoundsException d. ClassCastException e. NullPointerException Key:e See Figure 12.1 in Section 12.3. # 12. What exception type does the following program throw? public class Test { public static void main(String[] args) { Object o = null; System.out.println(o); } } a. ArithmeticException b. ArrayIndexOutOfBoundsException c. StringIndexOutOfBoundsException d. No exception e. NullPointerException Key:d The code is fine. No errors. # Section 12.4.2 Throwing Exceptions 14. Which of the following statements are true? a. You use the keyword throws to declare exceptions in the method heading. b. A method may declare to throw multiple exceptions. c. To throw an exception, use the key word throw. d. If a checked exception occurs in a method, it must be either caught or declared to be thrown from the method. Key:abcd All these statements are true. # 15. Analyze the following code: public class Test { public static void main(String[] args) throws MyException { System.out.println("Welcome to Java"); } } class MyException extends Error { ..


} a. You should not declare a class that extends Error, because Error raises a fatal error that terminates the program. b. You cannot declare an exception in the main method. c. You declared an exception in the main method, but you did not throw it. d. The program has a compile error. Key:a When an exception of Error type occurs, your program would terminate. Therefore, you should not declare an exception that extends Error. You declared an exception in the main method. If you did not throw anything, that is fine. # 10. What exception type does the following program throw? public class Test { public static void main(String[] args) { Object o = new Object(); String d = (String)o; } } a. ArithmeticException b. ArrayIndexOutOfBoundsException c. StringIndexOutOfBoundsException d. ClassCastException e. No exception Key:d The object o is of the type Object. It cannot be cast to (String). # Section 12.4.3 Catching Exceptions 16. Analyze the following code: public class Test { public static void main(String[] args) { try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; } catch (Exception ex) { System.out.println("NumberFormatException"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } } } a. The program displays NumberFormatException. b. The program displays RuntimeException. c. The program displays NumberFormatException followed by RuntimeException. d. The program has a compile error. Key:d catch (RuntimeException ex) should be specified before catch (Exception ex). # 4. An instance of and numeric errors. ..

describes programming errors, such as bad casting, accessing an out-of-bounds array,


a. RuntimeException b. Exception c. Error d. Throwable e. NumberFormatException Key:a See Table 12.3 in Section 12.3. # Section 12.4.4 Getting Information from Exceptions 17. Analyze the following program. public class Test { public static void main(String[] args) { try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } catch (Exception ex) { System.out.println(ex); } } } a. An exception is raised due to Integer.parseInt(s); b. An exception is raised due to 2 / i; c. The program has a compile error. d. The program compiles and runs without exceptions. Key:a Both (A) and (B) would cause exception, but (A) occurred first, so the exception is due to (A). # 18.

What is displayed on the console when running the following program?

public class Test { public static void main(String[] args) { try { p(); System.out.println("After the method call"); } catch (NumberFormatException ex) { System.out.println("NumberFormatException"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } } static void p() { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException int i = 0; © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


int y = 2 / i; System.out.println("Welcome to Java"); } } a. The program displays NumberFormatException. b. The program displays NumberFormatException followed by After the method call. c. The program displays NumberFormatException followed by RuntimeException. d. The program has a compile error. e. The program displays RuntimeException. Key:a It should be A. The main method invokes the method p. In p, Integer.parseInt(s) causes a NumberFormatException. The method p is now terminated. The NumberFormatException exception is handled in the main method. So NumberFormatException is displayed. # Section 12.4.5 Example: Declaring, Throwing, and Catching Exceptions 19. What is displayed on the console when running the following program? public class Test { public static void main(String[] args) { try { p(); System.out.println("After the method call"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } catch (Exception ex) { System.out.println("Exception"); } } static void p() throws Exception { try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } catch (Exception ex) { System.out.println("Exception"); } } } a. The program displays RuntimeException twice. b. The program displays Exception twice. c. The program displays RuntimeException followed by After the method call. d. The program displays Exception followed by RuntimeException. e. The program has a compile error. Key:c Invoking method p() causes a RuntimeException. It is handled in "catch (RuntimeException ex)" and then ..


System.out.println("After the method call") is called. # Section 12.5 The finally Clause 20. What is wrong in the following program? public class Test { public static void main (String[] args) { try { System.out.println("Welcome to Java"); } } } a. You cannot have a try block without a catch block. b. You cannot have a try block without a catch block or a finally block. c. A method call that does not declare exceptions cannot be placed inside a try block. d. Nothing is wrong. Key:b A try clause must be followed by a catch or finally clause. # 21.

What is displayed on the console when running the following program?

public class Test { public static void main (String[] args) { try { System.out.println("Welcome to Java"); } finally { System.out.println("The finally clause is executed"); } } } a. Welcome to Java b. Welcome to Java followed by The finally clause is executed in the next line c. The finally clause is executed d. None of the above Key:b The finally clause is always executed. # 22.

What is displayed on the console when running the following program?

public class Test { public static void main (String[] args) { try { System.out.println("Welcome to Java"); return; } finally { System.out.println("The finally clause is executed"); } } } a. Welcome to Java b. Welcome to Java followed by The finally clause is executed in the next line © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


c. The finally clause is executed d. None of the above Key:b The return statement exits the method, but before exiting the method, the finally clause is executed. # 23.

What is displayed on the console when running the following program?

public class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2 / i; System.out.println("Welcome to HTML"); } finally { System.out.println("The finally clause is executed"); } } } a. Welcome to Java, then an error message. b. Welcome to Java followed by The finally clause is executed in the next line, then an error message. c. The program displays three lines: Welcome to Java, Welcome to HTML, The finally clause is executed, then an error message. d. None of the above. Key:b integer divided by 0 in 2 / i causes an exception. # 24.

What is displayed on the console when running the following program?

public class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; double y = 2.0 / i; System.out.println("Welcome to HTML"); } finally { System.out.println("The finally clause is executed"); } } } a. Welcome to Java. b. Welcome to Java followed by The finally clause is executed in the next line. c. The program displays three lines: Welcome to Java, Welcome to HTML, The finally clause is executed. d. None of the above. Key:c A floating number divided by 0 does not raise an exception. # 25.

What is displayed on the console when running the following program?

public class Test { public static void main(String[] args) { ..


try { System.out.println("Welcome to Java"); int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } catch (RuntimeException ex) { System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); } } } a. The program displays Welcome to Java three times followed by End of the block. b. The program displays Welcome to Java two times followed by End of the block. c. The program displays Welcome to Java three times. d. The program displays Welcome to Java two times. Key:b integer divided by 0 in 2 / i causes an exception. # 26.

What is displayed on the console when running the following program?

public class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } catch (RuntimeException ex) { System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); } System.out.println("End of the block"); } } a. The program displays Welcome to Java three times followed by End of the block. b. The program displays Welcome to Java two times followed by End of the block. c. The program displays Welcome to Java two times followed by End of the block two times. d. You cannot catch RuntimeException errors. Key:c integer divided by 0 in 2 / i causes an exception. # 27.

What is displayed on the console when running the following program?

public class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); } System.out.println("End of the block"); } } a. The program displays Welcome to Java three times followed by End of the block. b. The program displays Welcome to Java two times followed by End of the block. c. The program displays Welcome to Java two times followed by End of the block two times. d. The program displays Welcome to Java and End of the block, and then terminates because of an unhandled exception. Key:d integer divided by 0 in 2 / i causes an exception. # Section 12.6 When to Use Exceptions 28. Which of the following is not an advantage of Java exception handling? a. Java separates exception handling from normal processing tasks. b. Exception handling improves performance. c. Exception handling makes it possible for the caller's caller to handle the exception. d. Exception handling simplifies programming because the error-reporting and error-handling code can be placed at the catch block. Key:b See the first paragraph in this section and also see in the overview in Section 12.2. # 29.

Analyze the following code:

public class Test { public static void main(String[] args) { try { int zero = 0; int y = 2 / zero; try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException } catch(Exception e) { } } catch(RuntimeException e) { System.out.println(e); } } } a. A try-catch block cannot be embedded inside another try-catch block. b. A good programming practice is to avoid nesting try-catch blocks, because nesting makes programs difficult to read. You can rewrite the program using only one try-catch block. c. The program has a compile error because Exception appears before RuntimeException. d. None of the above. Key:b The best answer is b. This question does not ask you what happens when you run the program. If you run the ..


program, a RuntimeException would occur and it would be caught be the last catch clause. # Section 12.7 Rethrowing Exceptions 30. What is displayed on the console when running the following program? public class Test { public static void main(String[] args) { try { method(); System.out.println("After the method call"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } catch (Exception ex) { System.out.println("Exception"); } } static void method() throws Exception { try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } catch (NumberFormatException ex) { System.out.println("NumberFormatException"); throw ex; } catch (RuntimeException ex) { System.out.println("RuntimeException"); } } } a. The program displays NumberFormatException twice. b. The program displays NumberFormatException followed by After the method call. c. The program displays NumberFormatException followed by RuntimeException. d. The program has a compile error. Key:c The exception is rethrown the the caller and the caller catches RuntimeException. # Section 12.10 The File Class 31. What are the reasons to create an instance of the File class? a. To determine whether the file exists. b. To obtain the properties of the file such as whether the file can be read, written, or is hidden. c. To rename the file. d. To delete the file. e. To read/write data from/to a file Key:abcd See the first part of this section and Figure 12.6. © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


# 32. Which of the following is used to test if a file c:\temp\test.txt exists? a. new File("c:\temp\test.txt").exists() b. new File("c:\\temp\\test.txt").exists() c. new File("c:\temp\test.txt").exist() d. new File("c:\\temp\\test.txt").exist() e. None of the above. Key:b See Figure 12.6. # 33. Which of the following statements creates an instance of File on Window for the file c:\temp.txt? a. new File("c:\temp.txt") b. new File("c:\\temp.txt") c. new File("c:/temp.txt") d. new File("c://temp.txt") Key:b On Windows, use \\ for the path separator. # 34. Which of the following statements are true? a. If a file (e.g., c:\temp.txt) does not exist, new File("c:\\temp.txt") returns null. b. If a directory (e.g., c:\liang) does not exist, new File("c:\liang") returns null. c. If a file (e.g., c:\temp.txt) does not exist, new File("c:\\temp.txt") creates a new file named c:\temp.txt. d. If a directory (e.g., c:\liang) does not exist, new File("c:\liang") creates a new directory named c:\liang. e. None of the above. Key:e The File class is used to create a File object. # Section 12.11 Text I/O Section 12.11.1 Writing Data Using PrintWriter 36. Which class do you use to write data into a text file? a. File b. PrintWriter c. Scanner d. System Key:b See Figure 12.8. # 38. Which method can be used to write data? a. close b. print c. exist d. rename Key:b See Listing 12.13. # 47. Which method can be used to create an output object for file temp.txt? a. new PrintWriter("temp.txt") b. new PrintWriter(temp.txt) c. new PrintWriter(new File("temp.txt")) d. new PrintWriter(File("temp.txt")) Key:ac See Listing 12.13. # 35. Which class contains the method for checking whether a file exists? © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


a. File b. PrintWriter c. Scanner d. System Key:a See Figure 12.8. # Section 12.11.2 Closing Resources Automatically Using try-with-resource 40. Which of the following statements are correct? I: try (PrintWriter output = new PrintWriter("output.txt");) { output.println("Welcome to Java"); } II: try (PrintWriter output = new PrintWriter("output.txt"); Scanner input = new Scanner(System.in);) { output.println(input.nextLine()); } III: PrintWriter output; try (output = new PrintWriter("output.txt");) { output.println("Welcome to Java"); } IV: try (PrintWriter output = new PrintWriter("output.txt");) { output.println("Welcome to Java"); } finally { output.close(); } a. I b. II c. III d. IV Key:ab III is wrong. You have to declare the resource reference variable and create the resource altogether in the try (…). # Section 12.11.3 Reading Data Using Scanner 37. Which class do you use to read data from a text file? a. File b. PrintWriter c. Scanner d. System Key:c See Figure 12.9. # 39. Which method can be used to read a whole line from the file? a. next ..


b. nextLine c. nextInt d. nextDouble Key:b See Figure 12.9. # 41. Which of the following statements are correct? I: File file = new File("input.txt"); try (Scanner input = new Scanner(file);) { String line = input.nextLine(); } II: try (File file = new File("input.txt"); Scanner input = new Scanner(file);) { String line = input.nextLine(); } III: File file; try (file = new File("input.txt"); Scanner input = new Scanner(file);) { String line = input.nextLine(); } IV: File file; Scanner input; try (file = new File("input.txt"); input = new Scanner(file);) { String line = input.nextLine(); } a. I b. II c. III d. IV Key:a File is not a subtype of AutoCloseable. So it cannot be used to open a resource in a try-with-resources. # 42. Which method can be used to create an input object for file temp.txt? a. new Scanner("temp.txt") b. new Scanner(temp.txt) c. new Scanner(new File("temp.txt")) d. new Scanner(File("temp.txt")) Key:c See Listing 12.15. # Section 12.11.4 How Does Scanner Work? 43. Suppose you enter 34.3 57.8 789, then press the ENTER key. Analyze the following code. Scanner input = new Scanner(System.in); int v1 = input.nextInt(); © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


int v2 = input.nextInt(); String line = input.nextLine(); a. After the last statement is executed, v1 is 34. b. The program has a runtime error because 34.3 is not an integer. c. After the last statement is executed, line contains characters '7', '8', '9', '\n'. d. After the last statement is executed, line contains characters '7', '8', '9'. Key:b See discussions in Section 12.11.3. # 44. Suppose you enter 34.3 57.8 789, then press the ENTER key. Analyze the following code. Scanner input = new Scanner(System.in); double v1 = input.nextDouble(); double v2 = input.nextDouble(); String line = input.nextLine(); a. After the last statement is executed, line contains characters '7', '8', '9'. b. After the last statement is executed, line contains characters '7', '8', '9', '\n'. c. After the last statement is executed, line contains characters ' ', '7', '8', '9', '\n'. d. After the last statement is executed, line contains characters ' ', '7', '8', '9'. Key:d See discussions in Section 12.11.3. # 45. Suppose you enter 34.3, the ENTER key, 57.8, the ENTER key. Analyze the following code. Line 1 Scanner input = new Scanner(System.in); Line 2 double v1 = input.nextDouble(); Line 3 double v2 = input.nextDouble(); Line 4 String line = input.nextLine(); a. After line 2 is executed, v1 is 34.3. b. After line 3 is executed, v2 is 57.8. c. After line 4 is executed, line contains an empty string. d. After line 4 is executed, line is null. e. After line 4 is executed, line contains character "\n". Key:abc See discussions in Section 12.11.3. # 46. Suppose you enter 34.3, the ENTER key, 57.8, the ENTER key, abc, the Enter key. Analyze the following code. Line 1 Scanner input = new Scanner(System.in); Line 2 double v1 = input.nextDouble(); Line 3 double v2 = input.nextDouble(); Line 4 String line = input.nextLine(); a. After line 2 is executed, v1 is 34.3. b. After line 3 is executed, v2 is 57.8. c. After line 4 is executed, line contains an empty string. d. After line 4 is executed, line is null. e. After line 4 is executed, line contains character "abc". Key:abc See discussions in Section 12.11.3. # Section 12.12 Reading Data from the Web 48. To create an InputStream to read from a file on a Web server, you use the method ..

in the URL


class. a. getInputStream(); b. obtainInputStream(); c. openStream(); d. connectStream(); Key:c See LiveExample 12.16.

..


Chapter 13 Abstract Classes and Interfaces Section 13.2 Abstract Classes 1. Which of the following class definitions defines a legal abstract class? a. class A { abstract void unfinished() { } } b. class A { abstract void unfinished(); } c. abstract class A { abstract void unfinished(); } d. public class abstract A { abstract void unfinished(); } Key:c In A and B, abstract keyword is missing for the class. In D, class and abstract are in a wrong order. The correct answer is C. # 2. Which of the following declares an abstract method in an abstract Java class? a. public abstract method(); b. public abstract void method(); c. public void abstract method(); d. public void method() {} e. public abstract void method() {} Key:b In A, the method has no return type. In C, void and abstract are in a wrong order. In D, the abstract keyword is missing. In E, the body {} should be removed. The correct answer is B. # Section 13.2.1 Why Abstract Methods? 3. Which of the following statements regarding abstract methods is false? a. An abstract class can have instances created using the constructor of the abstract class. b. An abstract class can be extended. c. A subclass of a non-abstract superclass can be abstract. d. A subclass can override a concrete method in a superclass to declare it abstract. e. An abstract class can be used as a data type. Key:a A is wrong because you cannot create an instance using the constructor from an abstract class. # 4. Which of the following statements regarding abstract methods is false? a. Abstract classes have constructors. b. A class that contains abstract methods must be abstract. c. It is possible to declare an abstract class that contains no abstract methods. d. An abstract method cannot be contained in a nonabstract class. e. A data field can be declared abstract. Key:e E is wrong, because a data field cannot be declared abstract. Only methods and classes can be declared abstract. # Section 13.2.2 Interesting Points about Abstract Classes 5. Suppose A is an abstract class, B is a concrete subclass of A, and both A and B have a no-arg constructor. Which of the following is correct? a. A a = new A(); b. A a = new B(); c. B b = new A(); d. B b = new B(); Key:bd Since B is a concrete class with a no-arg constructor, d is correct. Since an instance of B is also an instance of A, b is also correct. # 6. What is the output of running class Test? ..


public class Test { public static void main(String[] args) { new Circle9(); } } public abstract class GeometricObject { protected GeometricObject() { System.out.print("A"); } protected GeometricObject(String color, boolean filled) { System.out.print("B"); } } public class Circle9 extends GeometricObject { /** No-arg constructor */ public Circle9() { this(1.0); System.out.print("C"); } /** Construct circle with a specified radius */ public Circle9(double radius) { this(radius, "white", false); System.out.print("D"); } /** Construct a circle with specified radius, filled, and color */ public Circle9(double radius, String color, boolean filled) { super(color, filled); System.out.print("E"); } } a. ABCD b. BACD c. CBAE d. AEDC e. BEDC Key:e The sequence of constructor chaining is as follows: Circle9(), Circle9(1.0), Circle9(1.0, "white", false), GeometricObject("white", false). # Section 13.3 Case Study: the Abstract Number Class 7. The java.lang.Number and its subclasses are introduced in Chapter 11. Analyze the following code. Number numberRef = new Integer(0); Double doubleRef = (Double)numberRef; a. There is no such class named Integer. You should use the class Int. b. The compiler detects that numberRef is not an instance of Double. c. A runtime class casting exception occurs, since numberRef is not an instance of Double. ..


d. The program runs fine, since Integer is a subclass of Double. e. You can convert an int to double, so you can cast an Integer instance to a Double instance. Key:c numberRef refers to an Integer object and cannot be cast to (Double). # 8. Analyze the following code. Number[] numberArray = new Integer[2]; numberArray[0] = new Double(1.5); a. You cannot use Number as a data type since it is an abstract class. b. Since each element of numberArray is of the Number type, you cannot assign an Integer object to it. c. Since each element of numberArray is of the Number type, you cannot assign a Double object to it. d. At runtime, new Integer[2] is assigned to numberArray. This makes each element of numberArray an Integer object. So you cannot assign a Double object to it. Key:d The acutal element type in numberArray is of Integer. So you cannot assign new Double(1.5) to it. # 9. Analyze the following code. Which of the following statements is correct? public class Test { public static void main(String[] args) { Number x = new Integer(3); System.out.println(x.intValue()); System.out.println(x.compareTo(new Integer(4))); } } a. The program has a compile error because an Integer instance cannot be assigned to a Number variable. b. The program has a compile error because intValue is an abstract method in Number. c. The program has a compile error because x does not have the compareTo method. d. The program compiles and runs fine. Key:c x's declared type is Number. Number is not a subtype of Comparable. x does not have the compareTo method. # 11. Which of the following statements is incorrect? a. Integer i = 4.5; b. Double i = 4.5; c. Object i = 4.5; d. Number i = 4.5; Key:a i is an Integer. You cannot assign 4.5 to i. A is incorrect. B, C, and D are correct. 4.5 is autoboxed to new Double(4.5). A Double object is an instance of Object and Double. # 10. Analyze the following code. Which of the following statements is correct? public class Test { public static void main(String[] args) { Number x = new Integer(3); System.out.println(x.intValue()); System.out.println((Integer)x.compareTo(new Integer(4))); } } a. The program has a compile error because an Integer instance cannot be assigned to a Number variable. b. The program has a compile error because intValue is an abstract method in Number. c. The program has a compile error because x cannot be cast into Integer. ..


d. The program has a compile error because the member access operator (.) is executed before the casting operator. e. The program compiles and runs fine. Key:d Note that the . operator is executed before the casting operator. # Section 13.4 Case Study: Calendar and GregorianCalendar 12. The java.util.Calendar and java.util.GregorianCalendar classes are introduced in Chapter 11. Analyze the following code. Which of the following statements is correct? 1. import java.util.*; 2. public class Test { 3. public static void main(String[] args) { 4. Calendar[] calendars = new Calendar[10]; 5. calendars[0] = new Calendar(); 6. calendars[1] = new GregorianCalendar(); 7. } 8. } a. The program has a compile error on Line 4 because java.util.Calendar is an abstract class. b. The program has a compile error on Line 5 because java.util.Calendar is an abstract class. c. The program has a compile error on Line 6 because Calendar[1] is not of a GregorianCalendar type. d. The program has no compile errors. Key:b (A) is incorrect since it is OK to use abstract class as data type for arrays. new Calendar[10] does not create Calendar objects. It just creates an array with 10 elements, each of which can reference to a Calendar object. (B) is correct since you cannot create an object from an abstract class. (C) is incorrect since it is fine to create a GregorianCalendar object and assign its reference to a variable of its superclass type. # 13. Assume Calendar calendar = new GregorianCalendar(). returns the month of the year. a. calendar.get(Calendar.MONTH) b. calendar.get(Calendar.MONTH_OF_YEAR) c. calendar.get(Calendar.WEEK_OF_MONTH) d. calendar.get(Calendar.WEEK_OF_YEAR) Key:a B is wrong since Calendar.MONTH_OF_YEAR is not a valid field. # 14. Assume Calendar calendar = new GregorianCalendar(). a. calendar.get(Calendar.MONTH) b. calendar.get(Calendar.MONTH_OF_YEAR) c. calendar.get(Calendar.WEEK_OF_MONTH) d. calendar.get(Calendar.WEEK_OF_YEAR) Key:d See Table 13.1. # 15. Assume Calendar calendar = new GregorianCalendar(). a. calendar.get(Calendar.MONTH) b. calendar.get(Calendar.MONTH_OF_YEAR) c. calendar.get(Calendar.WEEK_OF_MONTH) d. calendar.get(Calendar.WEEK_OF_YEAR) e. calendar.getActualMaximum(Calendar.DAY_OF_MONTH) Key:e See Table 13.1. # Section 13.5 Interfaces 16. Which of the following is a correct interface? ..

returns the week of the year.

returns the number of days in a month.


a. interface A { void print() { }; } b. abstract interface A { print(); } c. abstract interface A { abstract void print() { };} d. interface A { void print();} Key:d In A, the print() method in the interface is a concrete method. In B and C, the abstract keyword is used before the interface, which is wrong. The correct answer is D. # 17. Which of the following are incorrect? a. An abstract class contains constructors. b. The constructors in an abstract class should be protected. c. The constructors in an abstract class are private. d. You may declare a final abstract class. e. An interface may contain constructors. Key:cde A and B are correct. C is wrong. D is wrong. E is wrong because an interface does not have constructors. # 18. is not a reference type. a. A class type b. An interface type c. An array type d. A primitive type Key:d Objects and arrays are reference types. Primitive types are not. # 19.

Show the output of running the class Test in the following code lines:

interface A { } class C { } class D extends C { } class B extends D implements A { } public class Test { public static void main(String[] args) { B b = new B(); if (b instanceof A) System.out.println("b is an instance of A"); if (b instanceof C) System.out.println("b is an instance of C"); } } a. Nothing. b. b is an instance of A. c. b is an instance of C. d. b is an instance of A followed by b is an instance of C. Key:d B is an instance of A, becuase B implements A. B is an instance of C because B extends D and D extends C. ..


# 20. Suppose A is an interface, B is a concrete class with a no-arg constructor that implements A. Which of the following is correct? a. A a = new A(); b. A a = new B(); c. B b = new A(); d. B b = new B(); Key:bd Since B is a concrete class with a no-arg constructor, d is correct. Since an instance of B is also an instance of A, b is also correct. # Section 13.6 The Comparable Interface 21. Analyze the following code: public class Test1 { public Object max(Object o1, Object o2) { if ((Comparable)o1.compareTo(o2) >= 0) { return o1; } else { return o2; } } } a. The program has a compile error because Test1 does not have a main method. b. The program has a compile error because o1 is an Object instance and it does not have the compareTo method. c. The program has a compile error because you cannot cast an Object instance o1 into Comparable. d. The program would compile if ((Comparable)o1.compareTo(o2) >= 0) is replaced by (((Comparable)o1).compareTo(o2) >= 0). Key:bd The . operator is performed before casting. # 22. Which of the following statements are true? a. The String class implements Comparable. b. The Date class implements Comparable. c. The Double class implements Comparable. d. The BigInteger class implements Comparable. Key:abcd Many classes in the Java API implements the Comparable interface if the objects of the class can be compared. Strings, Dates, Doubles, and BigIntegers can all be compared. These classes implement the Comparable interface. # 23.

Analyze the following code.

1. public class Test { 2. public static void main(String[] args) { 3. Fruit[] fruits = {new Fruit(2), new Fruit(3), new Fruit(1)}; 4. java.util.Arrays.sort(fruits); 5. } 6. } class Fruit { private double weight; ..


public Fruit(double weight) { this.weight = weight; } } a. The program has a compile error because the Fruit class does not have a no-arg constructor. b. The program has a runtime error on Line 3 because the Fruit class does not have a no-arg constructor. c. The program has a compile error on Line 4 because the Fruit class does not implement the java.lang.Comparable interface and the Fruit objects are not comparable. d. The program has a runtime error on Line 4 because the Fruit class does not implement the java.lang.Comparable interface and the Fruit objects are not comparable. Key:d (A) and (B) are incorrect since it is OK to define a class without a no-arg constructor. (C) is incorrect since it is OK to pass fruits to Arrays.sort(Object[]) without compile errors. (D) is correct because the Arrays.sort method requires the objects in the array to be comparable and their class must implement the java.lang.Comparable interface. # Section 13.7 The Cloneable Interface 24. Analyze the following code. public class Test { public static void main(String[] args) { java.util.Date x = new java.util.Date(); java.util.Date y = x.clone(); System.out.println(x = y); } } a. A java.util.Date object is not cloneable. b. x = y in System.out.println(x = y) causes a compile error because you cannot have an assignment statement inside a statement. c. x = y in System.out.println(x = y) causes a runtime error because you cannot have an assignment statement inside a statement. d. The program has a compile error because the return type of the clone() method is java.lang.Object. Key:d (A) is wrong because Date implements and Cloneable and overrides the clone() method. (B) and (C) are wrong because x = y is an assignment expression, which assigns y to x. (D) is correct. You have to cast it into Date in order to assign it to y. # 25. The output from the following code is

.

java.util.ArrayList<String> list = new java.util.ArrayList<String>(); list.add("New York"); java.util.ArrayList<String> list1 = (java.util.ArrayList<String>)(list.clone()); list.add("Atlanta"); list1.add("Dallas"); System.out.println(list1); a. [New York] b. [New York, Atlanta] c. [New York, Atlanta, Dallas] d. [New York, Dallas] Key:d The code added New York to list and cloned list1 from list. list1 now contains New York. Dallas is added to list1. So list1 contains New Your and Dallas. # ..


26. The GeometricObject and Circle classes are defined in this chapter. Analyze the following code. Which statements are correct? public class Test { public static void main(String[] args) { GeometricObject x = new Circle(3); GeometricObject y = (Circle)(x.clone()); System.out.println(x); System.out.println(y); } } a. The program has a compile error because the clone() method is protected in the Object class. b. After you override the clone() method and make it public in the Circle class, the problem can compile and run just fine, but y is null if Circle does not implement the Cloneable interface. c. To enable a Circle object to be cloned, the Circle class has to override the clone() method and implement the java.lang.Cloneable interface. d. If GeometricObject implements Cloneable and Circle overrides the clone() method, the clone() method will work fine to clone Circle objects. Key:abcd All the choices are correct. # Section 13.8 Interfaces vs. Abstract Classes 27. Which of the following statements is false? a. If you compile an interface without errors, a .class file is created for the interface. b. If you compile a class without errors but with warnings, a .class file is created. c. If you compile a class with errors, a .class file is created for the class. d. If you compile an interface without errors, but with warnings, a .class file is created for the interface. Key:c A .class file is created for each Java class and interface. But if it has a compile error, no .class file is created. # 28. Which of the following statements are true? a. Inheritance models the is-a relationship between two classes. b. A strong is-a relationship describes a direct inheritance relationship between two classes. c. A weak is-a relationship describes that a class has certain properties. d. A strong is-a relationship can be represented using class inheritance. e. A weak is-a relationship can be represented using interfaces. Key:abcde All the choices are correct. # 29. What is the best suitable relationship between Employee and Faculty? a. Composition b. Aggregation c. Inheritance d. None. Key:c Faculty is an Employee. # 30. Assume an employee can work for only one company. What is the best suitable relationship between Company and Employee? a. None b. Aggregation c. Inheritance d. Composition Key:d An employee is dependent on the company in this case. ..


# 31. The relationship between an interface and the class that implements it is . a. Composition b. Aggregation c. Inheritance d. None Key:c Inheritance means a type is a subtype of something. If a class implements an interface. The class is a subtype of the interface. # Section 13.9 Case Study: The Rational Class 32. The Rational class in this chapter is defined as a subclass of java.lang.Number. Which of the following expressions is correct? a. Rational.doubleValue(); b. Rational.doubleValue("5/4"); c. new Rational(5, 4).doubleValue(); d. new Rational(5, 4).toDoubleValue(); e. new Rational(5, 4).intValue(); Key:ce A is wrong, because the doubleValue() method is an instance method. B is wrong for two reasons: 1. the doubleValue() method is an instance method; 2. the doubleValue() method does not have arguments. D is wrong becasue there is no method named toDoubleValue(). # 33. The Rational class in this chapter extends java.lang.Number and implements java.lang.Comparable. Analyze the following code. 1. public class Test { 2. public static void main(String[] args) { 3. Number[] numbers = {new Rational(1, 2), new Integer(4), new Double(5.6)}; 4. java.util.Arrays.sort(numbers); 5. } 6. } a. The program has a compile error because numbers is declared as Number[], so you cannot assign {new Rational(1, 2), new Integer(4), new Double(5.6)} to it. b. The program has a runtime error because numbers is declared as Number[], so you cannot assign {new Rational(1, 2), new Integer(4), new Double(5.6)} to it. c. The program has a compile error because numbers is declared as Number[], so you cannot pass it to Arrays.sort(Object[]). d. The program has a runtime error because the compareTo methods in Rational, Integer, and Double classes do not compare the value of one type with a value of another type. Key:d (A) and (B) are incorrect because Rational, Integer, and Double are subclasses of Number and any instances of these classes can be elements of the Number[] array. (C) is incorrect because it is fine to pass an instance of Number[] to a parameter of the Object[] type. (D) is correct because the compareTo method in Rational, Integer, Double only compare two Rational objects, two Integer objects, or two Double objects. # Section 13.10 Class Design Guidelines 34. Which of the following statements are true? a. A class should describe a single entity and all the class operations should logically fit together to support a coherent purpose. b. A class should always contain a no-arg constructor. c. The constructors must always be public. ..


d. The constructors may be protected. Key:ad (B) is not true. Most classes have a no-arg constructor. But sometimes, it does not make any sense to provide a no-arg constructor. For example, StringTokenizer does not have a no-arg constructor. (C) is not true. For example, the constructor in the Math class is private to prevent creating instances from the class, because there is no need to create instances for the Math class since all methods are static in Math. The constructors for abstract classes should be protected in most cases. # 35. Which of the following is poor design? a. A data field is derived from other data fields in the same class. b. A method must be invoked after/before invoking another method in the same class. c. A method is an instance method, but it does not reference any instance data fields or invoke instance methods. d. A parameter is passed from a constructor to initialize a static data field. Key:abcd A is not good because there is no need to define the data field if it can be derived from other data fields. B is not good because it is highly problematic to impose any order for invoking the methods. C is a bad design because in this case the method should be defined as static. D is not good because a static data field is now tied to the creation of a specific object, which should not be the case.

..


Chapter 14 JavaFX Basics Section 14.2 JavaFX vs Swing and AWT 1. Why is JavaFX preferred? a. JavaFX is much simpler to learn and use for new Java programmers. b. JavaFX provides a multi-touch support for touch-enabled devices such as tablets and smart phones. c. JavaFX has a built-in 3D, animation support, video and audio playback, and runs as a standalone application or from a browser. d. JavaFX incorporates modern GUI technologies to enable you to develop rich Internet applications. Key:abcd Read the two paragraphs in this section. # Section 14.3 The Basic Structure of a JavaFX Program 2. Every JavaFX main class . a. implements javafx.application.Application b. extends javafx.application.Application c. overrides start(Stage s) method d. overrides start() method Key:bc See Listing 14.1. # 3. Which of the following statements are true? a. A primary stage is automatically created when a JavaFX main class is launched. b. You can have multiple stages displayed in a JavaFX program. c. A stage is displayed by invoking the show() method on the stage. d. A scene is placed in the stage using the addScene method e. A scene is placed in the stage using the setScene method Key:abce See Listing 14.2. # 4. What is the output of the following JavaFX program? import javafx.application.Application; import javafx.stage.Stage; public class Test extends Application { public Test() { System.out.println("Test constructor is invoked."); } @Override // Override the start method in the Application class public void start(Stage primaryStage) { System.out.println("start method is invoked."); } public static void main(String[] args) { System.out.println("launch application."); Application.launch(args); } } a. launch application. start method is invoked. b. start method is invoked. Test constructor is invoked. c. Test constructor is invoked. start method is invoked. ..


d. launch application. start method is invoked. Test constructor is invoked. e. launch application. Test constructor is invoked. start method is invoked. Key:e See Listing 14.1. # Section 14.4 Panes, UI Controls, and Shapes 5. Which of the following statements are true? a. A Scene is a Node. b. A Shape is a Node. c. A Stage is a Node. d. A Control is a Node. e. A Pane is a Node. Key:bde See Figure 14.3. # 6. Which of the following statements are true? a. A Node can be placed in a Pane. b. A Node can be placed in a Scene. c. A Pane can be placed in a Control. d. A Shape can be placed in a Control. Key:a See Figure 14.3. # 7. Which of the following statements are correct? a. new Scene(new Button("OK")); b. new Scene(new Circle()); c. new Scene(new ImageView()); d. new Scene(new Pane()); Key:ad See Figure 14.3. # 8. To add a circle object into a pane, use a. pane.add(circle); b. pane.addAll(circle); c. pane.getChildren().add(circle); d. pane.getChildren().addAll(circle); Key:cd See Listing 14.3. # 9. Which of the following statements are correct? a. Every subclass of Node has a no-arg constructor. b. Circle is a subclass of Node. c. Button is a subclass of Node. d. Pane is a subclass of Node. e. Scene is a subclass on Node. Key:abcd See Listing 14.3. # Section 14.5 Binding Properties 10. Which of the following are binding properties? a. Integer b. Double c. IntegerProperty d. DoubleProperty ..

.


e. String Key:cd See Listing 14.6. # 11. Which of the following can be used as a source for binding properties? a. Integer b. Double c. IntegerProperty d. DoubleProperty e. String Key:cd See Listing 14.6. # 12. Suppose a JavaFX class has a binding property named weight of the type DoubleProperty. By convention, which of the following methods are defined in the class? a. public double getWeight() b. public void setWeight(double v) c. public DoubleProperty weightProperty() d. public double weightProperty() e. public DoubleProperty WeightProperty() Key:abc See Listing 14.5. # 13. What is the output of the following code? import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; public class Test { public static void main(String[] args) { IntegerProperty d1 = new SimpleIntegerProperty(1); IntegerProperty d2 = new SimpleIntegerProperty(2); d1.bind(d2); System.out.print("d1 is " + d1.getValue() + " and d2 is " + d2.getValue()); d2.setValue(3); System.out.println(", d1 is " + d1.getValue() + " and d2 is " + d2.getValue()); } } a. d1 is 2 and d2 is 2, d1 is 3 and d2 is 3 b. d1 is 2 and d2 is 2, d1 is 2 and d2 is 3 c. d1 is 1 and d2 is 2, d1 is 1 and d2 is 3 d. d1 is 1 and d2 is 2, d1 is 3 and d2 is 3 Key:a See Listing 14.6. # 14. What is the output of the following code? import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; public class Test { ..


public static void main(String[] args) { IntegerProperty d1 = new SimpleIntegerProperty(1); IntegerProperty d2 = new SimpleIntegerProperty(2); d1.bindBidirectional(d2); System.out.print("d1 is " + d1.getValue() + " and d2 is " + d2.getValue()); d1.setValue(3); System.out.println(", d1 is " + d1.getValue() + " and d2 is " + d2.getValue()); } } a. d1 is 2 and d2 is 2, d1 is 3 and d2 is 3 b. d1 is 2 and d2 is 2, d1 is 2 and d2 is 3 c. d1 is 1 and d2 is 2, d1 is 1 and d2 is 3 d. d1 is 1 and d2 is 2, d1 is 3 and d2 is 3 Key:a See Listing 14.6. # Section 14.6 Common Properties and Methods for Nodes 15. Which of the following statements correctly sets the fill color of circle to black? a. circle.setFill(Color.BLACK); b. circle.setFill(Color.black); c. circle.setStyle("-fx-fill: black"); d. circle.setStyle("fill: black"); e. circle.setStyle("-fx-fill-color: black"); Key:ac See Listing 14.7. # 16. Which of the following statements correctly rotates the button 45 degrees counterclockwise? a. button.setRotate(45); b. button.setRotate(Math.toRadians(45)); c. button.setRotate(360 - 45); d. button.setRotate(-45); Key:cd See Listing 14.7. # Section 14.7 The Color Class 17. Which of the following statements correctly creates a Color object? a. new Color(3, 5, 5, 1); b. new Color(0.3, 0.5, 0.5, 0.1); c. new Color(0.3, 0.5, 0.5); d. Color.color(0.3, 0.5, 0.5); e. Color.color(0.3, 0.5, 0.5, 0.1); Key:bde See Figure 14.9. # Section 14.8 The Font Class 18. Which of the following statements correctly creates a Font object? a. new Font(34); b. new Font("Times", 34); c. Font.font("Times", 34); d. Font.font("Times", FontWeight.NORMAL, 34); e. Font.font("Times", FontWeight.NORMAL, FontPosture.ITALIC, 34); ..


Key:abcde See Figure 14.10. # 19. Which of the following statements are correct? a. A Color object is immutable. b. A Font object is immutable. c. You cannot change the contents in a Color object once it is created. d. You cannot change the contents in a Font object once it is created. Key:abcd See Figure 14.10. # Section 14.9 The Image and ImageView Classes 20. Which of the following statements correctly creates an ImageView object? a. new ImageView("http://www.cs.armstrong.edu/liang/image/us.gif"); b. new ImageView(new Image("http://www.cs.armstrong.edu/liang/image/us.gif")); c. new ImageView("image/us.gif"); d. new ImageView(new Image("image/us.gif")); Key:abcd See Listing 14.9. # 21. Analyze the following code: import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.geometry.Insets; import javafx.stage.Stage; import javafx.scene.image.Image; import javafx.scene.image.ImageView; public class Test extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { // Create a pane to hold the image views Pane pane = new HBox(10); pane.setPadding(new Insets(5, 5, 5, 5)); Image image = new Image("www.cs.armstrong.edu/liang/image/us.gif"); pane.getChildren().addAll(new ImageView(image), new ImageView(image)); // Create a scene and place it in the stage Scene scene = new Scene(pane); primaryStage.setTitle("ShowImage"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } /** * The main method is only needed for the IDE with limited * JavaFX support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } ..


} a. The program runs fine and displays two images. b. new Image("www.cs.armstrong.edu/liang/image/us.gif") must be replaced by new Image("http://www.cs.armstrong.edu/liang/image/us.gif"). c. The image object cannot be shared by two ImageViews. d. The addAll method needs to be replaced by the add method. Key:b See Listing 14.9. # Section 14.10 Layout Panes Section 14.10.1 FlowPane 22. To add a node into a pane, use a. pane.add(node); b. pane.addAll(node); c. pane.getChildren().add(node); d. pane.getChildren().addAll(node); Key:cd See Listing 14.10.

.

# 23. To add two nodes node1 and node2 into a pane, use a. pane.add(node1, node2); b. pane.addAll(node1, node2); c. pane.getChildren().add(node1, node2); d. pane.getChildren().addAll(node1, node2); Key:d See Listing 14.10. # 24. To remove a node from the pane, use a. pane.remove(node); b. pane.removeAll(node); c. pane.getChildren().remove(node); d. pane.getChildren().removeAll(node); Key:cd See Listing 14.10.

.

.

# 25. To remove two nodes node1 and node2 from a pane, use a. pane.remove(node1, node2); b. pane.removeAll(node1, node2); c. pane.getChildren().remove(node1, node2); d. pane.getChildren().removeAll(node1, node2); Key:d See Listing 14.10.

.

# 26. Which of the following statements are correct to create a FlowPane? a. new FlowPane() b. new FlowPane(4, 5) c. new FlowPane(Orientation.VERTICAL); d. new FlowPane(4, 5, Orientation.VERTICAL); Key:abcd See Listing 14.10. # Section 14.10.2 GridPane 27. To add a node to the the first row and second column in a GridPane pane, use a. pane.getChildren().add(node, 1, 2); ..

.


b. pane.add(node, 1, 2); c. pane.getChildren().add(node, 0, 1); d. pane.add(node, 0, 1); e. pane.add(node, 1, 0); Key:e See Listing 14.11. # 28. To add two nodes node1 and node2 to the the first row in a GridPane pane, use a. pane.add(node1, 0, 0); pane.add(node2, 1, 0); b. pane.add(node1, node2, 0); c. pane.addRow(0, node1, node2); d. pane.addRow(1, node1, node2); e. pane.add(node1, 0, 1); pane.add(node2, 1, 1); Key:ac See Listing 14.11. # Section 14.10.3 BorderPane 29. To place a node in the left of a BorderPane p, use a. p.setEast(node); b. p.placeLeft(node); c. p.setLeft(node); d. p.left(node); Key:c See Listing 14.12. # Section 14.10.4 HBox and VBox 30. To place two nodes node1 and node2 in a HBox p, use a. p.add(node1, node2); b. p.addAll(node1, node2); c. p.getChildren().add(node1, node2); d. p.getChildren().addAll(node1, node2); Key:d See Listing 14.13. # 31. Analyze the following code: import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.layout.HBox; import javafx.scene.shape.Circle; public class Test extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { HBox pane = new HBox(5); Circle circle = new Circle(50, 200, 200); pane.getChildren().addAll(circle); circle.setCenterX(100); circle.setCenterY(100); circle.setRadius(50); pane.getChildren().addAll(circle);

..

.

.

.


// Create a scene and place it in the stage Scene scene = new Scene(pane); primaryStage.setTitle("Test"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } /** * The main method is only needed for the IDE with limited * JavaFX support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } } a. The program has a compile error since the circle is added to a pane twice. b. The program has a runtime error since the circle is added to a pane twice. c. The program runs fine and displays one circle. d. The program runs fine and displays two circles. Key:a See Listing 14.13. # Section 14.11 Shapes 32. The properties are defined in the javafx.scene.shape.Shape class. a. stroke b. strokeWidth c. fill d. centerX Key:abc See the first paragraph. # Section 14.11.1 Text 33. The properties are defined in the javafx.scene.text.Text class. a. text b. x c. y d. underline e. strikethrough Key:abcde See Figure 14.26. # Section 14.11.2 Line 34. The properties are defined in the javafx.scene.shape.Line class. a. x1 b. x2 c. y1 d. y2 e. strikethrough Key:abcd See Figure 14.28. # Section 14.11.3 Rectangle 35. The properties are defined in the javafx.scene.shape.Rectangle class. a. width ..


b. x c. y d. height e. arcWidth Key:abcde See Figure 14.30. # Section 14.11.4 Circle and Ellipse 36. The properties are defined in the javafx.scene.shape.Ellipse class. a. centerX b. centerY c. radiusX d. radiusY Key:abcd See Figure 14.33. # Section 14.11.5 Arc 36. The properties are defined in the javafx.scene.shape.Ellipse class. a. centerX b. centerY c. radiusX d. radiusY e. startAngle Key:abcde See Figure 14.35. # Section 14.11.6 Polygon and Polyline 37. To construct a Polygon with three points x1, y1, x2, y2, x3, and y3, use . a. new Polygon(x1, y1, x2, y2, x3, y3) b. new Polygon(x1, y2, x3, y1, y2, y3) c. Polygon polygon = new Polygon(); polygon.getPoints().addAll(x1, y1, x2, y2, x3, y3) d. Polygon polygon = new Polygon(); polygon.getPoints().addAll(x1, y2, x3, y1, y2, y3) Key:ac See Figure 14.39. # 38. To construct a Polyline with three points x1, y1, x2, y2, x3, and y3, use . a. new Polyline(x1, y1, x2, y2, x3, y3) b. new Polyline(x1, y2, x3, y1, y2, y3) c. Polyline polyline = new Polygon(); polyline.getPoints().addAll(x1, y1, x2, y2, x3, y3) d. Polyline polyline = new Polygon(); polyline.getPoints().addAll(x1, y2, x3, y1, y2, y3) Key:ac See Figure 14.39. # 39. Assume p is a Polygon, to add a point (4, 5) into p, use . a. p.getPoints().add(4); p.getPoints().add(5); b. p.getPoints().add(4.0); p.getPoints().add(5.0); c. p.getPoints().addAll(4, 5); d. p.getPoints().addAll(4.0, 5.0); Key:bd Note that the getPoints() method in Polygon returns an ObservableList<Double> (see Figure 14.39). When you add a value to the list, the value must be a double value. It will be an error if it is int value. For example, Double d = 4 is wrong. It should be Double d = 4.0.

..


Chapter 15 Event-Driven Programming and Animations Section 15.2 Events and Event Sources 1. A JavaFX action event handler is an instance of a. ActionEvent b. Action c. EventHandler d. EventHandler<ActionEvent> Key:d See Table 15.1.

.

# 2. A JavaFX action event handler contains a method a. public void actionPerformed(ActionEvent e) b. public void actionPerformed(Event e) c. public void handle(ActionEvent e) d. public void handle(Event e) Key:c See Table 15.1. # 3. A JavaFX event handler for event type T is an instance of a. ActionEvent b. Action c. EventHandler d. EventHandler<T> Key:d See Table 15.1.

.

.

# 4. Which of the following are the classes in JavaFX for representing an event? a. ActionEvent b. MouseEvent c. KeyEvent d. WindowEvent Key:abcd All choices are correct. # Section 15.3 Registering Handlers and Handling Events 5. To register a source for an action event with a handler, use a. source.addAction(handler) b. source.setOnAction(handler) c. source.addOnAction(handler) d. source.setActionHandler(handler) Key:b Listing 15.2. # 6. Which of the following statements are true? a. A handler object fires an event. b. A source object fires an event. c. Any object such a String object can fire an event. d. A handler is registered with the source object for processing the event. Key:bd Listing 15.2. # 7.

Which of the following statements are true? ..

.


a. A Button can fire an ActionEvent. b. A Button can fire a MouseEvent. c. A Button can fire a KeyEvent. d. A TextField can fire an ActionEvent. Key:abcd All choices are correct. # 8. Which of the following statements are true? a. A Node can fire an ActionEvent. b. A Node can fire a MouseEvent. c. A Node can fire a KeyEvent. d. A Scene can fire a MouseEvent. Key:abcd All choices are correct. # 9. Which of the following statements are true? a. A Shape can fire an ActionEvent. b. A Shape can fire a MouseEvent. c. A Shape can fire a KeyEvent. d. A Text is a Shape. e. A Circle is a Shape. Key:bcde All choices are correct except (A). # Section 15.4 Inner Classes 10. Which of the following statements are true? a. Inner classes can make programs simple and concise. b. An inner class can be declared public or private subject to the same visibility rules applied to a member of the class. c. An inner class can be declared static. A static inner class can be accessed using the outer class name. A static inner class cannot access nonstatic members of the outer class. d. An inner class supports the work of its containing outer class and is compiled into a class named OuterClassName$InnerClassName.class. Key:abcd All choices are correct. See the bullet items. # 11. Suppose A is an inner class in Test. A is compiled into a file named a. A.class b. Test$A.class c. A$Test.class d. Test&A.class Key:b See See the bullet items. # 12. Which statement is true about a non-static inner class? a. It must implement an interface. b. It is accessible from any other class. c. It can only be instantiated in the enclosing class. d. It must be final if it is declared in a method scope. e. It can access private instance variables in the enclosing object. Key:e See bullet items. # Section 15.5 Anonymous Class Handlers 13. Which of the following statements are true? ..

.


a. An anonymous inner class is an inner class without a name. b. An anonymous inner class must always extend a superclass or implement an interface, but it cannot have an explicit extends or implements clause. c. An anonymous inner class must implement all the abstract methods in the superclass or in the interface. d. An anonymous inner class always uses the no-arg constructor from its superclass to create an instance. If an anonymous inner class implements an interface, the constructor is Object(). e. An anonymous inner class is compiled into a class named OuterClassName$n.class. Key:abcde See bullet items. # 14. Suppose A is an anonymous inner class in Test. A is compiled into a file named a. A.class b. Test$A.class c. A$Test.class d. Test$1.class e. Test&1.class Key:d See bullet items. # 15. Analyze the following code. import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.stage.Stage; public class Test extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { Button btOK = new Button("OK"); btOK.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { System.out.println("The OK button is clicked"); } }); Scene scene = new Scene(btOK, 200, 250); primaryStage.setTitle("MyJavaFX"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } /** * The main method is only needed for the IDE with limited JavaFX * support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } } a. The program has a compile error because no handlers are registered with btOK. ..

.


b. The program has a runtime error because no handlers are registered with btOK. c. The message "The OK button is clicked" is displayed when you click the OK button. d. The handle method is not executed when you click the OK button, because no handler is registered with btOK. Key:c See Listing 15.4. # 16. Analyze the following code. import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class Test extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { Button btOK = new Button("OK"); Button btCancel = new Button("Cancel"); EventHandler<ActionEvent> handler = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { System.out.println("The OK button is clicked"); } }; btOK.setOnAction(handler); btCancel.setOnAction(handler); HBox pane = new HBox(5); pane.getChildren().addAll(btOK, btCancel); Scene scene = new Scene(pane, 200, 250); primaryStage.setTitle("Test"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } /** * The main method is only needed for the IDE with limited JavaFX * support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } } a. When clicking the OK button, the program displays The OK button is clicked. b. When clicking the Cancel button, the program displays The OK button is clicked. c. When clicking either button, the program displays The OK button is clicked twice. d. The program has a runtime error, because the handler is registered with more than one source. Key:ab See Listing 15.4.

..


# Section 15.6 Simplifying Event Handing Using Lambda Expressions 17. Analyze the following code. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.stage.Stage; public class Test extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { // Create a button and place it in the scene Button btOK = new Button("OK"); btOK.setOnAction(e -> System.out.println("OK 1")); btOK.setOnAction(e -> System.out.println("OK 2")); Scene scene = new Scene(btOK, 200, 250); primaryStage.setTitle("MyJavaFX"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } /** * The main method is only needed for the IDE with limited JavaFX * support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } } a. When clicking the button, the program displays OK1 OK2. b. When clicking the button, the program displays OK1. c. When clicking the button, the program displays OK2. d. The program has a compile error, because the setOnAction method is invoked twice. Key:c See Listing 15.5. # 18. Which of the following code correctly registers a handler with a button btOK? a. btOK.setOnAction(e -> System.out.println("Handle the event")); b. btOK.setOnAction((e) -> System.out.println("Handle the event");); c. btOK.setOnAction((ActionEvent e) -> System.out.println("Handle the event")); d. btOK.setOnAction(e -> {System.out.println("Handle the event");}); Key:abcd See Listing 15.5. # 19. Fill in the code below in the underline: public class Test { public static void main(String[] args) { Test test = new Test(); test.setAction( }

..

);


public void setAction(T1 t) { t.m(); } } interface T1 { public void m(); } a. () -> System.out.print("Action 1! ") b. (e) -> System.out.print("Action 1! ") c. System.out.print("Action 1! ") d. (e) -> {System.out.print("Action 1! ")} Key:a See Listing 15.5. # 20. Fill in the code below in the underline: public class Test { public static void main(String[] args) { Test test = new Test(); test.setAction2( }

);

public void setAction2(T2 t) { t.m(4.5); } } interface T2 { public void m(Double d); } a. () -> System.out.print(e) b. (e) -> System.out.print(e) c. e -> System.out.print(e) d. (e) -> {System.out.print(e);} Key:bcd See Listing 15.5. # 21. Fill in the code below in the underline: public class Test { public static void main(String[] args) { Test test = new Test(); System.out.println(test.setAction3( } public double setAction3(T3 t) { return t.m(5.5); } } interface T3 { public double m(Double d); ..

));


} a. () -> e * 2 b. (e) -> e * 2 c. e -> e * 2 d. (e) -> {e * 2;} Key:bc See Listing 15.5. # 22. Analyze the following code: public class Test { public static void main(String[] args) { Test test = new Test(); test.setAction(() -> System.out.print("Action 1! ")); } public void setAction(T t) { t.m1(); } } interface T { public void m1(); public void m2(); } a. The program displays Action 1. b. The program has a compile error because T is not a functional interface. T contains multiple methods. c. The program would work if you delete the method m2 from the interface T. d. The program has a runtime error because T is not a functional interface. T contains multiple methods. Key:bc See Listing 15.5. # Section 15.8 Mouse Events 23. To handle the mouse click event on a pane p, register the handler with p using a. p.setOnMouseClicked(handler); b. p.setOnMouseDragged(handler); c. p.setOnMouseReleased(handler); d. p.setOnMousePressed(handler); Key:a

.

# 24. Fill in the code in the underlined location to display the mouse point location when the mouse is pressed in the pane. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Stage; public class Test extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { Pane pane = new Pane(); ..


Scene scene = new Scene(pane, 200, 250); primaryStage.setTitle("Test"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } /** * The main method is only needed for the IDE with limited JavaFX * support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } } a. pane.setOnMouseClicked((e) -> System.out.println(e.getX() + ", " + e.getY())); b. pane.setOnMouseReleased(e -> {System.out.println(e.getX() + ", " + e.getY())}); c. pane.setOnMousePressed(e -> System.out.println(e.getX() + ", " + e.getY())); d. pane.setOnMouseDragged((e) -> System.out.println(e.getX() + ", " + e.getY())); Key:c See Listing 15.8. # Section 15.9 Key Events 25. To handle the key pressed event on a pane p, register the handler with p using a. p.setOnKeyClicked(handler); b. p.setOnKeyTyped(handler); c. p.setOnKeyReleased(handler); d. p.setOnKeyPressed(handler); Key:d See Listing 15.9. # 26. Fill in the code to display the key pressed in the text. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.scene.text.Text; import javafx.stage.Stage; public class Test extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { Pane pane = new Pane(); Text text = new Text(20, 20, "Welcome"); pane.getChildren().add(text); Scene scene = new Scene(pane, 200, 250); primaryStage.setTitle("Test"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage text.setFocusTraversable(true); text.setOnKeyPressed( } ..

);

.


/** * The main method is only needed for the IDE with limited JavaFX * support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } } a. () -> text.setText(e.getText()) b. (e) -> text.setText(e.getText()) c. e -> text.setText(e.getText()) d. e -> {text.setText(e.getText());} Key:bcd See Listing 15.9. # 27. Suppose the following program displays a pane in the stage. What is the output if the user presses the key for letter B? import javafx.application.Application; import static javafx.application.Application.launch; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Stage; // import javafx classes omitted public class Test1 extends Application { @Override public void start(Stage primaryStage) { // Code to create and display pane omitted Pane pane = new Pane(); Scene scene = new Scene(pane, 200, 250); primaryStage.setTitle("MyJavaFX"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage pane.requestFocus(); pane.setOnKeyPressed(e -> System.out.print("Key pressed " + e.getCode() + " ")); pane.setOnKeyTyped(e -> System.out.println("Key typed " + e.getCode())); } /** * The main method is only needed for the IDE with limited * JavaFX support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } } a. Key pressed B Key typed UNDEFINED b. Key pressed B Key typed ..


c. Key typed UNDEFINED d. Key pressed B Key:a See Listing 15.9. # 28. Suppose the follwoing program displays a pane in the stage. What is the output if the user presses the DOWN arrow key? import javafx.application.Application; import static javafx.application.Application.launch; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Stage; // import javafx classes omitted public class Test1 extends Application { @Override public void start(Stage primaryStage) { // Code to create and display pane omitted Pane pane = new Pane(); Scene scene = new Scene(pane, 200, 250); primaryStage.setTitle("MyJavaFX"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage pane.requestFocus(); pane.setOnKeyPressed(e -> System.out.print("Key pressed " + e.getCode() + " ")); pane.setOnKeyTyped(e -> System.out.println("Key typed " + e.getCode())); } /** * The main method is only needed for the IDE with limited * JavaFX support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } } a. Key pressed DOWN Key typed UNDEFINED b. Key pressed DOWN Key typed c. Key typed UNDEFINED d. Key pressed DOWN Key:d See Listing 15.9. # Section 15.10 Listeners for Observable Objects 29. Analyze the following code: import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleDoubleProperty; public class Test { ..


public static void main(String[] args) { DoubleProperty balance = new SimpleDoubleProperty(); balance.addListener(ov -> System.out.println(2 + balance.doubleValue())); balance.set(4.5); } } a. The program displays 4.5. b. The program displays 6.5. c. The program would display 4.5 if the balance.set(4.5) is placed before the balance.addListener(...) statement. d. The program would display 6.5 if the balance.set(4.5) is placed before the balance.addListener(...) statement. Key:b See Listing 15.10. # Section 15.11 Animation 30. Which of the following methods is not defined in the Animation class? a. pause() b. play() c. stop() d. resume() Key:d See Figure 15.16. # 31. The properties are defined in the Animation class. a. autoReverse b. cycleCount c. rate d. status Key:abcd See Figure 15.16. # Section 15.11.1 PathTransition 32. The properties are defined in the PathTransition class. a. duration b. node c. orientation d. path Key:abcd See Figure 15.17. # Section 15.11.2 FadeTransition 33. To properties are defined in the FadeTransition class. a. duration b. node c. fromValue d. toValue e. byValue Key:abcde See Figure 15.19. # Section 15.11.3 Timeline 34. To create a KeyFrame with duration 1 second, use a. new KeyFrame(1000, handler) ..

.


b. new KeyFrame(1, handler) c. new KeyFrame(Duration.millis(1000), handler) d. new KeyFrame(Duration.seconds(1), handler) Key:cd See Listing 15.16. # 35. is a subclass of Animation. a. PathTransition b. FadeTransition c. Timeline d. Duration Key:abc See Listing 15.16.

..


Chapter 16 JavaFX UI Controls and Multimedia Section 16.2 Labeled and Label 1. To create a label with the specified text, use a. new Labelled(); b. new Label(); c. new Labelled(text); d. new Label(text); Key:d See Figure Figure 16.3. # 2. To set a red color for the text in the label lbl, use a. lbl.setFill(Color.red); b. lbl.setTextFill(Color.red); c. lbl.setFill(Color.RED); d. lbl.setTextFill(Color.RED); Key:d See Figure Figure 16.2.

.

.

# 3. are properties in Labelled. a. alignment b. contentDisplay c. graphic d. text e. underline Key:abcde See Figure Figure 16.2. # 4. To set the node to the right of the text in a label lbl, use a. lbl.setContentDisplay(ContentDisplay.TOP); b. lbl.setContentDisplay(ContentDisplay.BOTTOM); c. lbl.setContentDisplay(ContentDisplay.LEFT); d. lbl.setContentDisplay(ContentDisplay.RIGHT); Key:d See Figure Figure 16.2. # 6. is a superclass for Label. a. Scene b. Labelled c. ButtonBase d. Control e. Node Key:bde See Figure Figure 16.5. # Section 16.3 Button 8. Analyze the following code: import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; ..

.


import javafx.scene.layout.HBox; import javafx.stage.Stage; public class Test extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { HBox pane = new HBox(5); Image usIcon = new Image("http://www.cs.armstrong.edu/liang/image/usIcon.gif"); Button bt1 = new Button("Button1", new ImageView(usIcon)); Button bt2 = new Button("Button2", new ImageView(usIcon)); pane.getChildren().addAll(bt1, bt2); Scene scene = new Scene(pane, 200, 250); primaryStage.setTitle("Test"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } /** * The main method is only needed for the IDE with limited JavaFX * support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } } a. Two buttons displayed with the same icon. b. Only bt2 displays the icon and bt1 does not display the icon. c. Only bt1 displays the icon and bt2 does not display the icon. d. Two buttons displayed with different icons. Key:a Since images can be shared, both bt1 and bt2 display the same icon. # 9.

Analyze the following code:

import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class Test extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { StackPane pane = new StackPane(); Button bt1 = new Button("Java"); Button bt2 = new Button("Java"); Button bt3 = new Button("Java"); Button bt4 = new Button("Java"); pane.getChildren().addAll(bt1, bt2, bt3, bt4); Scene scene = new Scene(pane, 200, 250); primaryStage.setTitle("Test"); // Set the stage title ..


primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } /** * The main method is only needed for the IDE with limited JavaFX * support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } } a. One button is displayed with the text "Java". b. Two buttons are displayed with the same text "Java". c. Three buttons are displayed with the same text "Java". d. Four buttons are displayed with the same text "Java". Key:a Because you are using a StackPane. # 10.

Analyze the following code:

import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.Pane; import javafx.scene.layout.FlowPane; import javafx.stage.Stage; public class Test extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { Pane pane = new FlowPane(); Button bt1 = new Button("Java"); Button bt2 = new Button("Java"); Button bt3 = new Button("Java"); Button bt4 = new Button("Java"); pane.getChildren().addAll(bt1, bt2, bt3, bt4); Scene scene = new Scene(pane, 200, 250); primaryStage.setTitle("Test"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } /** * The main method is only needed for the IDE with limited JavaFX * support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } } a. One button is displayed with the text "Java". b. Two buttons are displayed with the same text "Java". ..


c. Three buttons are displayed with the same text "Java". d. Four buttons are displayed with the same text "Java". Key:d # 5. is a superclass for Button. a. Label b. Labelled c. ButtonBase d. Control e. Node Key:bcde See Figure Figure 16.5. # 7. The setOnAction method is defined in a. Label b. Labelled c. Node d. ButtonBase e. Button Key:d See Figure Figure 16.5.

.

# Section 16.4 CheckBox 11. checks whether the CheckBox chk is selected. a. chk.getSelected() b. chk.selected() c. chk.isSelected(). d. chk.select() Key:c See Listing 16.3. # 12. Which of the following statements are true? a. CheckBox inherits from ButtonBase. b. CheckBox inherits from Button. c. CheckBox inherits from Labelled. d. CheckBox inherits from Control. e. CheckBox inherits from Node. Key:acde See Figure 16.7. # Section 16.5 RadioButton 13. Which of the following statements are true? a. RadioButton inherits from ButtonBase. b. RadioButton inherits from Button. c. RadioButton inherits from Labelled. d. RadioButton inherits from Control. e. RadioButton inherits from Node. Key:acde See Figure 16.9. # 14. checks whether the RadioButton rb is selected. a. rb.getSelected() b. rb.selected() ..


c. rb.isSelected(). d. rb.select() Key:c See Listing 16.4. # 15. Analyze the following code: import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.RadioButton; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.FlowPane; import javafx.scene.layout.Pane; import javafx.stage.Stage; public class Test extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { Pane pane = new FlowPane(); ToggleGroup group = new ToggleGroup(); RadioButton rb1 = new RadioButton("Java"); RadioButton rb2 = new RadioButton("C++"); pane.getChildren().addAll(rb1, rb2); Scene scene = new Scene(pane, 200, 250); primaryStage.setTitle("Test"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } /** * The main method is only needed for the IDE with limited JavaFX * support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } } a. The program displays two radio buttons. The two radio buttons are grouped. b. The program displays one radio button with text Java. c. The program displays two radio buttons. The two radio buttons are not grouped. d. The program displays one radio button with text C++. Key:c To group the two use rb1.setToggleGroup(group); rb2.setToggleGroup(group); # Section 16.6 TextField 16. Which of the following statements are true? a. TextField inherits from TextInputControl. b. TextField inherits from ButtonBase. c. TextField inherits from Labelled. d. TextField inherits from Control. e. TextField inherits from Node. Key:ade ..


# 17. The properties a. text b. editable c. alignment d. prefColumnCount e. onAction Key:abcde See Figure 16.11.

can be used in a TextField.

# 18. Which of the following statements are true? a. You can specify a horizontal text alignment in a text field. b. You can specify the number of columns in a text field. c. You can disable editing on a text field. d. You can create a text field with a specified text. Key:abcd See Listing 16.5. # 19. The method a. tf.getText(s) b. tf.getText() c. tf.getString() d. tf.findString() Key:b See Listing 16.5.

gets the contents of the text field tf.

# 20. Which of the following statements are true? a. PasswordField inherits from TextInputControl. b. PasswordField inherits from TextField. c. PasswordField inherits from Labelled. d. PasswordField inherits from Control. e. PasswordField inherits from Node. Key:abde See the Note box at the end of the section. # Section 16.7 TextArea 22. Which of the following statements are true? a. You can specify a horizontal text alignment in a text area. b. You can specify the number of columns in a text area. c. You can disable editing on a text area. d. You can create a text field with a specified text area. e. You can specify the number of rows in a text area. Key:bcde See Figure 16.13. # 23. To wrap a line in a text area ta, invoke a. ta.setLineWrap(false) b. ta.setLineWrap(true) c. ta.WrapLine() d. ta.wrapText() e. ta.setWrapText(true) Key:e See Figure 16.13.

..

.


# 24. To wrap a line in a text area jta on words, invoke a. jta.setWrapStyleWord(false) b. jta.setWrapStyleWord(true) c. jta.wrapStyleWord() d. jta.wrapWord() Key:b See Figure 16.13. # 21. The method a. ta.setText(s) b. ta.appendText(s) c. ta.append(s) d. ta.insertText(s) Key:b

.

appends a string s into the text area ta.

# 25. Which of the following statements are true? a. TextArea inherits from TextInputControl. b. TextArea inherits from TextField. c. TextArea inherits from Labelled. d. TextArea inherits from Control. e. TextArea inherits from Node. Key:ade # Section 16.8 ComboBox 28. returns the selected item on a ComboBox cbo. a. cbo.getSelectedIndex() b. cbo.getSelectedItem() c. cbo.getSelectedIndices() d. cbo.getSelectedItems() e. cbo.getValue() Key:e See Listing 16.8. # 29. The method a. cbo.add(s) b. cbo.addChoice(s) c. cbo.addItem(s) d. cbo.addObject(s) e. cbo.getItems().add(s) Key:e See Listing 16.8.

adds an item s into a ComboBox cbo.

# 30. Which of the following statements are true? a. ComboBox inherits from ComboBoxBase. b. ComboBox inherits from ButtonBase. c. ComboBox inherits from Labelled. d. ComboBox inherits from Control. e. ComboBox inherits from Node. Key:ade # ..


31. You can use the a. value b. editable c. onAction d. items e. visibleRowCount Key:abcde See Figure 16.6.

properties in a ComboBox.

# 26. How many items can be added into a ComboBox object? a. 0 b. 1 c. 2 d. Unlimited Key:d # 27. How many items can be selected from a ComboBox at a time? a. 0 b. 1 c. 2 d. Unlimited Key:b # Section 16.9 ListView 32. are properties for a ListView. a. items b. orientation c. selectionModel d. visibleRowCount e. onAction Key:abc See Figure 16.18. # 33. Which of the following statements are true? a. ListView inherits from ComboBoxBase. b. ListView inherits from ButtonBase. c. ListView inherits from Labelled. d. ListView inherits from Control. e. ListView inherits from Node. Key:de See Figure 16.18. # 34. The statement for registering a listener for processing list view item change is a. lv.getItems().addListener(e -> {processStatements}); b. lv.addListener(e -> {processStatements}); c. lv.getSelectionModel().selectedItemProperty().addListener(e -> {processStatements}); d. lv.getSelectionModel().addListener(e -> {processStatements}); Key:c See Listing 16.9. # Section 16.10 ScrollBar 35. are properties of ScrollBar. ..

.


a. value b. min c. max d. orientation e. visibleAmount Key:abcde See Figure 16.22. # 36. The statement for registering a listener for processing scroll bar value change is a. sb.addListener(e -> {processStatements}); b. sb.getValue().addListener(e -> {processStatements}); c. sb.valueProperty().addListener(e -> {processStatements}); d. sb.getItems().addListener(e -> {processStatements}); Key:c See Listing 16.10.

.

# Section 16.11 Slider 37. are properties of Slider. a. value b. min c. max d. orientation e. visibleAmount Key:abcde See Figure 16.25. # 38. The statement for registering a listener for processing slider change is a. sl.addListener(e -> {processStatements}); b. sl.getValue().addListener(e -> {processStatements}); c. sl.valueProperty().addListener(e -> {processStatements}); d. sl.getItems().addListener(e -> {processStatements}); Key:c See Listing 16.11. # Section 16.13 Video and Audio 39. Which of the following statements are true? a. A Media can be shared by multiple MediaPlayer. b. A MediaPlayer can be shared by multiple MediaView. c. A MediaView can be placed into multiple Pane. d. A Media can be downloaded from a URL. Key:abd See the first three paragraphs. # 40. You can use the methods a. start(). b. stop(). c. pause(). d. play(). Key:cd See Figure 16.31. # 41. a. b. ..

You can use the properties autoPlay currentCount

to control a MediaPlayer.

to control a MediaPlayer.

.


c. cycleCount d. mute e. volume Key:abcde See Figure 16.31. # 42. You can use the properties a. x b. y c. mediaPlayer d. fitWidth e. fitHeight Key:abcde See Figure 16.32.

..

in a MediaView.


Chapter 17 Binary I/O Section 17.2 How is I/O Handled in Java? 1. Which of the following statements are true? a. A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing. b. You can use the PrintWriter class for outputting text to a file. c. You can use the Scanner class for reading text from a file. d. An input object is also called an input stream. e. An output object is also called an output stream. Key:abcde Read the text in this section. # Section 17.3 Text I/O vs. Binary I/O 2. Which of the following statements are true? a. Text I/O is built upon binary I/O to provide a level of abstraction for character encoding and decoding. b. Text I/O involves encoding and decoding. c. Binary I/O does not require conversions. d. Binary I/O is more efficient than text I/O, because binary I/O does not require encoding and decoding. e. Binary files are independent of the encoding scheme on the host machine and thus are portable. Key:abcde See Figure 17.2. # Section 17.4 Binary I/O Classes 3. Which method can you use to find out the number of the bytes in a file using InputStream? a. length() b. available() c. size() d. getSize() Key:b See Figure 17.4. # Section 17.4.1 FileInputStream/FileOutputStream 4. Which of the following statements are true? a. All methods in FileInputStream/FileOutputStream are inherited from InputStream/OutputStream. b. You can create a FileInputStream/FileOutputStream from a File object or a file name using FileInputStream/FileOutputStream constructors. c. The return value -1 from the read() method signifies the end of file. d. A java.io.FileNotFoundException would occur if you attempt to create a FileInputStream with a nonexistent file. e. A java.io.FileNotFoundException would occur if you attempt to create a FileOutputStream with a nonexistent file. Key:abcd (E) is false. All others are true. # 5. To append data to an existing file, use a. new FileOutputStream("out.dat") b. new FileOutputStream("out.dat", false) c. new FileOutputStream("out.dat", true) d. new FileOutputStream(true, "out.dat") Key:c See Figure 17.7. # 6.

What does the following code do?

FileInputStream fis = new FileInputStream("test.dat"); ..

to construct a FileOutputStream for file out.dat.


a. It creates a new file named test.dat if it does not exist and opens the file so you can write to it. b. It creates a new file named test.dat if it does not exist and opens the file so you can write to it and read from it. c. It creates a new file named test.dat regardless of whether it exists or not and opens the file so you can write to it. d. It creates a new file named test.dat regardless of whether it exists or not and opens the file so you can write to it and read from it. e. It creates a FileInputStream for test.dat if test.dat exists. Key:e See Figure 17.6. # Section 17.4.3 DataInputStream/DataOutputStream 7. Which type of exception occurs when creating a DataInputStream for a nonexistent file? a. FileNotExist b. FileNotExistException c. FileNotFound d. FileNotFoundException Key:d When creating an input stream object for input, a FileNotFoundException will occur if the file does not exist. # 8. Which of the following statements is correct to create a DataOutputStream to write to a file named out.dat? a. DataOutputStream outfile = new DataOutputStream(new File("out.dat")); b. DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat")); c. DataOutputStream outfile = new DataOutputStream(FileOutputStream("out.dat")); d. DataOutputStream outfile = new DataOutputStream("out.dat"); Key:b See Figure 17.10. # 9. After the following program is finished, how many bytes are written to the file t.dat? import java.io.*; public class Test { public static void main(String[] args) throws IOException { DataOutputStream output = new DataOutputStream( new FileOutputStream("t.dat")); output.writeShort(1234); output.writeShort(5678); output.close(); } } a. 2 bytes. b. 4 bytes. c. 8 bytes. d. 16 bytes. Key:b Each short number takes 2 bytes. So total is 4 bytes. # Section 17.4.4 BufferedInputStream/BufferedOutputStream 10. After the following program is finished, how many bytes are written to the file t.dat? import java.io.*; public class Test { public static void main(String[] args) throws IOException { DataOutputStream output = new DataOutputStream( ..


new BufferedOutputStream(FileOutputStream("t.dat"))); output.writeChar('A'); output.close(); } } a. 2 bytes. b. 4 bytes. c. 8 bytes. d. none of the above. Key:a Two bytes of Unicode for 'A' is written # Section 17.5 Case Study: Copying Files 11. After the following program is finished, how many bytes are written to the file t.dat? import java.io.*; public class Test { public static void main(String[] args) throws IOException { DataOutputStream output = new DataOutputStream( new FileOutputStream("t.dat")); output.writeChars("ABCD"); output.close(); } } a. 2 bytes. b. 4 bytes. c. 8 bytes. d. 12 bytes. e. 16 bytes. Key:c Two bytes of Unicode for each character is written to output. # 12. After the following program is finished, how many bytes are written to the file t.dat? import java.io.*; public class Test { public static void main(String[] args) throws IOException { DataOutputStream output = new DataOutputStream( new FileOutputStream("t.dat")); output.writeUTFString("ABCD"); output.close(); } } a. 2 bytes. b. 4 bytes. c. 6 bytes. d. 8 bytes. e. 10 bytes. Key:c "ABCD" are ASCII code, so each takes one byte in UTF. Total is 6 because the first two bytes stores the number of characters in the string. # exist.

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently


13. Which of the following statements are true? a. All files are stored in binary format. So, all files are essentially binary files. b. Text I/O is built upon binary I/O to provide a level of abstraction for character encoding and decoding. c. Encoding and decoding are automatically performed by text I/O. d. For binary input, you need to know exactly how data were written in order to read them in correct type and order. Key:abcd All the choices are true. # Section 17.6 Object I/O 14. Which of the following statements are true? a. ObjectInputStream/ObjectOutputStream enables you to perform I/O for objects in addition for primitive type values and strings. b. Since ObjectInputStream/ObjectOutputStream contains all the functions of DataInputStream/DataOutputStream, you can replace DataInputStream/DataOutputStream completely by ObjectInputStream/ObjectOutputStream. c. To write an object, the object must be serializable. d. The Serializable interface does not contain any methods. So it is a mark interface. e. If all the elements in an array is serializable, the array is serializable too. Key:abcde All choices are correct. # Section 17.6.1 The Serializable Interface 15. The Loan class given in the text does not implement java.io.Serializable. Analyze the following code. public class Foo implements java.io.Serializable { private int v1; private static double v2; private Loan v3 = new Loan(); } a. An instance of Foo can be serialized because Foo implements Serializable. b. An instance of Foo cannot be serialized because Foo contains a non-serializable instance variable v3. c. If you mark v3 as transient, an instance of Foo is serializable. Key:bc An object may not be serialized even though its class implements java.io.Serializable, because it may contain non-serializable instance variables. # 16. Which of the following statements is true? a. A static variable is not serialized. b. A transient variable is not serialized. c. An object must be an instance of Serializable for it to be serialized. d. The methods in an object are serialized. Key:c See the Note box. # Section 17.7 Random Access Files 20. With which I/O class can you append or update a file? a. RandomAccessFile() b. OutputStream() c. DataOutputStream() d. None of the above Key:a See the first paragraph. # 18. a. ..

Which of the following is the legal mode for creating a new RandomAccessFile stream? "w"


b. 'r' c. "rw" d. "rwx" Key:c See the third paragraph. # 19.

What happens if the file test.dat does not exist when you attempt to compile and run the following code?

import java.io.*; class Test { public static void main(String[] args) { try { RandomAccessFile raf = new RandomAccessFile("test.dat", "r"); int i = raf.readInt(); } catch(IOException ex) { System.out.println("IO exception"); } } } a. The program does not compile because raf is not created correctly. b. The program does not compile because readInt() is not implemented in RandomAccessFile. c. The program compiles, but throws IOException because the file test.dat doesn't exist. The program displays IO exception. d. The program compiles and runs fine, but nothing is displayed on the console. Key:c The problem is in line: new RandomAccessFile("test.dat", "r"); Because the file does not exist, you cannot open it for reading. # 17. To create a file, you can use . a. FileOutputStream b. FileWriter c. RandomAccessFile d. All of the above Key:d All these classes can be used to create files.

..


..

Chapter 18 Recursion Section 18.2 Example: Factorials 1. Which of the following statements are true? a. Every recursive method must have a base case or a stopping condition. b. Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case. c. Infinite recursion can occur if recursion does not reduce the problem in a manner that allows it to eventually converge into the base case. d. Every recursive method must have a return value. e. A recursive method is invoked differently from a non-recursive method. key:abc See the text before Listing 18.1. # 2. Fill in the code to complete the following method for computing factorial. /** Return the factorial for a specified index */ public static long factorial(int n) { if (n == 0) // Base case return 1; else return ; // Recursive call } a. n * (n - 1) b. n c. n * factorial(n - 1) d. factorial(n - 1) * n key:cd See Listing 18.1. # 3. What are the base cases in the following recursive method? public static void xMethod(int n) { if (n > 0) { System.out.print(n % 10); xMethod(n / 10); } } a. n > 0 b. n <= 0 c. no base cases d. n < 0 key:b See Listing 18.1. # 4. Analyze the following recursive method. public static long factorial(int n) { return n * factorial(n - 1); } a. Invoking factorial(0) returns 0.


..

b. Invoking factorial(1) returns 1. c. Invoking factorial(2) returns 2. d. Invoking factorial(3) returns 6. e. The method runs infinitely and causes a StackOverflowError. key:e There is no base case in this recursive function. # 5. How many times is the factorial method in Listing 18.1 invoked for factorial(5)? a. 3 b. 4 c. 5 d. 6 key:d See Listing 18.1. # Section 18.3 Example: Fibonacci Numbers 6. Which of the following statements are true? a. The Fibonacci series begins with 0 and 1, and each subsequent number is the sum of the preceding two numbers in the series. b. The Fibonacci series begins with 1 and 1, and each subsequent number is the sum of the preceding two numbers in the series. c. The Fibonacci series begins with 1 and 2, and each subsequent number is the sum of the preceding two numbers in the series. d. The Fibonacci series begins with 2 and 3, and each subsequent number is the sum of the preceding two numbers in the series. key:a See the first paragraph in this section. # 7. How many times is the fib method in Listing 18.2 invoked for fib(5)? a. 14 b. 15 c. 25 d. 31 e. 32 key:b number of time fib is invoked in fib(5) = 1 + number of time fib is invoked in fib(3) + number of time fib is invoked in fib(4) = 1 + 5 + 9 = 15 # 8. Fill in the code to complete the following method for computing a Fibonacci number. public static long fib(long index) { if (index == 0) // Base case return 0; else if (index == 1) // Base case return 1; else // Reduction and recursive calls return ; } a. fib(index - 1) b. fib(index - 2) c. fib(index - 1) + fib(index - 2) d. fib(index - 2) + fib(index - 1) key:cd See Listing 18.2.


..

# Section 18.4 Problem Solving Using Recursion 10. What is the return value for xMethod(4) after calling the following method? static int xMethod(int n) { if (n == 1) return 1; else return n + xMethod(n - 1); } a. 12 b. 11 c. 10 d. 9 Key:c 4 + 3 + 2 + 1 = 10 # 11. Fill in the code to complete the following method for checking whether a string is a palindrome. public static boolean isPalindrome(String s) { if (s.length() <= 1) // Base case return true; else if return false; else return isPalindrome(s.substring(1, s.length() - 1)); } a. (s.charAt(0) != s.charAt(s.length() - 1)) // Base case b. (s.charAt(0) != s.charAt(s.length())) // Base case c. (s.charAt(1) != s.charAt(s.length() - 1)) // Base case d. (s.charAt(1) != s.charAt(s.length())) // Base case key:a See Listing 18.3. # 12.

Analyze the following code:

public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4, 5}; xMethod(x, 5); } public static void xMethod(int[] x, int length) { System.out.print(" " + x[length - 1]); xMethod(x, length - 1); } } a. The program displays 1 2 3 4 6. b. The program displays 1 2 3 4 5 and then raises an ArrayIndexOutOfBoundsException. c. The program displays 5 4 3 2 1. d. The program displays 5 4 3 2 1 and then raises an ArrayIndexOutOfBoundsException. Key:d xMethod(x, 5) is invoked, then xMethod(x, 4), xMethod(x, 3), xMethod(x, 2), xMethod(x, 1), xMethod(x, 0).


..

When invoking xMethod(x, 0), a runtime exception is raised because System.out.print(" "+x[0-1]) causes array out of bound. # 9. In the following method, what is the base case? static int xMethod(int n) { if (n == 1) return 1; else return n + xMethod(n - 1); } a. n is 1. b. n is greater than 1. c. n is less than 1. d. no base case. key:a Base case is when the recursion stops. # Section 18.5 Recursive Helper Methods 13. Fill in the code to complete the following method for checking whether a string is a palindrome. public static boolean isPalindrome(String s) { return isPalindrome(s, 0, s.length() - 1); } public static boolean isPalindrome(String s, int low, int high) { if (high <= low) // Base case return true; else if (s.charAt(low) != s.charAt(high)) // Base case return false; else return ; } a. isPalindrome(s) b. isPalindrome(s, low, high) c. isPalindrome(s, low + 1, high) d. isPalindrome(s, low, high - 1) e. isPalindrome(s, low + 1, high - 1) key:e See Listing 18.4. # 14. Fill in the code to complete the following method for sorting a list. public static void sort(double[] list) { ; } public static void sort(double[] list, int high) { if (high > 1) { // Find the largest number and its index int indexOfMax = 0; double max = list[0]; for (int i = 1; i <= high; i++) {


if (list[i] > max) { max = list[i]; indexOfMax = i; } } // Swap the largest with the last number in the list list[indexOfMax] = list[high]; list[high] = max; // Sort the remaining list sort(list, high - 1); } } a. sort(list) b. sort(list, list.length) c. sort(list, list.length - 1) d. sort(list, list.length - 2) key:c See Listing 18.5. # 15. Fill in the code to complete the following method for binary search. public static int recursiveBinarySearch(int[] list, int key) { int low = 0; int high = list.length - 1; return ; } public static int recursiveBinarySearch(int[] list, int key, int low, int high) { if (low > high) // The list has been exhausted without a match return -low - 1; // Return -insertion point - 1 int mid = (low + high) / 2; if (key < list[mid]) return recursiveBinarySearch(list, key, low, mid - 1); else if (key == list[mid]) return mid; else return recursiveBinarySearch(list, key, mid + 1, high); } a. recursiveBinarySearch(list, key) b. recursiveBinarySearch(list, key, low + 1, high - 1) c. recursiveBinarySearch(list, key, low - 1, high + 1) d. recursiveBinarySearch(list, key, low, high) key:d See Listing 18.6. # Section 18.7 Tower of Hanoi 16. How many times is the recursive moveDisks method invoked for 3 disks? a. 3 b. 7 c. 10 © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


d. 14 key:b It is 2^3 - 1. In general, it is 2^n - 1. # 17. How many times is the recursive moveDisks method invoked for 4 disks? a. 5 b. 10 c. 15 d. 20 key:c It is 2^4 - 1. In general, it is 2^n - 1. # 18.

Analyze the following two programs:

A: public class Test { public static void main(String[] args) { xMethod(5); } public static void xMethod(int length) { if (length > 1) { System.out.print((length - 1) + " "); xMethod(length - 1); } } } B: public class Test { public static void main(String[] args) { xMethod(5); } public static void xMethod(int length) { while (length > 1) { System.out.print((length - 1) + " "); xMethod(length - 1); } } } a. The two programs produce the same output 5 4 3 2 1. b. The two programs produce the same output 1 2 3 4 5. c. The two programs produce the same output 4 3 2 1. d. The two programs produce the same output 1 2 3 4. e. Program A produces the output 4 3 2 1 and Program B prints 4 3 2 1 1 1 .... 1 infinitely. Key:e In Program B, xmethod(5) invokes xmethod(4), xmethod(4) invokes xmethod(3), xmethod(3) invokes xmethod(2), xmethod(2) invokes xmethod(1), xmethod(1) returns control to xmethod(2), xmethod(2) invokes xmethod(1) because of the while loop. This continues infinitely. # Section 18.8 Case Study: Fractals 20. In Listing 18.9, to draw three smaller triangles recursively, the program invokes: © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


..

a. displayTriangles(order - 1, p1, p12, p31); b. displayTriangles(order - 1, p12, p2, p23); c. displayTriangles(order - 1, p31, p23, p3); d. displayTriangles(order - 1, p12, p23, p31); key:abc See Listing 18.9. # Section 18.9 Recursion versus Iteration 20. Which of the following statements are true? a. Recursive methods run faster than non-recursive methods. b. Recursive methods usually take more memory space than non-recursive methods. c. A recursive method can always be replaced by a non-recursive method. d. In some cases, however, using recursion enables you to give a natural, straightforward, simple solution to a program that would otherwise be difficult to solve. key:bcd See the discussion in this section. # Section 18.10 Tail Recursion 21. Analyze the following functions; public class Test1 { public static void main(String[] args) { System.out.println(f1(3)); System.out.println(f2(3, 0)); } public static int f1(int n) { if (n == 0) return 0; else { return n + f1(n - 1); } } public static int f2(int n, int result) { if (n == 0) return result; else return f2(n - 1, n + result); } } a. f1 is tail recursion, but f2 is not b. f2 is tail recursion, but f1 is not c. f1 and f2 are both tail recursive d. Neither f1 nor f2 is tail recursive key:b See Listing 18.10. # 22. Show the output of the following code: public class Test1 { public static void main(String[] args) { System.out.println(f2(2, 0));


..

} public static int f2(int n, int result) { if (n == 0) return 0; else return f2(n - 1, n + result); } } a. 0 b. 1 c. 2 d. 3 key:a See Listing 18.10.


Chapter 19 Generics Section 19.2 Motivations and Benefits 1. Which of the following statements is correct? a. Generics can help detect type errors at compile time, thus make programs more robust. b. Generics can make programs easy to read. c. Generics can avoid cumbersome castings. d. Generics can make programs run faster. Key:abc See the third paragraph. # 2. Fill in the code in Comparable a. <String> b. <?> c. <Date> d. <E> Key:c See Figure 19.2.

c = new Date();

# 6. Suppose ArrayList<Double>list = new ArrayList<>(). Which of the following statements are correct? a. list.add(5.5); // 5.5 is automatically converted to new Double(5.5) b. list.add(3.0); // 3.0 is automatically converted to new Double(3.0) c. Double doubleObject = list.get(0); // No casting is needed d. double d = list.get(1); // Automatically converted to double Key:abcd See the end of this section. # 4. Suppose List list = new ArrayList(). Which of the following operations are correct? a. list.add("Red"); b. list.add(new Integer(100)); c. list.add(new java.util.Date()); d. list.add(new ArrayList()); Key:abcd In this case, List list is a raw type. You can add any objects into the list. # 5. Suppose List<String> list = new ArrayList<String>. Which of the following operations are correct? a. list.add("Red"); b. list.add(new Integer(100)); c. list.add(new java.util.Date()); d. list.add(new ArrayList()); Key:a In this case, List<String> list is a List of String. You can only add strings into list. # Section 19.3 Declaring Generic Classes and Interfaces 7. To declare a class named A with a generic type, use a. public class A<E> { ... } b. public class A<E, F> { ... } c. public class A(E) { ... } d. public class A(E, F) { ... } Key:a See Listing 19.1. # 8. To declare a class named A with two generic types, use ..


a. public class A<E> { ... } b. public class A<E, F> { ... } c. public class A(E) { ... } d. public class A(E, F) { ... } Key:b See the first Note box in this section. # 9. To declare an interface named A with a generic type, use a. public interface A<E> { ... } b. public interface A<E, F> { ... } c. public interface A(E) { ... } d. public interface A(E, F) { ... } Key:a See Listing 19.1. # 10. To declare an interface named A with two generic types, use a. public interface A<E> { ... } b. public interface A<E, F> { ... } c. public interface A(E) { ... } d. public interface A(E, F) { ... } Key:b Multiple generic types can be used to define generic classes and interfaces, and methods. # 11. To create a list to store integers, use a. ArrayList<Object> list = new ArrayList<>(); b. ArrayList<Integer> list = new ArrayList<>(); c. ArrayList<int> list = new ArrayList<int>(); d. ArrayList<Number> list = new ArrayList<>(); Key:b Generic types must be objects. So, use Integer rather than int. # Section 19.4 Generic Methods 12. The method header is left blank in the following code. Fill in the header. public class GenericMethodDemo { public static void main(String[] args ) { Integer[] integers = {1, 2, 3, 4, 5}; String[] strings = {"London", "Paris", "New York", "Austin"}; print(integers); print(strings); } { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); } } a. public static void print(Integer[] list) b. public static void print(String[] list) c. public static void print(int[] list) d. public static void print(Object[] list) e. public static <E> void print(E[] list) Key:de See Listing 19.2. ..


# 13. To create a generic type bounded by Number, use a. <E extends Number> b. <E extends Object> c. <E> d. <E extends Integer> Key:a See Listing 19.3. # Section 19.5 Case Study: Sorting an Array of Objects 3. Which of the following statements is correct? a. Comparable<String> c = new String("abc"); b. Comparable<String> c = "abc"; c. Comparable<Integer> c = 23; d. Comparable<Double> c = 3.4; Key:abcd All correct. # 28. Fill in the most appropriate code in the blanks in the MyInt class? public class MyInt implements int id;

{

public MyInt(int id) { this.id = id; } public String toString() { return String.valueOf(id); } public int compareTo( if (id > arg0.id) return 1; else if (id < arg0.id) return -1; else return 0; }

arg0) {

} a. Comparable / Object b. Comparable<MyInt> / MyInt c. Comparable<MyInt> / Object d. Comparable / MyInt Key:b To make MyInt comparable, implements Comparable<MyInt> and override the compare(MyInt) method. # Section 19.6 Raw Type and Backward Compatibility 14. Which of the following declarations use raw type? a. ArrayList<Object> list = new ArrayList<>(); b. ArrayList<String> list = new ArrayList<>(); c. ArrayList<Integer> list = new ArrayList<>(); ..


d. ArrayList list = new ArrayList(); Key:d See Listing 19.5. # 15. If you use the javac command to compile a program that contains raw type, what would the compiler do? a. report syntax error b. report warning and generate a class file c. report warning without generating a class file d. no error and generate a class file e. report warning and generate a class file if no other errors in the program. Key:e For javac, a class file is generated even if the program has compile warnings. # 16. If you use the javac –Xlint:unchecked command to compile a program that contains raw type, what would the compiler do? a. report compile error b. report warning and generate a class file c. report warning without generating a class file d. no error and generate a class file Key:b See Figure 19.5. # Section 19.7 Wildcards 17. Is ArrayList<Integer> a subclass of ArrayList<Object>? a. Yes b. No Key:b See Figure 19.6. # 23. Which of the following can be used to replace YYYYYYYY in the following code? public class WildCardDemo3 { public static void main(String[] args) { GenericStack<String> stack1 = new GenericStack<>(); GenericStack<Object> stack2 = new GenericStack<>(); stack2.push("Java"); stack2.push(2); stack1.push("Sun"); add(stack1, stack2); WildCardDemo2.print(stack2); } public static <T> void add(GenericStack<T> stack1, GenericStack<YYYYYYYY> stack2) { while (!stack1.isEmpty()) stack2.push(stack1.pop()); } } a. ? super Object b. ? super T c. ? extends T d. ? extends Object Key:b See Listing 19.9. ..


# 24. Which of the following can be used to replace YYYYYYYY in the following code? public class WildCardDemo3 { public static void main(String[] args) { GenericStack<String> stack1 = new GenericStack<>(); GenericStack<Object> stack2 = new GenericStack<>(); stack2.push("Java"); stack2.push(2); stack1.push("Sun"); add(stack1, stack2); WildCardDemo2.print(stack2); } public static <T> void YYYYYYYY { while (!stack1.isEmpty()) stack2.push(stack1.pop()); } } a. add(GenericStack<T> stack1, GenericStack<T> stack2) b. add(GenericStack<? extends T> stack1, GenericStack<T> stack2) c. add(GenericStack<T> stack1, GenericStack<? super T> stack2) d. add(GenericStack<T> stack1, GenericStack<Object> stack2) Key:bcd See Listing 19.9. # 18. Is ArrayList<Integer> a subclass of ArrayList<?>? a. Yes b. No Key:a See Figure 19.6. # 19. Is ArrayList<Integer> a subclass of ArrayList<? extends Number>? a. Yes b. No Key:a See Figure 19.6. # 20. Is ArrayList<Number> a subclass of ArrayList<? extends Number>? a. Yes b. No Key:a Number is a subtype of ? extends Number. # 21. Is ArrayList<?> same as ArrayList<? extends Object>? a. Yes b. No Key:a ? is same as ? extends Object # 22. Does <? super Number> represent a superclass of Number? a. Yes ..


b. No Key:a The super keyword used in the generic type means super type of. # Section 19.8 Erasure and Restrictions on Generics 25. ArrayList<String> and ArrayList<Integer> are two types. Does the JVM load two classes ArrayList<String> and ArrayList<Integer>? a. Yes b. No Key:b The JVM loads just one ArrayList. # 26. Which of the following statements are true? a. Generic type information is present at compile time. b. Generic type information is not present at runtime. c. You cannot create an instance using a generic class type parameter. d. You cannot create an array using a generic class type parameter. e. You cannot create an array using a generic class. Key:abcde See the discussion in this section. # 27. If E is a generic type for a class, can E be referenced from a static method? a. Yes b. No Key:b It is illegal to refer to a generic type parameter for a class in a static method or initializer, because generic type for a class belongs to a specific instantiation of the class.

..


Chapter 20 Lists, Stacks, Queues, and Priority Queues Section 20.2 Collections 1. All the concrete classes in the Java Collections Framework implement a. the Cloneable interface b. the Serializable interfaces c. the Comparable interface d. the Comparator interface Key:b See the last Note box in this section.

.

# 3. Which of the following methods are in the Collection interface? a. clear() b. isEmpty() c. size() d. getSize() Key:abc See Figure 20.2. # 4. Which of the following methods are in the Collection interface? a. add(o: E) b. addAll(c: Collection<? extends E>) c. contains(o: Object): boolean d. containsAll(c: Collection<?>): boolean Key:abcd See Figure 20.2. # 5. Which of the following methods are in the Collection interface? a. remove(o: Object): boolean b. removeAll(c: Collection<?>): boolean c. delete(o: E): boolean d. deleteAll(c: Collection<?>): boolean Key:ab See Figure 20.2. # 2. Which of the following statements are true? a. The Collection interface is the root interface for manipulating a collection of objects. b. The Collection interface provides the basic operations for adding and removing elements in a collection. c. The AbstractCollection class is a convenience class that provides partial implementation for the Collection interface. d. Some of the methods in the Collection interface cannot be implemented in the concrete subclass. In this case, the method would throw java.lang.UnsupportedOperationException, a subclass of RuntimeException. e. All interfaces and classes in the Collections framework are declared using generic type since JDK 1.5. Key:abcde All these statements are correct. # Section 20.3 Iterators 6. For an instance of Collection, you can obtain its iterator using a. c.getIterator() b. c.iterator() c. c.iterators() d. c.iterable() Key:b See Listing 20.2. ..

.


# 8. The iterator() method returns an instance of the a. Iterator b. Collection c. Iterable d. ArrayList Key:a See Listing 20.2.

interface.

# 9. You can use a for-each loop to traverse all elements in a container object that implements a. Iterator b. Collection c. Iterable d. ArrayList Key:c See the Tip box. # 7. The iterator() method is defined in the a. Iterator b. Collection c. Iterable d. ArrayList Key:c See Figure 20.2 in the preceding section.

.

interface.

# Section 20.5 Lists 15. Suppose list is a LinkedList that contains 1 million int values. Analyze the following code: A: for (int i = 0; i < list.size(); i++) sum += list.get(i); B: for (int i: list) sum += i; a. Code fragment A runs faster than code fragment B. b. Code fragment B runs faster than code fragment A. c. Code fragment A runs as fast as code fragment B. Key:b Because code fragment B uses an iterator to traverse the elements in a linked list. # 16. Which method do you use to test if an element is in a set or list named x? a. (element instanceof List) || (element instanceof Set) b. x.in(element) c. x.contain(element) d. x.contains(element) e. x.include(element) Key:d The contains method defined in the Collection interface checks if an element is in the collection (set or list) # 53. What is list after the following code is executed? ArrayList<Integer> list = new ArrayList<>(); ..


list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); list.remove(2); System.out.println(list); a. [1, 2, 3, 4, 5] b. [2, 3, 4, 5] c. [1, 3, 4, 5] d. [1, 2, 4, 5] e. [1, 2, 3, 4] Key:d List has two overloaded remove method remove(Object) and remove(int index). The latter is invoked for list.remove(2) to remove the element in the list at index 2. # 11. Which of the following statements are true? a. An ArrayList can grow automatically. b. An ArrayList can shrink automatically. c. You can reduce the capacity of an ArrayList by invoking the trimToSize() method on the list. d. You can reduce the capacity of a LinkedList by invoking the trimToSize() method on the list. Key:ac A LinkedList does not have excess capacity. # 21. What is the printout of the following code? List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); for (int i = 0; i < list.size(); i++) System.out.print(list.remove(i)); a. ABCD b. AB c. AC d. AD e. ABC Key:c Before the loop, the list is [A, B, C, D]. After invoking list.remove(0), the list becomes [B, C, D] and size becomes 3. Invoking remove(1) now deletes C from the list. The list becomes [B, D]. Now the list size is 2 and i is 2. So the loop ends. # 18. Suppose ArrayList x contains three strings [Beijing, Singapore, Tokyo]. Which of the following methods will cause runtime errors? a. x.get(2) b. x.set(3, "New York"); c. x.get(3) d. x.remove(3) e. x.size() Key:bcd There is no element at index 3. # 19. Which method do you use to find the number of elements in a set or list named x? a. x.length() ..


b. x.count() c. x.counts() d. x.size() e. x.sizes() Key:d The size method defined in the Collection interface returns the number of elements in the collection (set or list) # 20. Which method do you use to remove an element from a set or list named x? a. x.delete(element) b. x.remove(element) c. x.deletes(element) d. x.removes(element) e. None of the above Key:b The remove method defined in the Collection interface removes the element from the collection (set or list) # 10. Which of the following statements are true? a. java.util.List inherits all the methods from java.util.Collection. Additionally, it contains new methods for manipulating a list. b. The AbstractList class provides a partial implementation for the List interface. c. ArrayList is a concrete implementation of List using an array. d. LinkedList is a concrete implementation of List using a linked list. LinkedList contains all the methods in List and additional new methods for manipulating a linked list. e. ListIterator is a subinterface of Iterator and it provides the methods to support bi-directional traversal of a list. Key:abcde All the statements are correct. # 22. Suppose list list1 is [1, 2, 5] and list list2 is [2, 3, 6]. After list1.addAll(list2), list1 is a. [1, 2, 2, 3, 5, 6] b. [1, 2, 3, 5, 6] c. [1, 5] d. [2] Key:a Invoking list1.addAll(list2) adds all the elements in list2 into list1. # 23. Suppose list list1 is [1, 2, 5] and list list2 is [2, 3, 6]. After list1.removeAll(list2), list2 is a. [1, 2, 2, 3, 5, 6] b. [1, 2, 3, 5, 6] c. [1, 5] d. [2] e. [2, 3, 6] Key:c Invoking list1.removeAll(list2) removes all the elements in list2 from list1.

.

.

# 24. Which of the following statements are correct? a. When you create an array using new int[10], an array object is created with ten integers of value 0. b. When you create an array using new int[10], an array object is created with no values in the array. c. When you create an ArrayList using new ArrayList(), an ArrayList object is created with no elements in the ArrayList object. d. When you create an array using int[] x = new int[10], x.length is 10. e. When you create an array using ArrayList x = new ArrayList(10), x.size() is 10. Key:acd The .length attribut returns the size of an array and .size() method returns the size of a list. # ..


25. Suppose a list contains {"red", "green", "red", "green"}. What is the list after the following code? list.remove("red"); a. {"red", "green", "red", "green"} b. {"green", "red", "green"} c. {"green", "green"} d. {"red", "green", "green"} Key:b Invoking list.remove("red") removes "red" from list. # 26. Suppose a list contains {"red", "green", "red", "green"}. What is the list after the following code? String element = "red"; for (int i = 0; i < list.size(); i++) if (list.get(i).equals(element)) { list.remove(element); i--; } a. {"red", "red", "green"} b. {"red", "green"} c. {"green", "green"} d. {"green"} e. {} Key:c Invoking list.remove(element) removes element from list. # 27. Suppose a list contains {"red", "green", "red", "green"}. What is the list after the following code? String element = "red"; for (int i = list.size() - 1; i >= 0; i--) if (list.get(i).equals(element)) list.remove(element); a. {"red", "red", "green"} b. {"red", "green"} c. {"green", "green"} d. {"green"} e. {} Key:c Invoking list.remove(element) removes element from list. # 28. What is the output of the following code? ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.remove(2); System.out.println(list); a. [1, 2, 3] b. [1, 2] ..


c. [1] d. [1, 3] e. [2, 3] Key:b Invoking list.remove(2) removes the element at index from list. # 29. To remove all the elements in the list in the following code, replace the underlined blank space with

.

import java.util.*; public class Test { public static void main(String[] args) { <Integer> list = new ArrayList<>(); list.add(0); list.add(1); list.add(2); for (int i = 0; i < 3; i++) { list.remove(i); } System.out.println(list); } } a. Collection b. List c. ArrayList d. AbstractList Key:a If list is declared as Collection<Integer>, list.remove(i) is the same as list.remove(new Integer(i)). If list is declared as List<Integer>, ArrayList<Integer>, or AbstractList<Integer>, list.remove(i) is to remove the element at the index i. The list has three elements and the last index is 2. After removing the first element, the last index becomes 1. After removing another element, the last index becomes 0. You will receive an IndexOutOfBoundsException. # 12. Which of the following methods are in java.util.List? a. add(int index, E element) b. get(int index) c. set(int index, E element) d. remove(int index) e. subList(int fromIndex, int toIndex) Key:abcde All these methods are in the List interface. # 13. Which of the following are true? a. You can insert an element anywhere in an arraylist. b. You can insert an element anywhere in a linked list. c. You can use a linked list to improve efficiency for adding and removing elements at the beginning of a list. d. You should use an array list if your application does not require adding and removing elements at the beginning of a list. Key:abcd All true. # 14. Suppose list1 is an ArrayList and list2 is a LinkedList. Both contains 1 million double values. Analyze the ..


following code: A: for (int i = 0; i < list1.size(); i++) sum += list1.get(i); B: for (int i = 0; i < list2.size(); i++) sum += list2.get(i); a. Code fragment A runs faster than code fragment B. b. Code fragment B runs faster than code fragment A. c. Code fragment A runs as fast as code fragment B. Key:a See the discussion before the last Tip box. # 17. When you create an ArrayList using ArrayList<String> x = new ArrayList<>(2), a. two elements are created in the array list. b. no elements are currently in the array list. c. the array list size is currently 2. d. the array list capacity is currently 2. Key:bd new ArrayList<>(2) creates an ArrayList with initial capacity 2. # 31. What is the output of the following code? import java.util.*; public class Test { public static void main(String[] args) { List<String> list1 = new ArrayList<>(); list1.add("Atlanta"); list1.add("Macon"); list1.add("Savanna"); List<String> list2 = new ArrayList<>(); list2.add("Atlanta"); list2.add("Macon"); list2.add("Savanna"); List<String> list3 = new ArrayList<>(); list3.add("Macon"); list3.add("Savanna"); list3.add("Atlanta"); System.out.println(list1.equals(list2) + " " + list1.equals(list3)); } } a. true true b. true false c. false false d. false true Key:b list1, list2, and list3 are three ArrayLists. list1 and list2 contains the same elements in the same order. list1 and list3 contains the same elements, but in different orders.

..


# Section 20.6 The Comparator Interface 30. Which of the following statements are true? a. The Comparable interface contains the compareTo method with the signature "public int compareTo(E)". b. The Comparator interface contains the compare method with the signature "public int compare(E, E)". c. A Comparable object can compare this object with the other object. d. A Comparator object contains the compare method that compares two objects. Key:abcd See the first paragraph in this section. # 32. What is the output of the following code? import java.util.*; public class Test { public static void main(String[] args) { ArrayList<Student> list = new ArrayList<>(); list.add(new Student("Peter", 65)); list.add(new Student("Jill", 50)); list.add(new Student("Sarah", 34)); Collections.sort(list); System.out.print(list + " "); Collections.sort(list, new StudentComparator1()); System.out.println(list); } static class StudentComparator1 implements Comparator<Student> { public int compare(Student s1, Student s2) { return s1.name.compareTo(s2.name); } } static class Student implements Comparable<Student> { String name; int age; Student(String name, int age) { this.name = name; this.age = age; } public int compareTo(Student s) { return this.age - s.age; } public String toString() { return "[" + name + ", " + age + "]"; } } } a. [[Sarah, 34], [Jill, 50], [Peter, 65]] [[Sarah, 34], [Jill, 50], [Peter, 65]] b. [[Jill, 50], [Peter, 65], [Sarah, 34]] [[Jill, 50], [Peter, 65], [Sarah, 34]] c. [[Sarah, 34], [Jill, 50], [Peter, 65]] [[Jill, 50], [Peter, 65], [Sarah, 34]] d. [[Jill, 50], [Peter, 65], [Sarah, 34]] [[Sarah, 34], [Jill, 50], [Peter, 65]] ..


Key:c The students are sorted by age. # 30. Fill in the code to create a Comparator for two strings in increasing order of their length. public class SortStringByLength { public static void main(String[] args) { String[] cities = {"Atlanta", "Savannah", "New York", "Dallas"}; java.util.Arrays.sort(cities, ); for (String s : cities) { System.out.print(s + " "); } } } a. (s1, s2) -> {return s1.length() - s2.length();} b. (s1, s2) -> s1.length() - s2.length() c. java.util.Comparator.comparing(String::length) d. java.util.Comparator.comparing(s -> s.length()) Key:abcd See Listing 20.7 and the discussion on method reference. # Section 20.8 Static Methods for Lists and Collections 33. Which of the following is correct to sort the elements in a list lst? a. lst.sort() b. Collections.sort(lst) c. Arrays.sort(lst) d. new LinkedList<String>(new String[]{"red", "green", "blue"}) Key:b See Figure 20.7. # 34. You can use the methods in the Collections class to a. find the maximum object in a collection based on the compareTo method. b. find the maximum object in a collection using a Comparator object. c. sort a collection. d. shuffle a collection. e. do a binary search on a collection. Key:ab The Collections class has a method to sort a list, shuffle a list, and perform binary search on a list, but not on collection. Note that collection includes set. # 35. Which of the following statements are true? a. Collections.shuffle(list) returns a new list while the original list is not changed. b. Collections.reverse(list) returns a new list while the original list is not changed. c. Collections.sort(list) returns a new list while the original list is not changed. d. Collections.nCopies(int, Object) returns a new list that consists of n copies of the object. Key:d See Figure 20.7. # 36. Which of the following statements are true? a. Collections.shuffle(list) randomly reorders the elements in the list. b. Collections.shuffle(list, Random) randomly reorders the elements in the list with a specified Random object. c. If list1 and list2 are identical, the two lists may be different after invoking Collections.shuffle(list1) and Collections.shuffle(list2). d. If list1 and list2 are identical, the two lists are still identical after invoking Collections.shuffle(list1, new ..


Random(3)) and Collections.shuffle(list2, new Random(3)) with the same Random object. Key:abcd See Figure 20.7. # 37. Which of the following is correct to create a list from an array? a. new List<String>({"red", "green", "blue"}) b. new List<String>(new String[]{"red", "green", "blue"}) c. Arrays.asList<String>(new String[]{"red", "green", "blue"}) d. new ArrayList<String>(new String[]{"red", "green", "blue"}) e. new LinkedList(new String[]{"red", "green", "blue"}) Key:c The correct way to create a List from an array is to use the Arrays.asList method. # 38. To create a set that consists of string elements "red", "green", and "blue", use a. new HashSet<String>({"red", "green", "blue"}) b. new HashSet<String>(new String[]{"red", "green", "blue"}) c. new HashSet<String>(Arrays.asList(new String[]{"red", "green", "blue"})) d. new LinkedHashSet<String>(Arrays.asList(new String[]{"red", "green", "blue"})) e. new Set<String>(Arrays.asList(new String[]{"red", "green", "blue"})) Key:cd Both C and D are correct. In C, it creates a HashSet. In D, it creates a LinkedHashSet. # 39. To find a maximum object in an array of strings (e.g., String[] names = {"red", "green", "blue"}), use a. Arrays.max(names) b. Arrays.sort(names) c. Collections.max(names) d. Collections.max(Arrays.asList(names)) e. None of the above Key: d The max method is in the Collections class. # 40. You can use the methods in the Arrays class to a. find the maximum object in an array based on the compareTo method. b. find the maximum object in an array using a Comparator object. c. sort an array. d. shuffle an array. e. do a binary search on an array. Key:ce The Arrays class has the methods sort and binarySearch. # Section 20.9 The Vector and Stack Classes 42. java.util.Vector is a subtype of a. java.util.ArrayList b. java.util.LinkedList c. java.util.AbstractList d. java.util.Vector e. java.util.List Key:ce See Figure Figure 20.10. # 43. The methods for modifying element in the a. ArrayList b. LinkedList c. Stack ..

.

class are synchronized.


d. Vector Key:cd See the second paragraph. # 44. java.util.Stack is a subclass of . a. java.util.ArrayList b. java.util.LinkedList c. java.util.AbstractList d. java.util.Vector e. java.util.List Key:cde E is correct since Vector is a subclass of List. # 41. Which data type should you use if you want to store duplicate elements and be able to insert or delete elements at the beginning of the list? a. ArrayList b. LinkedList c. Vector d. Set e. Stack Key:b It takes O(1) time to insert and delete at the beginning of a LinkedList. # Section 20.10 Queues and Priority Queues 45. The method in the Queue interface retrieves and removes the head of this queue, or null if this queue is empty. a. poll() b. remove() c. peek() d. element() Key:a See Figure 20.12. # 51. Analyze the following code: import java.util.*; public class Test { public static void main(String[] args) { PriorityQueue<Integer> queue = new PriorityQueue<Integer>( Arrays.asList(60, 10, 50, 30, 40, 20)); for (int i: queue) System.out.print(i + " "); } } a. The program displays 60 10 50 30 40 20 b. The program displays 10 20 30 40 50 60 c. The program displays 60 50 40 30 20 10 d. There is no guarantee that the program displays 10 20 30 40 50 60 Key:d See Listing 20.11. # ..


52. Analyze the following code: import java.util.*; public class Test { public static void main(String[] args) { PriorityQueue<Integer> queue = new PriorityQueue<Integer>( Arrays.asList(60, 10, 50, 30, 40, 20)); while (!queue.isEmpty()) System.out.print(queue.poll() + " "); } } a. The program displays 60 10 50 30 40 20 b. The program displays 10 20 30 40 50 60 c. The program displays 60 50 40 30 20 10 d. There is no guarantee that the program displays 10 20 30 40 50 60 Key:b See Listing 20.11. # 46. The method in the Queue interface retrieves and removes the head of this queue and throws an exception if this queue is empty. a. poll() b. remove() c. peek() d. element() Key:b See Figure 20.12. # 47. The method in the Queue interface retrieves, but does not remove, the head of this queue, returning null if this queue is empty. a. poll() b. remove() c. peek() d. element() Key:c See Figure 20.12. # 48. The method in the Queue interface retrieves, but does not remove, the head of this queue, throwing an exception if this queue is empty. a. poll() b. remove() c. peek() d. element() Key:d See Figure 20.12. # 49. Which of the following statements are true? a. java.util.LinkedList implements the java.util.Queue interface. b. java.util.ArrayList implements the java.util.Queue interface. c. java.util.HashSet implements the java.util.Queue interface. d. java.util.LinkedHashSet implements the java.util.Queue interface. e. java.util.PriorityQueue implements the java.util.Queue interface. ..


Key:ae LinkedList and PriorityQueue implements the Queue interface. # 50. Which of the following statements are true? a. A PriorityQueue orders its elements according to their natural ordering using the Comparable interface if no Comparator is specified. b. A PriorityQueue orders its elements according to the Comparator if a Comparator is specified in the constructor. c. The priority of a PriorityQueue cannot be changed once a PriorityQueue is created. d. The priority of a PriorityQueue cannot be reversed once a PriorityQueue is created. Key:ab A default priority queue orders the elements using the Comparable interface. You can also create a PriorityQueue using any Comparator.

..


Chapter 21 Sets and Maps Section 21.2 Sets 1. Which of the data types below does not allow duplicates? a. Set b. List c. Vector d. Stack e. LinkedList Key:a See the first paragraph. # Section 21.2.1 HashSet 4. If two objects o1 and o2 are equal, what are the values for o1.equals(o2) and o1.hashCode() == o2.hashCode()? a. true true b. true false c. false true d. false false Key:a See the fourth paragraph. # 5. What is the output for the following code? import java.util.*; public class Test { public static void main(String[] args) { Set<A> set = new HashSet<A>(); set.add(new A()); set.add(new A()); set.add(new A()); set.add(new A()); System.out.println(set); } } class A { int r = 1; public String toString() { return r + ""; } public boolean equals(Object o) { return this.r == ((A)o).r; } public int hashCode() { return r; } } a. b.

[1] [1, 1] ..


c. [1, 1, 1] d. [1, 1, 1, 1] Key:a See the fourth paragraph. # 7. What is the output for the following code? import java.util.*; public class Test { public static void main(String[] args) { Set<A> set = new HashSet<>(); set.add(new A()); set.add(new A()); set.add(new A()); set.add(new A()); System.out.println(set); } } class A { int r = 1; public String toString() { return r + ""; } public int hashCode() { return r; } } a. [1] b. [1, 1] c. [1, 1, 1] d. [1, 1, 1, 1] Key:d See the fourth paragraph. Note that the equals method is not overridden. # 6. What is the output of the following code? import java.util.*; public class Test { public static void main(String[] args) { Set<String> set1 = new HashSet<>(); set1.add("Atlanta"); set1.add("Macon"); set1.add("Savanna"); Set<String> set2 = new HashSet<>(); set2.add("Atlanta"); set2.add("Macon"); set2.add("Savanna"); Set<String> set3 = new HashSet<>(); set3.add("Macon"); ..


set3.add("Savanna"); set3.add("Atlanta"); System.out.println(set1.equals(set2) + " " + set1.equals(set3)); } } a. true true b. true false c. false false d. false true Key:a See the fourth paragraph. # Section 21.2.2 LinkedHashSet 4. What is the output of the following code? import java.util.*; public class TestLinkedHashSet { public static void main(String[] args) { // Create a linked hash set Set<String> set = new LinkedHashSet<>(); // Add strings to the set set.add("London"); set.add("Paris"); set.add("New York"); set.add("San Francisco"); set.add("Beijing"); set.add("New York"); System.out.println(set); } } a. ["London", "Paris", "New York", "San Francisco", "Beijing"] b. [London, Paris, New York, San Francisco, Beijing] c. ["London", "Paris", "New York", "San Francisco", "Beijing", "New York"] d. [London, Paris, New York, San Francisco, Beijing, New York] Key:b See Listing 21.3. # 15. The output of the following code is

.

LinkedHashSet<String> set1 = new LinkedHashSet<>(); set1.add("New York"); LinkedHashSet<String> set2 = (LinkedHashSet<String>)(set1.clone()); set1.add("Atlanta"); set2.add("Dallas"); System.out.println(set2); a. [New York] b. [New York, Atlanta] c. [New York, Atlanta, Dallas] d. [New York, Dallas] Key:d set1 and set2 are two separate objects.

..


# 16. The output of the following code is

.

LinkedHashSet<String> set1 = new LinkedHashSet<>(); set1.add("New York"); LinkedHashSet<String> set2 = set1; set1.add("Atlanta"); set2.add("Dallas"); System.out.println(set2); a. [New York] b. [New York, Atlanta] c. [New York, Atlanta, Dallas] d. [New York, Dallas] Key:c set1 and set2 are the same object. # 19. If you want to store non-duplicated objects in the order in which they are inserted, you should use a. HashSet b. LinkedHashSet c. TreeSet d. ArrayList e. LinkedList Key:b LinkedHashSet is a special type of HashSet that preserves the order in which the elements are inserted. # Section 21.2.3 TreeSet 3. Which of the data types below could be used to store elements in their natural order based on the compareTo method? a. HashSet b. TreeSet c. LinkedHashSet d. Collection e. Set Key:b See Listing 21.4. # 9. Which of the following data types have iterators? a. HashSet b. TreeSet c. ArrayList d. LinkedList e. LinkedHashSet Key:abcde The Collection interface has the iterator() method to return an iterator from a collection. # 10. To get an iterator from a set, you may use the method. a. getIterator b. findIterator c. iterator d. iterators Key:c The Collection interface has the iterator() method to return an iterator from a collection. # Section 21.3 Comparing the Performance of Sets and Lists ..

.


11. Suppose set s1 is [1, 2, 5] and set s2 is [2, 3, 6]. After s1.addAll(s2), s1 is a. [1, 2, 2, 3, 5, 6] b. [1, 2, 3, 5, 6] c. [1, 5] d. [2] Key:b The addAll method is defined in the Collection interface. # 12. Suppose set s1 is [1, 2, 5] and set s2 is [2, 3, 6]. After s1.addAll(s2), s2 is a. [1, 2, 2, 3, 5, 6] b. [1, 2, 3, 5, 6] c. [1, 5] d. [2, 3, 6] e. [2] Key:d The addAll method is defined in the Collection interface.

.

.

# 13. Suppose set s1 is [1, 2, 5] and set s2 is [2, 3, 6]. After s1.removeAll(s2), s1 is a. [1, 2, 2, 3, 5, 6] b. [1, 2, 3, 5, 6] c. [1, 5] d. [2] Key:c The removeAll method is defined in the Collection interface. # 14. Suppose set s1 is [1, 2, 5] and set s2 is [2, 3, 6]. After s1.retainAll(s2), s1 is a. [1, 2, 2, 3, 5, 6] b. [1, 2, 3, 5, 6] c. [1, 5] d. [2] Key:d The retainAll method is defined in the Collection interface.

.

.

# Section 21.4 Case Study: Counting Keywords 17. Analyze the following code: import java.util.*; public class Test { public static void main(String[] args) { HashSet<String> set1 = new HashSet<>(); set1.add("red"); Set<String> set2 = set1.clone(); } } a. Line 5 is wrong because a HashSet object cannot be cloned. b. Line 5 has a compile error because set1.clone() returns an Object. You have to cast it to Set in order to compile it. c. The program will be fine if set1.clone() is replaced by (Set<String>)set1.clone() d. The program will be fine if set1.clone() is replaced by (Set<String>)(set1.clone()) e. The program will be fine if set1.clone() is replaced by (HashSet<String>)(set1.clone()) Key:bde Note that set1.clone() return an Object. # 18. Analyze the following code: ..


import java.util.*; public class Test { public static void main(String[] args) { Set<String> set1 = new HashSet<>(); set1.add("red"); Set set2 = set1.clone(); } } a. Line 5 is wrong because the declared type for set1 is Set and the clone method is not defined Set. b. The program will be fine if set1.clone() is replaced by (HashSet)set1.clone() c. The program will be fine if set1.clone() is replaced by (Set)((HashSet)set1).clone() d. The program will be fine if set1.clone() is replaced by (HashSet)((HashSet)set1).clone() e. The program will be fine if set1.clone() is replaced by (LinkedHashSet)((HashSet)set1).clone() Key:acd For (E), the program will compile fine, but will get a runtime ClassCastException because set1 is a HashSet, not a LinkedHashSet. # 20. Which of the following statements are true? a. All the methods in HashSet are inherited from the Collection interface. b. All the methods in TreeSet are inherited from the Collection interface. c. All the methods in LinkedHashSet are inherited from the Collection interface. d. All the methods in Set are inherited from the Collection interface. e. All the concrete classes of Collection have at least two constructors. One is the no-arg constructor that constructs an empty collection. The other constructs instances from a collection. Key:acde TreeSet has the first(), last(), headSet(toElement), and tailSet(fromElement) methods. # 21. Which of the following is correct to perform the set union of two sets s1 and s2? a. s1.union(s2) b. s1 + s2 c. s1.addAll(s2) d. s1.add(s2) Key:c The addAll method is to perform set union. # 22. Which of the following is correct to perform the set difference of two sets s1 and s2? a. s1.difference(s2) b. s1 - s2 c. s1.subtract(s2) d. s1.removeAll(s2) Key:d The removeAll method is to perform set difference. # 23. Which of the following is correct to perform the set intersection of two sets s1 and s2? a. s1.intersect(s2) b. s1.join(s2) c. s1.retainAll(s2) d. s1.intersection(s2) Key:c The retainAll method is to perform set intersection. # 24. Analyze the following code. ..


import java.util.*; public class Test { public static void main(String[] args) throws Exception { Set<String> set = new TreeSet<>(); set.add("Red"); set.add("Green"); set.add("Blue"); System.out.println(set.first()); } } a. The program displays Red b. The program displays Blue c. The program displays Green d. The program may display Red, Blue, or Green. e. The program cannot compile, because the first() method is not defined in Set. Key:e first() is defined in TreeSet. To compile this program, replace Set set = new TreeSet() with TreeSet set = new TreeSet(). # 25. Analyze the following code. import java.util.*; public class Test { public static void main(String[] args) throws Exception { TreeSet<String> set = new TreeSet<>(); set.add("Red"); set.add("Green"); set.add("Blue"); System.out.println(set.last()); } } a. The program displays Red b. The program displays Blue c. The program displays Green d. The program may display Red, Blue, or Green. e. The program cannot compile, because the last() method is not defined in Set. Key:a In this TreeSet, "Red" is the largest. # 26. Analyze the following code. import java.util.*; public class Test { public static void main(String[] args) throws Exception { TreeSet<String> set = new TreeSet<>();

..


set.add("Red"); set.add("Yellow"); set.add("Green"); set.add("Blue"); SortedSet temp = set.headSet("Purple"); System.out.println(temp.first()); } } a. The program displays Red b. The program displays Blue c. The program displays Green d. The program displays Yellow e. The program displays Purple Key:b In this TreeSet, "Blue" is the first. # 27. Analyze the following code. import java.util.*; public class Test { public static void main(String[] args) throws Exception { TreeSet<String> set = new TreeSet<>(); set.add("Red"); set.add("Yellow"); set.add("Green"); set.add("Blue"); SortedSet temp = set.tailSet("Purple"); System.out.println(temp.first()); } } a. The program displays Red b. The program displays Blue c. The program displays Green d. The program displays Yellow e. The program displays Purple Key:a In this TreeSet, "Red" is the first after Purple. # Section 21.5 Maps 36. Analyze the following code: public class Test { public static void main(String[] args) { Map<String, String> map = new HashMap<>(); map.put("123", "John Smith"); map.put("111", "George Smith"); map.put("123", "Steve Yao"); map.put("222", "Steve Yao"); } } ..


a. After all the four entries are added to the map, "123" is a key that corresponds to the value "John Smith". b. After all the four entries are added to the map, "123" is a key that corresponds to the value "Steve Yao". c. After all the four entries are added to the map, "Steve Yao" is a key that corresponds to the value "222". d. After all the four entries are added to the map, "John Smith" is a key that corresponds to the value "123". e. A runtime error occurs because two entries with the same key "123" are added to the map. Key:b The signature of the put method is put(key, value). So the first parameter in the put method is the key. When a new entry with the same key is added to the map, the existing entry with the same key is replaced by the new entry. # 29. The Collection interface is the base interface for a. Set b. List c. ArrayList d. LinkedList e. Map Key:abcd The Collection is not the base interface for Map.

.

# 33. The elements in are sorted. a. TreeSet b. List c. TreeMap d. HashSet e. LinkedHashSet Key:ac The elements in TreeMap and TreeSet are ordered. # 34. Suppose your program frequently tests whether a student is in a soccer team, what is the best data structure to store the students in a soccer team? a. ArrayList b. HashSet c. TreeSet c. LinkedList e. Vector Key:b # Section 21.6 Case Studies: Occurrences of Words 35. Suppose your program frequently tests whether a student is in a soccer team and also need to know the student’s information such as phone number, address, and age, what is the best data structure to store the students in a soccer team? a. ArrayList b. HashMap c. TreeMap d. LinkedList e. HashSet Key:b A HashMap would be the most efficient for this application. # 30. The Map is the base interface for a. TreeMap b. HashMap c. LinkedHashMap d. ArrayList ..

.


e. LinkedList Key:abc See Figure 21.3 in the preceding figure. # 31. Which of the following are correct methods in Map? a. put(Object key, Object value) b. put(Object value, Object key) c. get(Object key) d. get(int index) Key:ac See Figure 21.4 in the preceding figure. # 32. Which of the following are correct methods in Map? a. containsKey(Object key) b. containsValue(Object value) c. remove(Object key) d. remove(int index) e. isEmpty() Key:abce See Figure 21.4 in the preceding figure. # 28. To empty a Collection or a Map, you use the a. empty b. clear c. zero d. setEmpty Key:b The clear() method empty a map.

..

method.


Chapter 22 Developing Efficient Algorithms Section 22.2 Measuring Algorithm Efficiency Using Big O Notation 1. Analyzing algorithm efficiency is . a. to measure their actual execution time b. to estimate their execution time c. to estimate their growth function Key:c See the first paragraph in this section. # 2. An input that results in the shortest execution time is called the a. best-case input b. worst-case input c. average-case input Key:a See the second paragraph.

.

# 3. Why is the analysis often for the worst case? a. Best-case is not representative. b. Worst-case is not representative, but worst-case analysis is very useful. You can show that the algorithm will never be slower than the worst-case. c. Average-case analysis is ideal, but difficult to perform, because it is hard to determine the relative probabilities and distributions of various input instances for many problems. Key:abc See the second paragraph. # 4. Which of the following complexity is O(nlogn)? a. 300n + 400n*n b. 23nlogn + 50 c. 45n + 45nlogn + 503 d. n*n*n + nlogn Key:bc O(23nlogn + 50) = O(nlong) = O(45n + 45nlogn + 503) # 5. On an average, if an element is in the list, linear search searches a. the whole list b. half of the list c. just one element in the list d. one fourth of the list Key:b See the fourth paragraph in this section. # Section 22.3 Examples: Determining Big O 6. What is the number of iterations in the following loop: int count = 5; while (count < n) { count = count + 3; } a. n - 5 b. n - 3 c. n / 3 - 1 © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


d. (n - 5) / 3 e. the ceiling of (n - 5) / 3 Key:e Consider n = 5, 0 iteration. Consider n = 6, 1 iteration. Consider n = 7, 1 iteration. Consider n = 8, 1 iteration. Consider n = 9, 2 iterations. Consider n = 10, 2 iterations. Consider n = 11, 2 iterations. Consider n = 12, 3 iterations. Consider n = 13, 3 iterations. Consider n = 14, 3 iterations. Consider n = 15, 4 iterations. (ceiling((15-5)/3) = 4. # Section 22.4 Analyzing Algorithm Time Complexity 7. For a sorted list of 1024 elements, a binary search takes at most a. 11 b. 100 c. 512 d. 6 Key:a log(1024) is 6.

comparisons.

# 8. O(1) is . a. constant time b. logarithmic time c. linear time d. log-linear time Key:a See toward the end of the section. # 9. The time complexity for the Towers of Hanoi algorithm in the text is a. O(n) b. O(n^2) c. O(n^3) d. O(2^n) Key:d See toward the end of the section. # 11. The time complexity for the binary search algorithm in the text is a. O(nlogn) b. O(logn) c. O(n^2) d. O(2^n) Key:b See Section 22.4.1. # 10. The time complexity for the selection sort algorithm in the text is a. O(nlogn) b. O(n^2) c. O(logn) d. O(2^n) Key:b See Section 22.4.2.

.

.

.

# Section 22.5 Finding Fibonacci Numbers using Dynamic Programming 12. approach is the process of solving subproblems, then combining the solutions of the subproblems to obtain an overall solution. This naturally leads to a recursive solution. However, it would be inefficient to use recursion, because the subproblems overlap. The key idea behind dynamic programming is to solve each subproblem only once and store the results for subproblems for later use to avoid redundant computing of the subproblems. a. Divide-and-conquer © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


b. Dynamic programming c. Brutal-force d. Backtracking Key:b See the last paragraph. # 13. The time complexity for the recursive Fibonacci algorithm in the text is a. O(nlogn) b. O(n^2) c. O(logn) d. O(2^n) Key:d See the second paragraph.

.

# 14. The time complexity for the algorithm using the dynamic programming approach is a. O(n) b. O(n^2) c. O(logn) d. O(2^n) Key:a See the time complexity analysis after Listing 22.2.

.

# Section 22.6 Finding Greatest Common Divisors Using Euclid’s Algorithm 15. The time complexity for the Euclid’s algorithm is . a. O(n) b. O(n^2) c. O(logn) d. O(2^n) Key:c See the time complexity analysis after Listing 22.4. # Section 22.7 Efficient Algorithms for Finding Prime Numbers 16. The time complexity for the Sieve of Eratosthenes algorithm is a. O(n) b. O(n^(1.5)/logn) c. O(logn) d. O(2^n) Key:b See the time complexity analysis after Listing 22.7.

.

# Section 22.8 Finding the Closest Pair of Points Using Divide-and-Conquer 17. The time complexity for the the closest pair of points problem using divide-and-conquer is a. O(n) b. O(nlogn) c. O(logn) d. O(2^n) Key:b See the time complexity analysis at the end of this section.

.

# 18. approach divides the problem into subproblems, solves the subproblems, then combines the solutions of the subproblems to obtain the solution for the entire problem. Unlike the approach, the subproblems in the divide-and-conquer approach don’t overlap. A subproblem is like the original problem with a smaller size, so you can apply recursion to solve the problem. a. Divide-and-conquer/dynamic programming © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


b. Dynamic programming/divide-and-conquer c. Brutal-force/divide-and-conquer d. Backtracking/dynamic programming Key:a See the third paragraph. # Section 22.9 Solving the Eight Queens Problem Using Backtracking 19. The approach searches for a candidate solution incrementally, abandoning that option as soon as it determines that the candidate cannot possibly be a valid solution, and then looks for a new candidate. a. Divide-and-conquer b. Dynamic programming c. Brutal-force d. Backtracking Key:d See the first paragraph. # Section 22.10 Computational Geometry: Finding a Convex Hull Section 22.10.1 Gift-Wrapping Algorithm 20. The gift-wrapping algorithm for finding a convex hull takes a. O(n) b. O(nlogn) c. O(logn) d. O(n^2) Key:d See Section 22.10.1. # Section 22.10.2 Graham's Algorithm 21. The Graham’s algorithm for finding a convex hull takes a. O(n) b. O(nlogn) c. O(logn) d. O(n^2) Key:b See Section 22.10.2.

time.

time.

# Section 22.11 String Matching 22. To find a match for a string of size m in a text of size n, the brute-force algorithm would take worst case. a. O(n) time b. O(m) time c. O(n + m) time d. O(m*n) time Key:d See the end of the section. # Section 22.11.1 The Boyer-Moore Algorithm 23. To find a match for a string of size m in a text of size n, the Boyer-Moore algorithm would take the worst case. a. O(n) time b. O(m) time c. O(n + m) time d. O(m*n) time Key:d See the end of the section.

in the

in

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


# Section 22.11.2 The Knuth-Morris-Pratt Algorithm 24. To find a match for a string of size m in a text of size n, the KMP algorithm would take worst case. a. O(n) time b. O(m) time c. O(n + m) time d. O(m*n) time Key:c See the end of the section.

in the

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


Chapter 23 Sorting Section 23.2 Insertion Sort 1. The best-time complexity for insertion sort is a. O(1) b. O(logn) c. O(n) d. O(nlogn) e. O(n*n) Key:c In the best case, the list is already sorted.

.

# 2. The worst-time complexity for insertion sort is . a. O(1) b. O(logn) c. O(n) d. O(nlogn) e. O(n*n) Key:e See the time complexity analysis at the end of the section. # Section 23.3 Bubble Sort 3. Suppose a list is {2, 9, 5, 4, 8, 1}. After the first pass of bubble sort, the list becomes a. 2, 9, 5, 4, 8, 1 b. 2, 9, 5, 4, 1, 8 c. 2, 5, 9, 4, 8, 1 d. 2, 5, 4, 8, 1, 9 e. 2, 1, 5, 4, 8, 9 Key:d See Figure 23.3. # 4. The best-time complexity for bubble sort is a. O(1) b. O(logn) c. O(n) d. O(nlogn) e. O(n*n) Key:c In the best case, the list is already sorted.

.

# 5. The worst-time complexity for bubble sort is . a. O(1) b. O(logn) c. O(n) d. O(nlogn) e. O(n*n) Key:e See the time complexity analysis at the end of the section. # Section 23.4 Merge Sort 6. The time to merge two sorted lists of size n is a. O(1) b. O(logn)

.

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


c. O(n) d. O(nlogn) e. O(n*n) Key:c See Figure 23.5. # 7. The worst-time complexity for merge sort is . a. O(1) b. O(logn) c. O(n) d. O(nlogn) e. O(n*n) Key:d See the time complexity analysis at the end of this section. # 8. The average-time complexity for merge sort is . a. O(1) b. O(logn) c. O(n) d. O(nlogn) e. O(n*n) Key:d See the time complexity analysis at the end of this section. # Section 23.5 Quick Sort 9. What is correct about a pivot? a. A pivot divides a list into two sublists of equal size. b. A pivot can be chosen arbitrarily. c. A pivot divides a list into two sublists, the elements in the first list are no larger than the pivot and the elements in the second list are larger than the pivot. d. You should always choose a pivot that divides the list evenly. Key:bc See the Listing 23.7. # 10. Suppose you choose the first element as a pivot in the list {5 2 9 3 8 4 0 1 6 7}. Using the partition algorithm in the book, what is the new list after the partition? a. 5 2 9 3 8 4 0 1 6 7 b. 4 2 3 0 1 5 6 7 9 8 c. 4 2 1 3 0 5 8 9 6 7 d. 2 3 4 0 1 5 9 8 6 7 e. 2 3 4 0 1 5 6 7 8 9 Key:c See the partition animation. # 11. The worst-time complexity for quick sort is . a. O(1) b. O(logn) c. O(n) d. O(nlogn) e. O(n*n) Key:e See the time complexity analysis at the end of this section. # 12. The average-time complexity for quick sort is

.

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


a. O(1) b. O(logn) c. O(n) d. O(nlogn) e. O(n*n) Key:d See the time complexity analysis at the end of this section. # 13. Using the partition algorithm to partition an array {5, 8, 10, 3, 4, 19, 2} for a quick sort, what is the resulting array after the partition? a. {5, 8, 10, 3, 4, 19, 2} b. {2, 3, 4, 5, 8, 10, 19} c. {2, 3, 4, 5, 10, 19, 8} d. {3, 2, 4, 5, 10, 19, 8} e. {3, 2, 4, 5, 8, 10, 19} Key:d See Figure 23.8. # Section 23.6 Heap Sort 14. Which of the following statements are true? a. A heap is a complete binary tree. b. Each node is greater than or equal to any of its children. c. A binary tree is complete if every level of the tree is full except that the last level may not be full and all the leaves on the last level are placed left-most. d. A heap is a full binary tree. Key:abc See the first part in this section. # Section 23.6.1 Storing a Heap 17. A heap is represented using an array. Is the array {1 2 4 5 9 3} a heap? a. Yes b. No Key:b See Figure 23.11. # 18. A heap is represented using an array. Is the array {64 42 59 32 39 44} a heap? a. Yes b. No Key:a See Figure 23.11. # 21. Suppose a heap is stored in an array list as follows: {100, 55, 92, 23, 33, 81}. The parent of 81 is a. 100 b. 55 c. 92 d. 23 e. 33 Key:c See Figure 23.11. # Section 23.6.2 Adding a New Node 16. To add a new node, you need to start a process by first placing it as property. a. the new root

.

and move it up to maintain the heap

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


b. the last node in the heap c. the left child of the root d. the right child of the root Key:b See Figure 23.12. # 22. Suppose a heap is stored in an array list as follows: {100, 55, 92, 23, 33, 81}. After inserting 103, what is the content of the array list? a. {100, 55, 92, 23, 33, 81, 103} b. {100, 55, 103, 23, 33, 92, 81} c. {103, 55, 92, 23, 33, 81, 92} d. {103, 55, 100, 23, 33, 81, 92} e. {103, 55, 92, 23, 33, 81, 100} Key:d See Figure 23.13. # Section 23.6.3 Removing a New Node 15. To remove the root, you need to start a process by first placing to maintain the heap property. a. one of the root's children b. the larger child of the root c. the smaller child of the root d. the last node in the heap Key:d See Figure 23.14.

to the place of the root and move it down

# Section 23.6.6 Heap Sort Time Complexity 19. The worst-time complexity for heap sort is a. O(1) b. O(logn) c. O(n) d. O(nlogn) e. O(n*n) Key:d See the discussion in this section. # 20. The average-time complexity for heap sort is a. O(1) b. O(logn) c. O(n) d. O(nlogn) e. O(n*n) Key:d See the discussion in this section. # Section 23.7 Bucket Sort and Radix Sort 23. The most efficient algorithm for sorting integer keys is a. quick sort b. merge sort c. heap sort d. radix sort Key:d The complexity of radix sort is O(n).

.

# © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


24. The algorithm does not compare keys. a. quick sort b. merge sort c. heap sort d. radix sort Key:d See the first paragraph in this section.

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues Section 24.2 Common Operations for Lists 1. is a data structure to store data in sequential order. a. A list b. A set c. A tree d. A stack e. A queue Key:a See the first paragraph. # 2. Which of the following operations are supported by a list? a. Retrieve an element from this list. b. Insert a new element to this list. c. Delete an element from this list. d. Find how many elements are in this list. e. Find whether an element is in this list. Key:abcde See the bullet items. # 3. Which of the following statements are true? a. MyArrayList and MyLinkedList are two concrete implementations of MyList. b. MyArrayList is implemented using an array. The array is dynamically created. If the capacity of the array is exceeded, create a new larger array and copy all the elements from the current array to the new array. c. MyLinkedList is implemented using a linked structure. d. A linked structure consists of nodes. Each node is dynamically created to hold an element. All the nodes are linked together to form a list. Key:abcd See Figure 24.2. # Section 24.3 Array Lists 4. In the implementation of MyArrayList, which of the following are true? a. size indicates the number of elements in the list. b. capacity is the length of the array used to store the elements in the list. c. capacity is always greater than size. d. size is reduced by 1 if an element is deleted from the list. e. capacity is reduced by 1 if an element is deleted from the list. Key:abd (C) is not correct because capacity may be equal to size. # 5. In the implementation of MyArrayList, which of the following are true? a. size never reduces. b. capacity never reduces. c. Inside MyArrayList, a regular array is used to store elements. d. size is not declared in MyArrayList, but declared in MyAbstractList as protected. e. If the current capacity equals to size, capacity is doubled when a new element is added to MyArrayList Key:bcde See Listing 24.2. # Section 24.4.3 Implementing MyLinkedLinked Lists 6. In the implementation of MyLinkedList, which of the following are true? a. MyLinkedList contains all the methods defined in MyList. Additionally, MyLinkedList defines several new methods ..


that are appropriate for processing a linked list. b. MyArrayList does not introduce new methods. All the methods in MyArrayList are defined in MyList. c. You can use a linked list to improve efficiency for adding and removing an element anywhere in a list. d. You should use an array list if your application does not require adding and removing an element anywhere in a list. Key:abcd See Listing 24.5. # 7. In the implementation of MyLinkedList, which of the following are true? a. Node is defined as an inner class inside MyLinkedList. b. Node is defined as a static inner class inside MyLinkedList because it does not reference any instance data fields in MyLinkedList. c. Node has a property named next that links to the node after this node. d. Node has a property named element that stores an element. Key:abcd See Listing 24.5. # 8. In the implementation of MyLinkedList, which of the following are true? a. MyLinkedList has a capacity property. b. MyLinkedList has the properties named first and last to point to the nodes in a linked list. c. If a linked list is empty, first is null and last is null. d. If a linked list contains one element, first points to the node and last is null. e. last.next is always null. Key:bce (D) is partially wrong, last and first points to the same node if a linked list contains one node. # Section 24.4.4 MyArrayList vs. MyLinkedList 9. MyArrayList is more efficient than MyLinkedList for the following operations: a. Insert/delete an element in the middle of the list. b. Insert/delete an element in the beginning of the list. c. Append an element at the end of the list. d. Retrieve an element at given the index. Key:d See Table 24.1. # 10. MyLinkedList is more efficient than MyArrayList for the following operations: a. Insert/delete an element in the middle of the list. b. Insert/delete an element in the beginning of the list c. Append an element at the end of the list. d. Retrieve an element at given the index. Key:b See Table 24.1. # 11. Suppose list1 is a MyArrayList and list2 is a MyLinkedList. Both contains 1 million double values. Analyze the following code: A: while (list1.size() > 0) list1.remove(0); B: while (list2.size() > 0) list2.remove(0); a. Code fragment A runs faster than code fragment B. ..


b. Code fragment B runs faster than code fragment A. c. Code fragment A runs as fast as code fragment B. Key:b It takes O(1) time to remove the first element in a linked list. # 12. Suppose list1 is an MyArrayList and list2 is a MyLinkedList. Both contains 1 million double values. Analyze the following code: A: while (list1.size() > 0) list1.remove(size() - 1); B: while (list2.size() > 0) list2.remove(size() - 1); a. Code fragment A runs faster than code fragment B. b. Code fragment B runs faster than code fragment A. c. Code fragment A runs as fast as code fragment B. Key:a It takes O(n) time to remove the last element in a MyLinkedList. # 13. Suppose list1 is an MyArrayList and list2 is a MyLinkedList. Both contains 1 million double values. Analyze the following code: A: for (int i = 0; i < 100000; i++) list1.add(0, i); B: for (int i = 0; i < 100000; i++) list2.add(0, i); a. Code fragment A runs faster than code fragment B. b. Code fragment B runs faster than code fragment A. c. Code fragment A runs as fast as code fragment B. Key:b LinkedList takes constant time to insert at the beginning. # 14. Suppose list1 is an MyArrayList and list2 is a MyLinkedList. Both contains 1 million double values. Analyze the following code: A: for (int i = 0; i < 100000; i++) list1.add(i); B: for (int i = 0; i < 100000; i++) list2.add(i); a. Code fragment A runs faster than code fragment B. b. Code fragment B runs faster than code fragment A. c. Code fragment A runs as fast as code fragment B. Key:c MyLinkedList is a one-way LinkedList. It takes O(n) time to append at the end. ..


# 15. Suppose list1 is a MyArrayList and list2 is a MyLinkedList. Both contains 1 million double values. Analyze the following code: A: for (int i = 0; i < list1.size(); i++) sum += list1.get(i); B: for (int i = 0; i < list2.size(); i++) sum += list2.get(i); a. Code fragment A is more efficient that code fragment B. b. Code fragment B is more efficient that code fragment A. c. Code fragment A is as efficient as code fragment B. Key:a The get(i) method takes O(1) time in MyArrayList, but O(n) time in MyLinkedList. # Section 24.5 Stacks and Queues 16. Which of the following are true? a. A stack can be viewed as a special type of list, where the elements are accessed, inserted, and deleted only from the end, called the top, of the stack. b. A queue represents a waiting list. A queue can be viewed as a special type of list, where the elements are inserted into the end (tail) of the queue, and are accessed and deleted from the beginning (head) of the queue. c. Since the insertion and deletion operations on a stack are made only at the end of the stack, you can use either an ArrayList or a LinkedList. However, ArrayList has less overhead than LinkedList. d. Since deletions are made at the beginning of the list, it is more efficient to implement a queue using a LinkedList than an ArrayList. Key:abcd See the first paragraph. # 17. In the implementation of MyStack and MyQueue, which of the following are true? a. MyStack contains all the methods defined in MyArrayList. b. MyQueue contains all the methods defined in MyLinkedList. c. MyStack contains an array list for storing elements. d. MyQueue contains a linked list for storing elements. Key:cd See Figure 24.21. # Section 24.6 Priority Queues 18. Which data structure is appropriate to store patients in an emergency room? a. Stack b. Queue c. Priority Queue d. Linked List Key:c See the first paragraph. # 19. Which data structure is appropriate to store customers in a clinic for taking flu shots? a. Stack b. Queue c. Priority Queue d. Array List ..


e. Linked List Key:b See the first paragraph. # 20. Suppose the rule of the party is that the participants who arrive later will leave earlier. Which data structure is appropriate to store the participants? a. Stack b. Queue c. Array List d. Linked List Key:a See the first paragraph.

..


Chapter 25 Binary Search Trees Section 25.2 Binary Search Tree Basics 1. A (with no duplicate elements) has the property that for every node in the tree the value of any node in its left subtree is less than the value of the node and the value of any node in its right subtree is greater than the value of the node. a. binary tree b. binary search tree c. list d. linked list Key:b See the third paragraph. # 2. The of a path is the number of the edges in the path. a. length b. depth c. height d. degree Key:a See the second paragraph. # 3. The of a node is the length of the path from the root to the node. a. length b. depth c. height d. degree Key:b See the second paragraph. # 4. The of a nonempty tree is the length of the path from the root node to its furthest leaf + 1. a. length b. depth c. height d. degree Key:c See the second paragraph. # Section 25.3 Representing Binary Search Trees 10. Which of the following is correct to create a TreeNode for integer 50. a. TreeNode<int> node = new TreeNode<int>(50); b. TreeNode<Integer> node = new TreeNode<Integer>(50); c. TreeNode<Integer> node = new TreeNode<>(50); d. TreeNode<int> node = new TreeNode<>(50); Key:bc The actual type for generic parameter must be an object type. So <int> is wrong. # Section 25.4 Searching for an Element 10. What is the return type for the search function? a. int b. double c. char d. boolean Key:d See Listing 25.1. ..


# 11. The time complexity for searching an element in a binary search tree is a. O(n) b. O(logn) c. O(nlogn) d. O(n^2) Key:a In the worst case, all the nodes may be in one line.

.

# Section 25.5 Inserting an Element into a BST 10. A new element is always inserted into a leaf node. a. True b. False Key:a See Listing 25.2. # 12. The time complexity for inserting an element into a binary search tree is a. O(n) b. O(logn) c. O(nlogn) d. O(n^2) Key:a In the worst case, all the nodes may be in one line.

.

# Section 25.6 Tree Traversal 8. The is to visit the nodes level by level. First visit the root, then all children of the root from left to right, then grandchildren of the root from left to right, and so on. a. inorder traversal b. preorder traversal c. postorder traversal d. breadth-first traversal Key:d See the definition for all the traversals presented in this section. # 16. Suppose the keys 3, 4, 45, 21, 92, 12 are inserted into a BST in this order. What is the inorder traversal of the elements? a. 3 4 12 21 45 92 b. 3 4 45 21 12 92 c. 12 21 92 45 4 3 d. 4 45 21 12 92 3 e. 4 21 12 92 45 3 Key:a See the first paragraph. # 18. Suppose the keys 3, 4, 45, 21, 92, 12 are inserted into a BST in this order. What is the postorder traversal of the elements? a. 3 4 12 21 45 92 b. 3 4 45 21 12 92 c. 12 21 92 45 4 3 d. 4 45 21 12 92 3 e. 4 21 12 92 45 3 Key:c See the second paragraph.

..


# 17. Suppose the keys 3, 4, 45, 21, 92, 12 are inserted into a BST in this order. What is the preorder traversal of the elements? a. 3 4 12 21 45 92 b. 3 4 45 21 12 92 c. 12 21 92 45 4 3 d. 4 45 21 12 92 3 e. 4 21 12 92 45 3 Key:b See the third paragraph. # 19. Suppose the keys 3, 4, 45, 21, 92, 12 are inserted into a BST in this order. What is the preorder traversal of the elements after inserting 2 into the tree? a. 3 2 4 12 21 45 92 b. 3 2 4 45 21 12 92 c. 12 2 21 92 45 4 3 d. 4 2 45 21 12 92 3 e. 4 2 21 12 92 45 3 Key:b See the third paragraph. # 5. The is to visit the left subtree of the current node first, then the current node itself, and finally the right subtree of the current node. a. inorder traversal b. preorder traversal c. postorder traversal d. breadth-first traversal Key:a See the discussion on tree traversal in this section. # 6. The is to visit the left subtree of the current node first, then the right subtree of the current node, and finally the current node itself. a. inorder traversal b. preorder traversal c. postorder traversal d. breadth-first traversal Key:c See the discussion on tree traversal in this section. # 7. The is to visit the current node first, then the left subtree of the current node, and finally the right subtree of the current node. a. inorder traversal b. preorder traversal c. postorder traversal d. breadth-first traversal Key:b See the discussion on tree traversal in this section. # Section 25.7 The BST Class 9. In the implementation of BST, which of the following are true? a. Node is defined as an inner class inside BST. b. Node is defined as a static inner class inside BST because it does not reference any instance data fields in BST. c. Node has a property named left that links to the left subtree and a property named right that links to the right subtree and a property named right ..


d. BST contains a property named root. If tree is empty, root is null. Key:abcd See Figure 25.6. # Section 25.8 Deleting Elements from a BST 13. The time complexity for deleing an element into a binary search tree is a. O(n) b. O(logn) c. O(nlogn) d. O(n^2) Key:a In the worst case, all the nodes may be in one line.

.

# Section 25.9 Tree Visualization and MVC 14. What is the signature of the recursive method in BTView.java? a. displayTree() b. displayTree(BST.TreeNode<Integer>, double, double, double) c. displayTree(BST.TreeNode<String>, double, double, double) d. displayTree(BST.TreeNode<Integer>, int, int, int) Key:b See Listing 25.9. # 20. Suppose the keys 3, 4, 45, 21, 92, 12 are inserted into a BST in this order. What is the preorder traversal of the elements after deleting 45 from the tree? a. 3 4 12 21 92 b. 3 4 21 12 92 c. 12 21 92 45 4 3 d. 4 21 12 92 3 Key:b See the algorithm for deleting an element from a BST in this section and the discussion on tree traversal in Section 25.6. # Section 25.10 Iterators 14. True or False? You can traverse the elements in a BST using a for-each loop. a. True b. False Key:a See Listing 25.10. # Section 25.11 Case Study: Data Compression 15. A Huffman tree is constructed using a a. dynamic programming b. divide-and-conquer c. greedy d. back-tracking Key:c See the paragraph before Figure 25.19.

..

algorithm.


Chapter 26 AVL Trees Section 26.1 Introduction 1. The of a node is the height of its right subtree minus the height of its left subtree. a. balance factor b. depth c. length d. degree Key:a See the third paragraph. # 2. The balance factor of every node in an AVL tree may be a. 0 b. 1 c. -1 d. 2 Key:abc See the third paragraph.

.

# 3. A(n) (with no duplicate elements) has the property that for every node in the tree the value of any node in its left subtree is less than the value of the node and the value of any node in its right subtree is greater than the value of the node. a. binary tree b. binary search tree c. AVL tree d. binary heap Key:bc An AVL tree is a BST. # Section 26.2 Rebalancing Trees 5. If a node has a balance factor 2 and its right child node has a balance factor 1 or 0. This node is a. LL imbalance b. LR imbalance c. RR imbalance d. RL imbalance Key:c See the definition for the RR imbalance. # 5. If a node has a balance factor -2 and its right child node has a balance factor 1 or 0. This node is a. LL imbalance b. LR imbalance c. RR imbalance d. RL imbalance Key:b See the definition for the LR imbalance.

.

.

# Section 26.3 Designing Classes for AVL Trees 5. The AVLTreeNode class contains the data fields: a. element b. height c. left d. right Key:abcd See Figure 26.8. © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


# Section 26.7 The AVLTree Class 5. In a(n) , the element j to be removed is always at the root. a. binary tree b. binary search tree c. AVL tree d. binary heap Key:d In a binary heap, the element to be removed is always at the root. # 6. In a(n) , the element just inserted is always at the leaf. a. binary search tree b. AVL tree c. binary heap Key:ab In a BST and AVLTree, the new element is always inserted at the leaf. # 8. What is the preorder traversal of the elements in a AVL tree after inserting 3, 4, 45, 21, 92, 12 in this order? a. 3 4 12 21 92 45 b. 3 4 12 21 45 92 c. 45 4 3 21 12 92 d. 45 21 12 92 3 4 e. 21 4 3 12 45 92 Key:e For preorder, see Section 25.6. # Section 26.9 AVL Tree Time Complexity Analysis 4. The time complexity for insertion, deletion, and search is O(logn) for a(n) a. binary tree b. binary search tree c. AVL tree d. binary heap Key:c See the time analysis in this section.

.

# 7. The average time-complexity for insertion, deletion, and search in a(n) is O(logn). a. binary search tree b. AVL tree c. binary heap Key:b See the time analysis in this section. In a binary heap, search would take O(n) time.

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


Chapter 27 Hashing Section 27.2 What Is Hashing? 1. A hashing function . a. stores an element in the hash table b. maps a key to an index in the hash table Key:b See the first paragraph in this section. # 2. If each key is mapped to a different index in the hash table, it is called a. normal hashing b. perfect hashing Key:b See the first paragraph in this section.

.

# 3. A collision occurs . a. when two or more keys are mapped to the same hash value. b. when two elements have the same key value. c. when two elements are mapped to the same key. Key:a See the last paragraph in this section. # Section 27.3 Hash Functions and Hash Codes 5. What is the return type value for the hashCode() method? a. byte b. short c. int d. long Key:c See the first paragraph. # 6. True or False? Two objects have the same hash codes if they are equal. a. True b. False Key:a See the first numbered item. # 7. True or False? Two objects are equal if their hash codes are equal. a. True b. False Key:b Two different objects may have the hash code. # 4. Every object has the hashCode() method. a. True b. False Key:a See the first paragraph in this section. # Section 27.3.1 Hash Codes for Primitive Types 9. For an Integer object with value 20, what is its hashCode? a. 10 b. 20 © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


c. 30 d. 40 Key:b See the first paragraph. # Section 27.3.2 Hash Codes for Strings 8. If two strings are equal, the two strings have the same hashCodes. a. True b. False Key:a See the first numbered item in Section 27.3. # Section 27.3.3 Compressing Hash Codes 4. True or False? Assume N and hashCode are positive and N is an integer of power of 2, hashCode % N is the same as hashCode & (N - 1). a. True b. False Key:a See the second paragraph in this section. # 10. 1 & 3 is . a. 0 b. 1 c. 2 d. 3 Key:b See the discussion in this section. # 10. 1 << 2 is . a. 2 b. 3 c. 4 d. 5 Key:c See the discussion in this section. # Section 27.4 Handling Collision Using Open Addressing 12. When a collision occurs during the insertion of an entry to a hash table, sequentially. a. linear probing b. quadratic probing c. double hashing. Key:a See Section 27.4.1.

finds the next available location

# Section 27.5 Handling Collision Using Separate Chaining 11. is to find an open location in the hash table in the event of collision. a. Open addressing b. Separate chaining Key:a See Section 27.4.1. # 13. The locations.

places all entries with the same hash index into the same location, rather than finding new

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


a. open addressing scheme b. separate chaining scheme Key:b See Figure 27.7. # Section 27.6 Load Factor and Rehashing 14. measures how full the hash table is. a. Load factor b. Threshold Key:a See the first paragraph.

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


Chapter 28 Graphs and Applications Section 28.2 Basic Graph Terminologies 1. A is an edge that links a vertex to itself. a. loop b. parallel edge c. weighted edge d. directed edge Key:a See the basic terminologies in this section. # 2. If two vertices are connected by two or more edges, these edges are called a. loop b. parallel edge c. weighted edge d. directed edge Key:b See the basic terminologies in this section. # 3. A

.

is the one in which every two pairs of vertices are connected.

a. complete graph b. weighted graph c. directed graph Key:a See the basic terminologies in this section. # 4. What is the number of edges in a complete graph of n vertices? a. n b. n - 1 c. n(n-1)/2 d. n*n Key:c (n-1) + (n-2) + ... + 3 + 2 + 1 (i.e., the first vertext has n-1 edges, remove it. The next vertex has n-1 edges. Remove it. so on.) # 5. What is the number of edges in a tree of n vertices? a. n b. n - 1 c. n(n-1)/2 d. n*n Key:b A tree of n vertices has n-1 edges. # Section 28.4 Modeling Graphs 6. Suppose a graph is created in the following code. What is the output of the following code? String[] vertices = {"Atlanta", "Dallas", "Chicago", "New York", "Seattle"}; int[][] edges = { {0, 1}, {0, 2}, {1, 0}, {1, 2}, {1, 3}, {1, 4}, {2, 0}, {2, 1}, {2, 3}, ..


{3, 1}, {3, 2}, {3, 4}, {4, 1}, {4, 3} }; Graph<String> graph1 = new UnweightedGraph<>(vertices, edges); System.out.println("The index of vertex Chicago is: " + graph1.getIndex("Chicago")); a. 1 b. 2 c. 3 d. 4 e. 5 Key:b See Listing 28.2. # 7. Suppose a graph is created in the following code. What is the number of vertices in the graph? Integer[] vertices = {0, 1, 2, 3, 4}; int[][] edges = { {0, 1}, {0, 2}, {1, 0}, {1, 2}, {1, 3}, {1, 4}, {2, 0}, {2, 1}, {2, 3}, {3, 1}, {3, 2}, {3, 4}, {4, 1}, {4, 3} }; Graph<Integer> graph1 = new UnweightedGraph<>(vertices, edges); System.out.println("The number of vertices in graph1: " + graph1.getSize()); a. 1 b. 2 c. 3 d. 4 e. 5 Key:e See Listing 28.2. # 8. Suppose a graph is created in the following code. What is the degree of vertex 3 in the graph? Integer[] vertices = {0, 1, 2, 3, 4}; int[][] edges = { {0, 1}, {0, 2}, {1, 0}, {1, 2}, {1, 3}, {1, 4}, {2, 0}, {2, 1}, {2, 3}, {3, 1}, {3, 2}, {3, 4}, {4, 1}, {4, 3} }; Graph<Integer> graph1 = new UnweightedGraph<>(vertices, edges); System.out.println("The degree of vertex 3: " + graph1.getDegree(3)); a. 1 ..


b. 2 c. 3 d. 4 e. 5 Key:c See Listing 28.2. # Section 28.7 Depth-First Search (DSF) 11. Suppose a graph is created in the following code. Using the dfs algorithm in the text, what is the output for the path from 4 to 0? Integer[] vertices = {0, 1, 2, 3, 4}; int[][] edges = { {0, 1}, {0, 2}, {1, 0}, {1, 2}, {1, 3}, {1, 4}, {2, 0}, {2, 1}, {2, 3}, {3, 1}, {3, 2}, {3, 4}, {4, 1}, {4, 3} }; Graph<Integer> graph1 = new UnweightedGraph<>(vertices, edges); UnweigtedGraph<Integer>.Tree dfs = graph1.dfs(0); System.out.println(dfs.getPath(4)); a. [4, 3, 2, 0] b. [4, 3, 1, 0] c. [4, 1, 0] d. [4, 3, 2, 1, 0] e. [4, 1, 2, 0] Key:d See Listing 28.9. # 9. The search of a graph first visits a vertex, then it recursively visits all the vertices adjacent to that vertex. a. depth-first b. breadth-first Key:a See Listing 28.8. # 10. The time complexity of the DFS algorithm is O(|E| + |V|). a. true b. false Key:a See the paragraph before Figure 28.12. # Section 28.9 Breadth-First Search 14. Suppose a graph is created in the following code. Using the bfs algorithm in the text, what is the output for the path from 4 to 0? Integer[] vertices = {0, 1, 2, 3, 4}; int[][] edges = { {0, 1}, {0, 2}, {1, 0}, {1, 2}, {1, 3}, {1, 4}, {2, 0}, {2, 1}, {2, 3}, ..


{3, 1}, {3, 2}, {3, 4}, {4, 1}, {4, 3} }; Graph<Integer> graph1 = new UnweightedGraph<>(vertices, edges); UnweightedGraph<Integer>.Tree bfs = graph1.bfs(0); System.out.println(bfs.getPath(4)); a. [4, 3, 2, 0] b. [4, 3, 1, 0] c. [4, 1, 0] d. [4, 3, 2, 1, 0] e. [4, 1, 2, 0] Key:c See Listing 28.12. # 13. The time complexity of the BFS algorithm is O(|E| + |V|). a. true b. false Key:a See the paragraph before Figure 28.15. # 12. The search of a graph first visits a vertex, then all its adjacent vertices, then all the vertices adjacent to those vertices, and so on. a. depth-first b. breadth-first Key:b See Listing 28.11.

..


Chapter 29 Weighted Graphs and Applications Section 29.2 Representing Weighted Graphs 1. True or False? The WeightedEdge class extends Edge. a. True b. False Key:a See Listing 29.1. # 2. A WeightedEdge object contains the public data fields a. u b. v c. weight d. length Key:abc See Listing 29.1. # Section 29.3 The WeightedGraph Class 4. The WeightedGraph is a subtype of a. UnweightedGraph b. AbstractGraph c. Graph d. WeightedEdge Key:ac See Figure 29.4.

.

.

# 3. The adjacent edge for each vertex in the WeightedGraph class is stored in a. an ArrayList b. a LinkedList c. a PriorityQueue d. a Stack Key:a See Listing 29.2.

.

# 5. The addEdge(u, v, w) method performs the following operations: a. Invokes super.add(u, v) to add an edge. b. Adds a weighed edge to the adjacent list for vertex u. c. Adds a weighed edge to the adjacent list for vertex v. Key:abc See Listing 29.2. # Section 29.4 Minimum Spanning Trees 9. Suppose a weighted graph is created in the following code. What is total weight of a minimum spanning tree? Integer[] vertices = {0, 1, 2, 3, 4}; int[][] edges = { {0, 1, 9}, {0, 2, 5}, {1, 0, 9}, {1, 2, 6}, {1, 3, 4}, {1, 4, 7}, {2, 0, 5}, {2, 1, 6}, {2, 3, 3}, {3, 1, 4}, {3, 2, 3}, {3, 4, 1}, {4, 1, 7}, {4, 3, 1} }; © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


WeightedGraph<Integer> graph1 = new WeightedGraph<>(vertices, edges); WeightedGraph<Integer>.MST tree1 = graph1.getMinimumSpanningTree(); System.out.println("Total weight is " + tree1.getTotalWeight()); a. 10 b. 11 c. 12 d. 13 e. 14 Key:d See Listing 29.6. # 7. The MST class is subtype of a. BST b. AVLTree c. SearchTree d. Tree Key:c See Figure 29.8.

.

# 8. The getMinimumSpanningTree() method returns a. an ArrayList b. a LinkedList c. a queue d. a MST Key:d See Listing 29.5.

.

# 6. A graph may have several minimum spanning tree. a. True b. False Key:a See Figure 29.5. # Section 29.5 Finding Shortest Paths 13. Suppose a weighted graph is created in the following code. What is the shortest path from vertex 4 to 0? Integer[] vertices = {0, 1, 2, 3, 4}; int[][] edges = { {0, 1, 9}, {0, 2, 5}, {1, 0, 9}, {1, 2, 6}, {1, 3, 4}, {1, 4, 7}, {2, 0, 5}, {2, 1, 6}, {2, 3, 3}, {3, 1, 4}, {3, 2, 3}, {3, 4, 1}, {4, 1, 7}, {4, 3, 1} }; WeightedGraph<Integer> graph1 = new WeightedGraph<>(vertices, edges); WeightedGraph<Integer>.ShortestPathTree tree1 = graph1.getShortestPath(graph1.getIndex(0));

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


System.out.println("Shortest path from 4 to 0 is " + tree1.getPath(4)); a. 4 1 0 b. 4 1 3 2 0 c. 4 3 2 0 d. 4 3 1 0 e. 4 1 2 0 Key:c See Listing 29.8. # 11. The ShortestPathTree class is subtype of a. BST b. AVLTree c. UnweightedGraph.SearchTree d. Tree Key:c See Figure 29.19. # 12. The getShortestPath() method returns a. an ArrayList b. a LinkedList c. a ShortestPathTree d. a MST Key:c See Listing 29.7.

.

.

# 10. A of a graph is a subgraph that is a tree and connects all vertices in the graph. a. spanning tree b. shortest path Key:a See the definition of spanning tree and shortest path in this chapter.

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


Chapter 30 Aggregate Operations on Collection Streams Section 30.2 Stream Pipelines 1. The default method is defined the Collection interface for creating a stream. a. getStream() b. Stream() c. stream() d. findStream() Key:c See the first paragraph. # 2. The Stream interface extends a. Collection b. Collections c. BaseStreams d. BaseStream Key:d See Figure 30.1. # 3. A stream pipeline may contain a. 0 b. 1 c. 0 or 1 d. 0 or more Key:d See the third paragraph. # 4. A stream pipeline may contain a. 0 b. 1 c. 0 or 1 d. 0 or more Key:b See the third paragraph.

.

intermediate methods.

terminal methods.

# 5. The Stream<T> interface contains static methods for creating instances of Stream. a. empty() b. of(T... values) c. of(values: T) d. concat(Stream<? extedns T> s1, Stream<? extends T> s2) Key:abcd See Figure 30.1. # 6. is an intermediate method. a. distinct b. filter c. limit d. skip Key:abcd See Figure 30.1. # 7. a. sorted ..

is an intermediate method.


b. map c. mapToInt d. mapToLong e. mapToDouble Key:abcde See Figure 30.1. # 8. is a terminal method. a. count b. max c. min d. findFirst e. findAny Key:abcde See Figure 30.1. # 9. is a terminal method. a. allMatch b. anyMatch c. noneMatch d. forEach Key:abcd See Figure 30.1. # 10. is a terminal method. a. reduce b. collect c. toArray d. map Key:abc See Figure 30.1. # 11. Which of the following methods takes an argument of the Comparator type? a. max b. min c. sorted d. forEach Key:abc See Figure 30.1. # 12. The statement forEach(System.out::println) is the same as a. forEach(System.out::print) b. forEach(System.out.println) c. forEach(e -> System.out.println()) d. forEach(e -> System.out.println(e)) Key:d See Figure 30.1.

.

# 13. The statement sorted((s1, s2) -> s1.compareToIgnoreCase(s2)) is the same as a. sorted(String::compareToIgnoreCase(s)) b. sorted(String::compareToIgnoreCase()) c. sorted(String::compareToIgnoreCase) d. sorted(compareToIgnoreCase(s)) Key:c See Figure 20.6 on Comparator. Comparator is often used with streams. ..

.


# 14. What is the output of the following code? Character[] chars = {'D', 'B', 'A', 'C'}; Stream.of(chars).filter(e -> e > 'B').sorted() .forEach(System.out::print); a. DC b. CD c. ABCD d. DCBA Key:b See Listing 30.1. # 15. What is the output of the following code? Character[] chars = {'D', 'B', 'A', 'C'}; System.out.println(Stream.of(chars).allMatch(e -> e > 'B') + " " + Stream.of(chars).noneMatch(e -> e > 'B')); a. true true b. true false c. false true d. false false Key:d See Listing 30.1. # 16. What is the output of the following code? Character[] chars = {'D', 'B', 'A', 'C'}; System.out.println(Stream.of(chars).skip(2) .max(Character::compareTo) + " " + Stream.of(chars).skip(2) .min(Character::compareTo)); a. C C b. A A c. A C d. C A Key:d See Listing 30.1. # 17. What is the output of the following code? Character[] chars = {'D', 'B', 'A', 'C'}; Stream.of(chars).map(e -> e.toLowerCase()).forEach(System.out::print); a. D B A C b. d b a c c. DBAC d. dbac Key:d See Listing 30.1. # 17. What is the output of the following code? System.out.println(Stream.of(new Loan(2.5, 1, 10.0), ..


new Loan(7.5, 5, 10.1), new Loan(7.5, 3, 10.2), new Loan(7.5, 3, 10.3)) .max((e1, e2) -> e1.getNumberOfYears() - e2.getNumberOfYears()) .get().getLoanAmount()); a. 10.0 b. 10.1 c. 10.2 d. 10.3 Key:b See Listing 30.1. # Section 30.3 IntStream, LongStream, and DoubleStream 18. is a subtype of BaseStream. a. Stream b. IntStream c. LongStream d. DoubleStream Key:abcd See the first paragraph. # 19. represents a sequence of a. IntStream, int b. LongStream, long c. DoubleStream, double d. FloatStream, float Key:abc See the first paragraph. # 20. sum() is a method defined in a. Stream b. IntStream c. LongStream d. DoubleStream Key:bcd See the first paragraph.

values.

.

# 21. What is the output of the following code? Character[] chars = {'D', 'B', 'A', 'C'}; System.out.println(Stream.of(chars).mapToInt(e -> e - 'A').sum()); a. 4 b. 5 c. 6 d. 7 Key:c See Listing 30.2. # 22. What is the output of the following code? double[] numbers = {1.2, 1, 2.2, 3.6}; System.out.println(DoubleStream.of(numbers) .mapToInt(e -> (int)e).sum()); a. 4 b. 5 ..


c. 6 d. 7 Key:d See Listing 30.2. # 23. What is the output of the following code? double[] numbers = {1.2, 1.23, 2.2, 3.6}; System.out.println(DoubleStream.of(numbers) .mapToObj(e -> e + "").mapToInt(e -> e.length()).sum()); a. 12 b. 13 c. 14 d. 15 Key:b See Listing 30.2. # Section 30.4 Parallel Streams 24. To create a parallel stream from a Collection object c, use a. c.stream() b. c.parallelStream() c. c.stream().parallel() d. c.stream().sequential() Key:bc See the first paragraph. # 25. The following statement displays IntStream.of(1, 2, 3, 4, 5).parallel() .forEach(e -> System.out.print(e + " ")); a. 1 2 3 4 5 b. 5 4 3 2 1 c. 1 2 3 5 4 d. 1 2 3 4 5 in a random order Key:d See Listing 30.3. # 26. is a stateless method. a. sorted b. filter c. limit d. map e. distinct Key:bcd See the second paragraph. # 27. is a stateful method. a. sorted b. filter c. limit d. map e. distinct Key:ae See Listing 30.3. ..

.

.


# Section 30.5 Stream Reduction Using the reduce method 28. The following statement displays . System.out.println(IntStream.of(1, 2, 3, 4, 5).parallel() .reduce(0, (e1, e2) -> e1 + e2)); a. 14 b. 15 c. 16 d. 17 e. 18 Key:b See the third paragraph. # 29. The following statement displays

.

System.out.println(IntStream.of(1, 2, 3, 4, 5).parallel() .reduce(1, (e1, e2) -> e1 * e2)); a. 120 b. 140 c. 130 d. 150 e. 170 Key:a See the third paragraph. # 30. The following statement displays

.

System.out.println(IntStream.of(1, 2, 3, 4, 5).parallel() .reduce(Integer.MAX_VALUE, (e1, e2) -> Math.min(e1, e2))); a. 1 b. 2 c. 3 d. 4 e. 5 Key:a See Listing 30.4. # 31. The following statement displays

.

System.out.println(IntStream.of(1, 2, 3, 4, 5) .mapToObj(e -> e + "").reduce((e1, e2) -> e1 + " " + e2).get()); a. nothing b. 1 c. 2 d. 3 e. 1 2 3 4 5 Key:e See Listing 30.4. # 32. The following statement displays System.out.println(IntStream.of(1, 2, 3, 4, 5) ..

.


.mapToObj(e -> e + "").reduce((e1, e2) -> e1 + " " + e2).get()); a. nothing b. 1 c. 2 d. 3 e. 1 2 3 4 5 Key:e See Listing 30.4. # 34. Show the output of the following code: import java.util.stream.IntStream; import java.util.stream.Stream; public class Test { public static void main(String [] args){ int[][] m = {{1, 2, 3}, {3, 4, 5}, {5, 2}, {1, 3}}; Stream.of(m).map(e -> IntStream.of(e)) .reduce((e1, e2) -> IntStream.concat(e1, e2)) .get().distinct() .forEach(e -> System.out.print(e + " ")); } } a. 1 2 3 3 4 5 5 2 1 2 b. 1 2 3 4 5 c. 1 2 3 4 5 in a random order d. 5 4 3 2 1 Key:b See Listing 30.4. # 35. Show the output of the following code: import java.util.stream.IntStream; import java.util.stream.Stream; public class Test { public static void main(String [] args){ int[][] m = {{1, 2, 3}, {3, 4, 5}, {5, 2}, {1, 3}}; System.out.println( Stream.of(m).map(e -> IntStream.of(e)) .reduce((e1, e2) -> IntStream.concat(e1, e2)) .get().distinct().mapToObj(e -> e + "") .reduce((e1, e2) -> e1 + ", " + e2).get()); } } a. 1, 2, 3, 3, 4, 5, 5, 2, 1, 2 b. 1, 2, 3, 3, 4, 5, 5, 2, 1, 2, c. 1, 2, 3, 4, 5, d. 1, 2, 3, 4, 5 Key:d See Listing 30.4. # Section 30.6 Stream Reduction Using the collect Method 36. The following statement displays . ..


System.out.println(IntStream.of(1, 2, 3, 4, 5) .collect(() -> new ArrayList(), (c, e) -> c.add(e), (c1, c2) -> c1.addAll(c2))); a. [1, 2, 3, 4] b. [1] c. [1, 2] d. [1, 2, 3] e. [1, 2, 3, 4, 5] Key:e See Listing 30.5. # 37. The following statement displays

.

System.out.println(IntStream.of(2, 5, 5, 4, 5) .collect(() -> new TreeSet(), (c, e) -> c.add(e), (c1, c2) -> c1.addAll(c2))); a. [2, 4, 5, 5] b. [2, 5, 4] c. [2, 5, 5, 4, 5] d. [5, 2, 4] e. [2, 4, 5] Key:e See Listing 30.5. # 37. The following statement displays

.

System.out.println(IntStream.of(2, 5, 5, 4, 5) .mapToObj(e -> e).collect(Collectors.toList())); a. [2, 4, 5, 5] b. [2, 5, 4] c. [2, 5, 5, 4, 5] d. [5, 2, 4] e. [2, 4, 5] Key:c See Listing 30.5. # 38. The following statement displays

.

IntStream.of(2, 5, 5, 4, 5) .mapToObj(e -> e).collect(Collectors.toSet()) .stream().sorted().forEach(e -> System.out.print(e + " ")); a. 2 4 5 5 b. 2 5 4 c. 2 5 5 4 5 d. 5 2 4 e. 2 4 5 Key:e See Listing 30.5. # Section 30.7 Grouping Elements Using the groupingby Collector 39. The following statement displays . IntStream.of(1, 2, 3, 4, 1, 3, 5, 4, 4).mapToObj(e -> e).collect( ..


Collectors.groupingBy(e -> e, Collectors.counting())) .forEach((k, v) -> {if (k == 3) System.out.println(k + " " + v);}); a. 3 1 b. 3 2 c. 3 3 d. 2 3 e. 2 1 Key:b See Listing 30.6. # 42. The following statement displays

.

IntStream.of(1, 2, 2, 1, 1).mapToObj(e -> e).collect( Collectors.groupingBy(e -> e, TreeMap::new, Collectors.counting())) .forEach((k, v) -> {System.out.print(k + " " + v + " ");}); a. 1 3 2 3 b. 1 3 2 1 c. 1 3 2 2 d. 2 3 1 3 e. 2 2 1 3 Key:c See Listing 30.6. # 42. The following statement displays

.

Map<Double, Double> map = Stream.of(new Loan(2.5, 1, 10.0), new Loan(7.5, 5, 10.1), new Loan(7.5, 3, 10.2), new Loan(7.5, 5, 10.3)) .collect(Collectors.groupingBy(Loan::getAnnualInterestRate, TreeMap::new, Collectors.summingDouble(Loan::getLoanAmount))); map.forEach((k, v) -> System.out.print(k + " " + v + " "));a. 1 3 2 3 a. 7.5 10.0 2.5 30.6 b. 7.5 30.6 2.5 10.0 c. 2.5 7.5 2.5 30.6 d. 2.5 10.0 7.5 30.6 Key:d See Listing 30.6. # 30. Show the output of the following code. String s = "good"; Stream.of(s).forEach(e -> System.out.print(e + " ")); a. g o o d b. good c. a random object reference d. [g, o, o, d] Key:b See Listing 30.6. # 44. Show the output of the following code. String s = "good"; ..


Stream.of(s.toCharArray()).forEach(e -> System.out.print(e + " ")); a. g o o d b. good c. a random object reference d. [g, o, o, d] Key:c See Listing 30.6. # 45. Show the output of the following code. import java.util.stream.Stream; public class Test { public static void main(String[] args) { String s = "good"; Stream.of(toCharacterArray(s.toCharArray())).forEach(e -> System.out.print(e + " ")); } public static Character[] toCharacterArray(char[] list) { Character[] result = new Character[list.length]; for (int i = 0; i < result.length; i++) { result[i] = list[i]; } return result; } } a. g o o d b. good c. a random object reference d. [g, o, o, d] Key:a See Listing 30.6. # 40. is a terminal method. a. reduce b. collect c. forEach d. map e. mapToInt Key:abc See Listing 30.6. # 41. The forEach method is defined in the a. Stream b. IntStream c. LongStream d. DoubleStream e. Collection Key:abcde See Listing 30.6.

..

interface.


Chapter 31 Advanced JavaFX Section 31.2 JavaFX CSS 1. A JavaFX style property is defined with a prefix a. -fxb. fxc. -fx d. fx Key:a

.

# 2. defines a style class. a. .plaincircle {-fx-fill: white; -fx-stroke: black;} b. #plaincircle {-fx-fill: white; -fx-stroke: black;} c. plaincircle {-fx-fill: white; -fx-stroke: black;} d. +plaincircle {-fx-fill: white; -fx-stroke: black;} Key:a # 3. defines a style id. a. .plaincircle {-fx-fill: white; -fx-stroke: black;} b. #plaincircle {-fx-fill: white; -fx-stroke: black;} c. plaincircle {-fx-fill: white; -fx-stroke: black;} d. +plaincircle {-fx-fill: white; -fx-stroke: black;} Key:b # 4. Which of the following statements are true? a. Multiple style sheets can be loaded to a Scene or a Parent. b. Multiple style classes can be applied to a single node. c. A style id can be applied to a unique node. d. A style class and a style id can both be applied to a node. e. If the same property is defined in both a style class and a style id and applied to a node, the one defined in the style id takes precedence. Key:abcde # 5. The method loads a style sheet named style.css for a node or a scene. a. node.setStyleSheet("style.css"); b. node.getStyleSheets.setStyleSheet("style.css"); c. node.getStylesheets.add("style.css"); d. node.setStylesheets("style.css"); Key:c # 6. The method sets a style class is named plaincircle for a node or a scene. a. node.setStyleClass("plaincircle"); b. node.getStyleSheets.setStyleClass("plaincircle"); c. node.getStylesheets.addClass("plaincircle"); d. node.setStyle("plaincircle"); Key:a # ..


7. The method sets a style id named greencircle for a node or a scene. a. node.setStyleId("greencircle"); b. node.setId("greencircle"); c. node.getStylesheets.addId("greencircle"); d. node.setStyle("greencircle"); Key:b # 8. The getStylesheets() method is defined in a. Scene b. Node c. Parent d. Pane e. Control Key:ac # Section 31.3 QuadCurve, CubicCurve, and Path 9. The QuadCurve class contains the a. startX, startY b. endX, endY c. controlX, controlY d. x, y Key:abc

.

properties.

# 10. To construct a QuadCurve with starting point (100, 75.5), control point (40, 55.5), and end point (56, 80), use . a. new QuadCurve(100, 75.5, 40, 55.5, 56, 80) b. new QuadCurve(100, 75.5, 56, 80, 40, 55.5) c. new QuadCurve(40, 55.5, 100, 75.5, 56, 80) d. QuadCurve.build().startX(100).startY(75.5).controlX(40).controlY(55.5).endX(56).endY(80).create() Key:ad # 11. The CubicCurve class contains the a. startX, startY b. endX, endY c. controlX1, controlY1 d. controlX2, controlY2 e. x, y Key:abcd

properties.

# 12. The method moves the Path position to (100, 100). a. path.moveTo(100, 100) b. path.getElements().add(new MoveTo(100, 100)) c. path.add(new MoveTo(100, 100)) d. path.getElements().move(100, 100) Key:b # 13. You can draw a segment in the path using a. path.addElements().add(new MoveTo(100, 100)); ..

.


b. path.addElements().add(new HLineTo(100)); c. path.addElements().add(new VLineTo(100)); d. path.addElements().add(new LineTo(100, 300)); Key:abcd # Section 31.4 Coordinate Transformations 14. The translateX, translateY, translateZ, rotate, scaleX, scaleY, scaleZ properties are defined in a. Scene b. Parent c. Stage d. Node Key:d # 15. Assume Rectangle rectangle = new Rectangle(10, 10, 50, 60), what is rectangle.getX() after rectangle.setTranslateX(10)? a. 10 b. 0 c. 20 d. -10 Key:a # 16. Assume Rectangle rectangle = new Rectangle(10, 10, 50, 60), what is rectangle.getX() after rectangle.setRotate(10)? a. 10 b. 0 c. 20 d. -10 Key:a # 17. Assume Rectangle rectangle = new Rectangle(10, 10, 50, 60), what is rectangle.getWidth() after rectangle.setScaleX(2)? a. 100 b. 50 c. 200 d. 10 Key:b # Section 31.5 Strokes 18. The stroke property is defined in a. Scene b. Parent c. Stage d. Node e. Shape Key:e # 19. The a. stroke ..

property is defined in Shape.

.

.


b. strokeWidth c. strokeType d. strokeLineCap e. strokeLineJoin Key:abcde # 20. is a valid stroke type. a. StrokeType.INSIDE b. StrokeType.CENTER c. StrokeType.OUTSIDE d. StrokeType.LEFT e. StrokeType.RIGHT Key:abc # 21. is a valid stroke cap type. a. StrokeLineCap.BUTT b. StrokeLineCap.ROUND c. StrokeLineCap.SQUARE d. StrokeLineCap.ELLIPSE e. StrokeLineCap.CIRCLE Key:abc # 22. is a valid stroke line join. a. StrokeLineJOIN.MITER b. StrokeLineJOIN.BEVEL c. StrokeLineJOIN.ROUND d. StrokeLineJOIN.SQUARE e. StrokeLineJOIN.CENTER Key:abc # 14. strokeDashArray is an instance of a. List<Double> b. List<double> c. ObservableList<Double> d. ObservableList<double> Key:d # Section 31.6 Menus 14. To create a menu bar, use a. new MenuBar() b. new Menu() c. new MenuItem() d. new CheckMenuItem() e. new RadioMenuItem() Key:a # 14. To create a menu, use a. new MenuBar() ..

.

.

.


b. new Menu() c. new MenuItem() d. new CheckMenuItem() e. new RadioMenuItem() Key:b # 14. To create a menu item, use a. new MenuBar() b. new Menu() c. new MenuItem() d. new CheckMenuItem() e. new RadioMenuItem() Key:c

.

# 14. To create a check menu item, use a. new MenuBar() b. new Menu() c. new MenuItem() d. new CheckMenuItem() e. new RadioMenuItem() Key:d # 14. To create a radio menu item, use a. new MenuBar() b. new Menu() c. new MenuItem() d. new CheckMenuItem() e. new RadioMenuItem() Key:e

.

.

# 14. You can set a graphic such as an ImageView in a a. MenuBar b. Menu c. MenuItem d. CheckMenuItem e. RadioMenuItem Key:bcde # 14. To add a menu to a menu bar, use a. menuBar.add(menu) b. menuBar.addAll(menu) c. menuBar.getMenus().add(menu) d. menuBar.getItems().add(menu) Key:c # 14. To add a menu item to a menu, use a. menu.add(menuItem) b. menu.addAll(menuItem) ..

.

.

.


c. menu.getItems().add(menuItem) d. menu.getMenus().add(menuItem) Key:c # Section 31.7 Context Menus 14. To add a menu item to a context menu, use a. contextMenu.add(menuItem) b. contextMenu.addAll(menuItem) c. contextMenu.getItems().add(menuItem) d. contextMenu.getMenus().add(menuItem) Key:c # 14. To display a context menu, use a. contextMenu.show() b. contextMenu.show(node) c. contextMenu.show(node, x, y) d. contextMenu.show(x, y) Key:c

.

# Section 31.8 SplitPane 14. To add a node to a split pane, use a. splitPane.add(node) b. splitPane.getChildren().add(node) c. splitPane.getItems().add(node) d. splitPane.getChildren().addItem(node) Key:c # Section 31.9 TabPane 14. The possible value of a tab side is a. Side.TOP b. Side.BOTTOM c. Side.LEFT d. Side.RIGHT Key:abcd # 14. The a. id b. text c. tooltip d. graphic e. content Key:abcde

.

.

properties are defined in the Tab class.

# 14. To add a node to a tab, use a. tab.getItems().add(node) b. tab.getChildren().add(node) c. tab.setContent(node) d. tab.add(node) ..

.

.


Key:c # 14. To add tabs to a tab pane, use a. tabPane.getItems().addAll(tab1, tab2) b. tabPane.getTabs().addAll(tab1, tab2) c. tabPane.getChildren().addAll(tab1, tab2) d. tab.addAll(tab1, tab2) Key:b

.

# Section 31.10 TableView 14. The properties are defined in the TableView class. a. editable b. items c. placeholder d. selectionModel Key:abcd # 14. The a. editable b. graphic c. id d. resizable e. text Key:abcde

properties are defined in the TableColumn class.

# 14. To add a table column to a table view, use a. tableView.add(tableColumn) b. tableView.getItems().add(tableColumn) c. tableView.getChildren().add(tableColumn) d. tableView.getColumns().add(tableColumn) Key:d

..

.


Chapter 32 Multithreading and Parallel Programming Section 32.3 Creating Tasks and Threads 1. Analyze the following code: public class Test implements Runnable { public static void main(String[] args) { Thread t = new Thread(this); t.start(); } public void run() { System.out.println("test"); } } a. The program does not compile because this cannot be referenced in a static method. b. The program compiles fine, but it does not print anything because t does not invoke the run() method. c. The program compiles and runs fine and displays test on the console. d. None of the above. Key:a # 2.

What is the output of the following code?

// Test.java: Define threads using the Thread class public class Test { /** Main method */ public static void main(String[] args) { new Test(); } public Test() { // Create threads PrintChar printA = new PrintChar('a', 4); PrintChar printB = new PrintChar('b', 4); // Start threads printA.run(); printB.run(); } class PrintChar implements Runnable { private char charToPrint; // The character to print private int times; // The times to repeat /** Construct a thread with specified character and number of times to print the character */ public PrintChar(char c, int t) { charToPrint = c; times = t; } ..


/** Override the run() method to tell the system what the thread will do */ public void run() { for (int i = 0; i < times; i++) System.out.print(charToPrint); } } } a. aaaaabbbbb b. bbbbbaaaaa c. character a and b are randomly printed d. ababababab Key:a Note that the run() in the thread is directly invoked. The threads printA and printB are not started. Threads printA and printB are actually running from the same main thread sequentially. # 3.

Analyze the following code:

public abstract class Test implements Runnable { public void doSomething() { }; } a. The program will not compile because it does not implement the run() method. b. The program will not compile because it does not contain abstract methods. c. The program compiles fine. d. None of the above. Key:c (a) is wrong because class Test is abstract, (b) is wrong because an abstract class may contain no abstract method. (c) is correct. # 4.

Analyze the following code:

public class Test implements Runnable { public static void main(String[] args) { Test t = new Test(); t.start(); } public void run() { } } a. The program does not compile because the start() method is not defined in the Test class. b. The program compiles, but it does not run because the start() method is not defined. c. The program compiles, but it does not run because the run() method is not implemented. d. The program compiles and runs fine. Key:a # 5.

Analyze the following code:

public class Test implements Runnable { public static void main(String[] args) { Test t = new Test(); ..


} public Test() { Thread t = new Thread(this); t.start(); } public void run() { System.out.println("test"); } } a. The program has a compilation error because t is defined in both the main() method and the constructor Test(). b. The program compiles fine, but it does not run because you cannot use the keyword this in the constructor. c. The program compiles and runs and displays nothing. d. The program compiles and runs and displays test. Key:d # Section 32.4 The Thread Class 6. Why does the following class have a syntax error? import java.applet.*; public class Test extends Applet implements Runnable { public void init() throws InterruptedException { Thread t = new Thread(this); t.sleep(1000); } public synchronized void run() { } } a. The sleep() method is not invoked correctly; it should be invoked as Thread.sleep(1000). b. You cannot put the keyword synchronized in the run() method. c. The init() method is defined in the Applet class, and it is overridden incorrectly because it cannot claim exceptions in the subclass. d. The sleep() method should be put in the try-catch block. This is the only reason for the compilation failure. Key:c # 7. Which of the following expressions must be true if you create a thread using Thread = new Thread(object)? a. object instanceof Thread b. object instanceof Frame c. object instanceof Applet d. object instanceof Runnable Key:d # 8. Which of the following methods in the Thread class are deprecated? a. yield() b. stop(); c. resume(); d. suspend(); Key:bcd ..


# 9. You can use the a. sleep(long milliseconds) b. yield() c. stop() d. suspend() Key:ab

method to temporarily release time for other threads.

# 10. Which of the following statements are defined in the Object class? a. sleep(long milliseconds) b. wait() c. notify() d. notifyAll() e. toString() Key:bcde # 11. You can use the a. sleep(long milliseconds) b. yield() c. stop() d. suspend() e. join() Key:e # 12.

method to force one thread to wait for another thread to finish.

When you run the following program, what will happen?

public class Test extends Thread { public static void main(String[] args) { Test t = new Test(); t.start(); t.start(); } public void run() { System.out.println("test"); } } a. Nothing is displayed. b. The program displays test twice. c. The program displays test once. d. An illegal java.lang.IllegalThreadStateException may be thrown because you just started thread and thread might have not yet finished before you start it again. Key:d # 13. a. b. c. d. ..

Which of the following method is a static in java.lang.Thread? run() sleep(long) start() join()


e. setPriority(int) Key:b # 14. Which of the following methods in Thread throws InterruptedException? a. run() b. sleep(long) c. start() d. yield() e. setPriority(int) Key:b # 15. Given the following code, which set of code can be used to replace the comment so that the program displays time to the console every second? import java.applet.*; import java.util.*; public class Test extends Applet implements Runnable { public void init() { Thread t = new Thread(this); t.start(); } public void run() { for(; ;) { //display time every second System.out.println(new Date().toString()); } } } a. try { sleep(1000); } catch(InterruptedException e) { } b. try { t.sleep(1000); } catch(InterruptedException e) { } c. try { Thread.sleep(1000); } catch(RuntimeException e) { } d. try { Thread.sleep(1000); } catch(InterruptedException e) { } Key:d t is defined in the init() method, which cannot be accessed in the run() method. So, b is incorrect. # Section 32.5 Case Study: Flashing Text 16. Which of the following statements are true? a. You can use a timer or a thread to control animation. b. A timer is a source component that fires an ActionEvent at a 'fixed rate.' c. The timer and event-handling run on the same event dispatcher thread. If it takes a long time to handle the event, the actual delay time between two events will be longer than the requested delay time. d. In general, threads are more reliable and responsive than timers. Key:abcd # Section 32.6 GUI Event Dispatcher Thread 17. Which of the following statements are true? a. The javax.swing.SwingUtilities.invokeLater method creates a thread. b. The javax.swing.SwingUtilities.invokeAndWait method runs the code in the event dispatcher thread. c. The javax.swing.SwingUtilities.invokeLater method runs the code in the event dispatcher thread and doesn't return ..


until the event-dispatching thread has executed the specified code. d. GUI event handling is executed in the event dispatcher thread. Key:bcd invokeLater and invokeAndWait methods do not create a thread. These methods run the code in the event dispatcher thread. # Section 32.8 Thread Pools 18. Suppose there are three Runnable tasks, task1, task2, task3. How do you run them in a thread pool with 2 fixed threads? a. new Thread(task1).start(); new Thread(task2).start(); new Thread(task3).start(); b. ExecutorService executor = Executors.newFixedThreadPool(3); executor.execute(task1); executor.execute(task2); executor.execute(task3); c. ExecutorService executor = Executors.newFixedThreadPool(2); executor.execute(task1); executor.execute(task2); executor.execute(task3); d. ExecutorService executor = Executors.newFixedThreadPool(1); executor.execute(task1); executor.execute(task2); executor.execute(task3); Key:c # 19. How do you create a cached thread pool? a. ExecutorService executor = Executors.newCachedThreadPool(); b. ExecutorService executor = Executors.newCachedThreadPool(1); c. ExecutorService executor = Executors.newCachedThreadPool(2); d. ExecutorService executor = Executors.newCachedThreadPool(3); Key:a # Section 32.9 Thread Synchronization 20. The keyword to synchronize methods in Java is a. synchronize b. synchronizing c. synchronized d. Synchronized Key:c

.

# 21. Which of the following statements are true? a. A synchronized instance method acquires a lock on the object for which the method was invoked. b. A synchronized instance method acquires a lock on the class of the object for which the method was invoked. c. A synchronized statement can be used to acquire a lock on any object, not just this object, when executing a block of the code in a method. d. A synchronized statement is placed inside a synchronized block. Key:abcd # Section 32.10 Synchronization Using Locks 22. Which of the following are correct statements to create a Lock? a. Lock lock = new Lock(); b. Lock lock = new ReentrantLock(); c. Lock lock = new ReentrantLock(true); d. Lock lock = new ReentrantLock(false); Key:bcd # ..


23. Which of the following are correct statements to create a Lock so the longest-wait thread will obtain the lock first? a. Lock lock = new Lock(); b. Lock lock = new ReentrantLock(); c. Lock lock = new ReentrantLock(true); d. Lock lock = new ReentrantLock(false); Key:c # 24. You should always invoke the unlock method in the finally clause. a. true b. false Key:a To ensure that the lock will eventually be released. # Section 32.11 Cooperation Among Threads 25. How do you create a condition on a lock? a. Condition condition = lock.getCondition(); b. Condition condition = lock.newCondition(); c. Condition condition = Lock.newCondition(); d. Condition condition = Lock.getCondition(); Key:b # 26. Which method on a condition should you invoke to causes the current thread to wait until the condition is signaled? a. condition.await(); b. condition.wait(); c. condition.waiting(); d. condition.waited(); Key:a # 27. Which method on a condition should you invoke to wake all waiting threads? a. condition.wake(); b. condition.signal(); c. condition.wakeAll(); d. condition.signalAll(); Key:d # 28. Which of the following statements are true? a. A condition is associated with a lock. b. To invoke methods on a condition, the lock must be obtained first. c. Once you invoke the await method on a condition, the lock is automatically released. Once the condition is right, the thread re-acquires the lock and continues executing. d. The signal method on a condition causes the lock for the condition to be released. Key:abc # 29. Which of the following statements are true? a. The wait(), notify(), and notifyAll() methods must be invoked from a synchronized method or a synchronized block. b. When wait() is invoked, it pauses the thread and releases the lock on the object simultaneously. When the thread ..


is restarted after being notified, the lock is automatically reacquired. c. The notify() method can wake only one waiting thread. d. An exception would occur if no thread is waiting on the object when the notify() method is invoked on the object. Key:d # 30.

Analyze the following code.

// Test.java: Define threads using the Thread class import java.util.*; public class Test { private Stack stack = new Stack(); private int i = 0; /** Main method */ public static void main(String[] args) { new Test(); } public Test() { // Start threads new Producer().start(); new Consumer().start(); } class Producer extends Thread { public void run() { while (true) { System.out.println("Producer: put " + i); stack.push(new Integer(i++)); synchronized (stack) { notifyAll(); } } } } class Consumer extends Thread { public void run() { while (true) { synchronized (stack) { try { while (stack.isEmpty()) stack.wait(); System.out.println("Consumer: get " + stack.pop()); } catch (InterruptedException ex) { ex.printStackTrace(); } } } } } ..


} a. The program creates two threads: one to add data to the stack and the other to get data from the stack. b. The program has a compilation error on the notifyAll() method in the Producer class because it is not invoked from the stack object. c. The program will throw an exception because the notifyAll() method in the Producer class is not invoked from the stack object. d. The program has a logic error because the lock obtained by the synchronized block for notifyAll in the Producer class is stack and it should be this (i.e., synchronized (this) { notifyAll(); }). Key:c notifyAll() should be invoked from stack because stack is the object the Consumer thread is waiting on. # Section 32.13 Blocking Queues 31. You can create a blocking queue using a. ArrayBlockingQueue b. LinkedBlockingQueue c. PriorityBlockingQueue d. PriorityQueue Key:abc

.

# 32. Which of the following statements are true? a. a blocking queue has a capacity. b. A blocking queue causes a thread to block when you try to add an element to a full queue. c. A blocking queue causes a thread to block when you try to remove an element from an empty queue. d. The BlockingQueue interface is the base interface for all concrete blocking queue classes. e. The BlockingQueue interface provides the synchronized put and take methods for adding an element to the head of the queue and for removing an element from the tail of the queue, Key:abcde # Section 32.14 Semaphores 33. Which of the following statements are true? a. Semaphores can be used to restrict the number of threads that access a shared resource. b. Before accessing the resource, a thread must acquire a permit from the semaphore. c. After finishing with the resource, the thread must return the permit back to the semaphore. d. You can create a Semaphore with a specified number of permits. Key:abcd # 34. Which of the following methods can be used to obtain a permit from a Semaphore s? a. get() b. ask() c. acquire() d. delete() Key:c # 35. Which of the following methods can be used to return a permit to a Semaphore s? a. return() b. release() c. send() d. add() Key:c

..


Chapter 33 Networking Section 33.2 Client/Server Computing 1. When creating a server on a port that is already in use, a. java.net.BindException occurs b. the server is created with no problems c. the server is blocked until the port is available d. the server encounters a fatal error and must be terminated Key:a

.

# 2. When creating a client on a server port that is already in use, . a. the client can connect to the server regardless of whether the port is in use b. java.net.BindException occurs c. the client is blocked until the port is available d. the client encounters a fatal error and must be terminated Key:a To connect to a client, the server creates a client socket from the ServerSocket. You can create any number of client sockets on the server side to connect to a client on the Internet. # 3. The server listens for a connection request from a client using the following statement: a. Socket s = new Socket(ServerName, port); b. Socket s = serverSocket.accept() c. Socket s = serverSocket.getSocket() d. Socket s = new Socket(ServerName); Key:b # 4. The client requests a connection to a server using the following statement: a. Socket s = new Socket(ServerName, port); b. Socket s = serverSocket.accept(); c. Socket s = serverSocket.getSocket(); d. Socket s = new Socket(ServerName); Key:a # 5. When a client requests connection to a server that has not yet started, a. java.net.BindException occurs b. java.net.ConnectionException occurs c. the client is blocked until the server is started d. the client encounters a fatal error and must be terminated Key:b

.

# 6. To connect to a server running on the same machine with the client, which of the following can be used for the hostname? a. "localhost" b. "127.0.0.1" c. InetAddress.getLocalHost(), d. "127.127.127.1". Key:abc # ..


7. To create an InputStream on a socket s, you use a. InputStream in = new InputStream(s); b. InputStream in = s.getInputStream(); c. InputStream in = s.obtainInputStream(); d. InputStream in = s.getStream(); Key:b

.

# Section 33.3 The InetAddress Class 8. models an IP address, which can be used to find the host name and IP address of the client. a. The ServerSocket class b. The Socket class c. The InetAddress class d. The Connection interface Key:c # 9. You can invoke a. socket.InetAddress(); b. socket.getInetAddress(); c. socket.obtainInetAddress(); d. socket.retrieveInetAddress(); Key:b # 10. The a. getIP() b. getIPAddress() c. getHostAddress() d. getAddress() Key:c

on a Socket object, say socket, to obtain an InetAddress object.

method in the InetAddress class returns the IP address.

# Section 33.4 Serving Multiple Clients 11. A ServerSocket can connect to a. one b. two c. ten d. an unlimited number of Key:d

clients.

# Section 33.5 Applet Clients 12. You can obtain the server's hostname by invoking a. getCodeBase().host() b. getCodeBase().getHost() c. getCodeBase().hostName() d. getCodeBase().getHostName() Key:b # Section 33.6 Sending and Receiving Objects 13. To obtain an ObjectInputStream from a socket, use a. socket.getInputStream() ..

on an applet.

.


b. socket.getObjectStream() c. socket.getObjectInputStream() d. socket.objectInputStream() e. new ObjectInputStream(socket.getInputStream()); Key:e # 14. To obtain an ObjectOutputStream from a socket, use a. socket.getOutputStream() b. socket.getObjectStream() c. socket.getObjectOutputStream() d. socket.objectOutputStream() e. new ObjectOutputStream(socket.getOutputStream()) Key:e

..

.


Chapter 34 Java Database Programming Section 34.2 Relational Database Systems 1. In a relational data model, defines the representation of the data. a. Structure b. Integrity c. Language d. SQL Key:a # 2. In a relational data model, a. Structure b. Integrity c. Language d. SQL Key:b # 3. In a relational data model, a. Structure b. Integrity c. Language d. SQL Key:cd

imposes constraints on the data.

provides the means for accessing and manipulating data.

# 4. specify the permissible values for an attribute. a. Domain constraints b. Primary key constraints c. Foreign key constraints d. intra-relational constraints e. inter-relational constraints Key:a # 5. are known as intra-relational constraints, meaning that a constraint involves only one relation. a. Domain constraints b. Primary key constraints c. Foreign key constraints Key:ab # 6. is an attribute or a set of attributes that uniquely identifies the relation. a. A superkey b. A key c. A candidate key d. A primary key Key:a # Section 34.3 SQL 7. SQL statements may change the contents of a database. ..


a. SELECT b. UPDATE c. DELETE d. INSERT Key:bcd # 8. To retrieve all courses with more than 3 credit hours, you write select * from Course where numOfCredits > 3; Is this statement correct? a. Yes b. No Key:a # Section 34.4 JDBC 9. Which of the following statements loads the JDBC-ODBC driver? a. Class.forName(sun.jdbc.odbc.JdbcOdbcDriver) b. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") c. Class.loadClass(sun.jdbc.odbc.JdbcOdbcDriver) d. Class.loadClass("sun.jdbc.odbc.JdbcOdbcDriver") Key:b # 10. Where is com.mysql.jdbc.Driver located? a. in the standard Java library bundled with JDK b. in a JAR file mysqljdbc.jar downloadable from the book's Companion Website c. in a JAR file classes12.jar downloadable from the book's Companion Website d. in a JAR file ojdbc14.jar downloadable from the book's Companion Website Key:b # 11. Invoking Class.forName method may throw a. RuntimeException b. ClassNotFoundException c. IOException d. SQLException Key:b # 12. A database URL for an access database source test is a. test b. jdbcodbc:test c. jdbc:odbc:test d. sun.jdbc:odbc:test Key:c

.

.

# 13. A database URL for a MySQL database named test on host panda.armstrong.edu is a. jdbc.mysql.//panda.armstrong.edu/test ..

.


b. jdbc:mysql:/panda.armstrong.edu/test c. jdbc:mysql://panda.armstrong.edu/test d. jdbc.mysql://panda.armstrong.edu/test Key:c # 14. To connect to a local MySQL database named test, use a. Connection connection = DriverManager.getConnection(jdbc:mysql://localhost/test); b. Connection connection = DriverManager.connect("jdbc:mysql://localhost/test"); c. Connection connection = DriverManager.getConnection("mysql:jdbc://localhost/test"); d. Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/test"); Key:d # 15. To create a statement on a Connection object conn, use a. Statement statement = conn.statement(); b. Statement statement = Connection.createStatement(); c. Statement statement = conn.createStatement(); d. Statement statement = connection.create(); Key:c # 16. To execute a SELECT statement "select * from Address" on a Statement object stmt, use a. stmt.execute("select * from Address"); b. stmt.executeQuery("select * from Address"); c. stmt.executeUpdate("select * from Address"); d. stmt.query("select * from Address"); Key:b # 17. Which of the following statements are true? a. You may load multiple JDBC drivers in a program. b. You may create multiple connections to a database. c. You may create multiple statements from one connection. d. You can send queries and update statements through a Statement object. Key:abcd # 18. Analyze the following code: ResultSet resultSet = statement.executeQuery ("select firstName, mi, lastName from Student where lastName " + " = 'Smith'"); System.out.println(resultSet.getString(1)); a. If the SQL SELECT statement returns no result, resultSet is null. b. The program will have a runtime error, because the cursor in resultSet does not point to a row. You must use resultSet.next() to move the cursor to the first row in the result set. Subsequently, resultSet.next() moves the cursor to the next row in the result set. c. resultSet.getString(1) returns the firstName field in the result set. d. resultSet.getString(1) returns the mi field in the result set. Key:bc # 19. Suppose that your program accesses MySQL or Oracle database. Which of the following statements are true? a. If the driver for MySQL and Oracle are not in the classpath, the program will have a syntax error. ..


b. If the driver for MySQL and Oracle are not in the classpath, the program will have a runtime error, indicating that the driver class cannot be loaded. c. If the database is not available, the program will have a syntax error. d. If the database is not available, the program will have a runtime error, when attempting to create a Connection object. Key:bd # 20. Which of the following are interfaces? a. Connection b. Statement c. ResultSet d. DriverManager Key:abc # 21.What is the return value from stmt.executeUpdate("insert into T values (100, 'Smith')") a. void b. an int value indicating how many rows are effected from the invocation c. a value indicating whether the SQL statement has been executed successfully d. an object that contains the status of the execution Key:b # Section 34.5 PreparedStatement 22. Which of the following statements are true? a. PreparedStatement is a subinterface of Statement b. PreparedStatement is for SQL query statements only. You cannot create a PreparedStatement for SQL update statements. c. PreparedStatement is efficient for repeated executions. d. The parameters in a prepared statement are denoted using the ? sign. Key:acd # 23. Suppose a prepared statement is created as follows: Statement preparedStatement = connection.prepareStatement ("insert into Student (firstName, mi, lastName) " + "values (?, ?, ?)"); To set a value John to the first parameter, use a. preparedStatement.setString(0, "John"); b. preparedStatement.setString(1, "John"); c. preparedStatement.setString(0, 'John'); d. preparedStatement.setString(1, 'John'); Key:b # 24. If a prepared statement preparedStatement is a SQL SELECT statement, you execute the statement using . a. preparedStatement.execute(); ..


b. preparedStatement.executeUpdate(); c. preparedStatement.executeQuery(); d. preparedStatement.query(); Key:c # Section 34.6 CallableStatement 25. Which of the following statements are true? a. CallableStatement is a subinterface of PreparedStatement b. CallableStatement is for SQL query statements only. You cannot create a CallableStatement for SQL update statements. c. CallableStatement is more efficient than PreparedStatement. d. CallableStatement is for executing predefined functions and procedures. Key:ad # 26. Suppose a callable statement is created as follows: CallableStatement callableStatement = connection.prepareCall( "{call sampleProcedure(?, ?, ?)}"); Assume that the first parameter is an IN parameter with value John. To set this parameter value, use a. callableStatement.setString(0, "John"); b. callableStatement.setString(1, "John"); c. callableStatement.setString(0, 'John'); d. callableStatement.setString(1, 'John'); Key:b # 27. Suppose a callable statement is created as follows: CallableStatement callableStatement = connection.prepareCall( "{call sampleProcedure(?, ?, ?)}"); Assume that the second parameter is an OUT parameter with value John. To register this parameter, use a. callableStatement.registerOutParameter(0, java.sql.Types.STRING); b. callableStatement.registerOutParameter(1, java.sql.Types.STRING); c. callableStatement.registerOutParameter(2, java.sql.Types.STRING); Key:c # Section 34.7 Retrieving Metadata 28. Database meta data are retrieved through . a. a Connection object b. a Statement object c. a ResultSet Object d. a PreparedStatement object Key:a getMetaData() on a Connection object returns a DatabaseMetaData object. # 29. What information may be obtained from a DatabaseMetaData object? a. database URL and product name ..


b. JDBC driver name and version c. maximum number of connections to the database d. maximum table name length and maximum number of columns in a table Key:abcd # 30. Result set meta data are retrieved through . a. a Connection object b. a Statement object c. a ResultSet Object d. a PreparedStatement object Key:c getMetaData() on a ResultSet object returns a DatabaseMetaData object. # 31. What information may be obtained from a ResultSetMetaData object? a. database URL and product name b. JDBC driver name and version c. number of columns in the result set d. number of rows in the result set Key:c

..


Chapter 35 Advanced Database Programming Section 35.3 Batch Processing 1. To add the SQL statement "insert into T values (100, 'Smith')" into the batch into a Statement stmt, use a. stmt.add("insert into T values (100, 'Smith')"); b. stmt.add('insert into T values (100, 'Smith')'); c. stmt.addBatch("insert into T values (100, 'Smith')"); d. stmt.addBatch('insert into T values (100, 'Smith')'); Key:c # 2. Invoking executeBatch() returns . a. an int value indicating how many SQL statements in the batch have been executed successfully. b. a ResultSet c. an array of counts, each of which counts the number of the rows affected by the SQL command. d. an int value indicating how many rows are effected by the batch execution. Key:c # Section 35.4 Scrollable and Updateable Result Set 3. To obtain a scrollable or updateable result set, you must first create a statement using which of the following? a. Statement statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); b. Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); c. Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); d. Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); Key:c # 4. In a scrollable and updateable result set, you can use a. first() b. last() c. insertRow() d. deleteRow() e. updateRow() Key:abcde # Section 35.5 RowSet, JdbcRowSet, and CachedRowSet 5. RowSet is an extension of . a. Connection b. Statement c. ResultSet d. CLOB Key:c # 6. You can use a RowSet to a. set a database URL b. set a database username ..

.

methods on a result set.


c. set a database password d. set a SQL query statement Key:abcd # 7. You may create a RowSet using a. new RowSet() b. new JdbcRowSet() c. new CachedRowSet() d. new JdbcRowSetImpl() e. new CachedRowSetImpl() Key:de

.

# 8. To move the cursor to the 2nd row in a RowSet, use a. next(2) b. first() c. next() d. absolute(2) e. last() Key:d # 9. To update a String column in a RowSet, use a. updateString("newValue") b. updateString("columnName", "newValue") c. updateString("newValue", "columnName") d. updateObject("newValue", "columnName") Key:b # 10. To commit the changes in a CachedRowSet, use a. commint() b. acceptChanges() c. acceptUpdates() d. refresh() Key:b

.

.

.

# Section 35.6 RowSetTableModel 11. For a JTable to be synchronized with a JDBC RowSet, you may create a table model with the following features: a. The model should extend AbstractTableModel and implement getRowCount(), getColumnCount(), and getValueAt(int row, int column). b. The model should implement RowSetListener and the methods rowSetChanged(RowSetEvent e), rowChanged(RowSetEvent e), cursorMoved(RowSetEvent e). c. You should invoke fireTableStructureChanged() method from rowSetChanged(RowSetEvent e) and rowChanged(RowSetEvent e) to synchronize changes in the RowSet with the the JTable Key:abc # 12. The index of row and column in JTable is 0-based. The index of row and column in RowSet is 1-based. a. true b. false Key:a ..


# Section 35.7 Storing and Retrieving Images in JDBC 13. You can store images in a database using data type a. varchar2 b. varchar c. BLOB d. CLOB Key:c

.

# 14. You can store large text in a database using data type a. varchar2 b. varchar c. BLOB d. CLOB Key:d # 15. You can store large text in a database using data type a. varchar2 b. varchar c. BLOB d. CLOB Key:d # 16. To get binary data from a column, use a. getBlob() b. getBinaryStream() c. getBinaryData() d. getData() Key:a # 17. To set binary data to a column, use a. setBlob() b. setBinaryStream() c. setBinaryData() d. setData() Key:b

..

.

.

in Statement.

in Statement.


Chapter 36 Internationalization Section 36.2 The Locale Class 1. How do you set a button jbt's text to a character with the Unicode 13AE? a. jbt.setText("13AE"); b. jbt.setText("\13AE"); c. jbt.setText("\u13AE"); d. jbt.setText("/u13AE"); e. jbt.setText('\u13AE'); Key:c # 2. How do you create a locale for the United States? a. new Locale("en", "US"); b. new Locale("US", "en"); c. Locale.US; d. Locale.getLocale("en", "US") Key:ac # 3. Which of the following methods is defined in the Locale class? a. getLanguage() b. getCountry() c. getVariant() d. getCountryVariant() Key:abc # 4. Which of the following methods is correct to obtain the available locales in the classes Calendar, Collator, DateFormat, and NumberFormat? a. getLocales() b. getAllLocales() c. getAvailableLocales() d. availableLocales() Key:c # 5. Which of the following classes have the getAvailableLocales() method? a. Calendar b. Collator c. DateFormat d. NumberFormat Key:abcd # Section 36.3 Processing Date and Time 6. Which of the following set of code lines displays the current time in locale sensitive format? a. GregorianCalendar gcal = new GregorianCalendar(); System.out.println(gcal.toString()); b. Date d = new Date(); System.out.println(d.toString()); c. GregorianCalendar gcal = new  GregorianCalendar(new TimeZone("CST")); System.out.println(gcal.toString()); d. GregorianCalendar gcal = new GregorianCalendar(); DateFormat myFormat = DateFormat.getDateTimeInstance(); myFormat.setTimeZone(TimeZone.getTimeZone("CST")); System.out.println(myFormat.format(gcal.getTime())); ..


Key:d # 7. Which of the following code is correct to obtain hour from a Calendar object cal? a. cal.getHour(); b. cal.hour(); c. cal.get(Hour); d. cal.get(Calendar.HOUR); Key:d # 8. Which of the following code is correct to set a time zone in a Calendar object? a. cal.timeZone("CST"); b. cal.setTimeZone("CST"); c. cal.getTimeZone(); d. cal.get(Calendar.HOUR); Key:b # 9. Which of the following constants are the valid date and time format? a. DateFormat.SHORT b. DateFormat.MEDIUM c. DateFormat.LONG d. DateFormat.FULL Key:abcd # 10. Which of the following statements are true? a. SimpleDateFormat is a subclass of DateFormat. b. DateFormatSymbols is a subclass of SimpleDateFormat. c. SimpleDateFormat enables you to choose any user-defined pattern for date and time formatting. d. You can obtain localizable date-time formatting data, such as the names of the months, the names of the days of the week, and the time zone data, from an instance of DateFormatSymbols. Key:acd # 11. Suppose DateFormatSymbols symbols = new DateFormatSymbols(), Which of the following statements is correct to return month names? a. String[] monthNames = symbols.getMonths(); b. String[] weekdayNames = symbols.getWeekdays(); c. String[] eras = symbols.getEras(); d. String[] eras = symbols.getAmPmStrings(); Key:a # 12. Which of the following are in the java.text package? a. DateFormatSymbols b. DateFormat c. SimpleDateFormat d. Date e. Locale Key:abc # ..


Section 36.4 Formatting Numbers 13. Which of the following code is correct to create an instance for formatting numbers? a. NumberFormat.getInstance(); b. NumberFormat.getNumberInstance(locale); c. NumberFormat.getInstance(locale); d. NumberFormat.getNumberFormatInstance(locale); Key:abc # 14. Which of the following code is correct to create an instance for formatting numbers in currency? a. NumberFormat.getCurrencyInstance(locale); b. NumberFormat.getCurrencyInstance(); c. NumberFormat.currencyInstance(locale); d. NumberFormat.currencyInstance(); Key:ab # 15. Which of the following code is correct to create an instance for formatting numbers in percent? a. NumberFormat.getPercentInstance(locale); b. NumberFormat.getPercentInstance(); c. NumberFormat.percentInstance(locale); d. NumberFormat.percentInstance(); Key:ab # 16. Which of the following are valid methods in NumberFormat? a. format(double) b. format(long) c. setMaximumIntegerDigits(int) d. setMinimumIntegerDigits(int) Key:abcd # 17. Which of the following code displays the numbers with at least two digits before and after the decimal point? a. NumberFormat numberForm = NumberFormat.getNumberInstance(); DecimalFormat df = (DecimalFormat)numberForm;<br>df.applyPattern("00.00"); b.NumberFormat numberForm = NumberFormat.getNumberInstance(); numberForm.setMaximumFractionDigits(2); numberForm.setMinimumFractionDigits(2); c. NumberFormat numberForm = NumberFormat.getNumberInstance();<br>numberForm.setMaximumFractionDigits(2); Key:a # 18. Suppose that NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US). Which of the following statement is legal? a. Number number = NumberFormat.parse("$5,000.56"); b. Number number = currencyFormat.parse("$5,000.56"); c. Number number = currencyFormat.parseCurrency("$5,000.56"); d. Number number = currencyFormat.parse("5,000.56"); Key:b # 19. Which of the following statements are true? a. DecimalFormat is a subclass of NumberFormat. ..


b. You can create an instance of DecimalFormat using new DecimalFormat(Local). c. You can create an instance of NumberFormat using new NumberFormat(Local). d. You can create an instance of NumberFormat using the static factory methods in NumberFormat. e. An instance created using the static factory methods in NumberFormat is also an instance of DecimalFormat. Key:ade # 20. Which of the following statements are true regarding DecimalFormat? a. A pattern can specify the minimum number of digits before the decimal point and the maximum number of digits after the decimal point. b. The characters '0' and '#' are used to specify a required digit and an optional digit, respectively. c. The optional digit is not displayed if it is zero. d. If there are more actual digits before the decimal point, all the digits are displayed. e. If there are more digits after the decimal point, the digits are rounded. Key:abcde # 21. Suppose you apply the pattern "00.0##" on a DecimalFormat object f using f.applyPattern("00.0##"). What is the return value from decimalFormat.format(111.2226)? a. 11.223 b. 111.222 c. 111.223 d. 11.2226 Key:c # 22. Suppose you apply the pattern "00.0##%" on a DecimalFormat object f using f.applyPattern("00.0##%"). What is the return value from decimalFormat.format(111.2226)? a. 11.223% b. 111.222% c. 11122.3% d. 1122.3% e. 11122.26% Key:e # Section 36.5 Resource Bundles 23. A resource bundle is . a. a Java source code that contains image, audio, and text files b. a Java class file or a text file that provides locale-specific information c. an image file d. an audio file Key:b # 24. Which of the following code is correct to create an instance of ResourceBundle? a. ResourceBundle.getBundle(); b. ResourceBundle.getBundle(locale); c. ResourceBundle.getBundle(resourcefilename); d. ResourceBundle.getBundle(resourcefilename, locale); Key:c

..


Chapter 37 Servlets Section 37.2 HTML and Common Gateway Interface 1. Which of the following statements are true? a. Static information is preprocessed and stored in a file. The information in the files can be updated, but at any given time every request for the same document returns exactly the same result. b. Dynamic information is not stored in a file. It is generated dynamically and sent directly to the client. c. Common GateWay Interface provides a standard framework for Web servers to interact with external programs, known as CGI programs. d. CGI programs are all written in Perl. Key:abc # 2. In a URL query string, the a. ? b. = c. & d. + e. Key:a

symbol separates the program from the parameters.

# 3. In a URL query string, the parameter name and value are associated using the a. ? b. = c. & d. + e. Key:b # 4. In a URL query string, parameter pairs are separated using the a. ? b. = c. & d. + e. Key:c # 5. In a URL query string, the a. ? b. = c. & d. + e. Key:d

symbol denotes a space character.

# 6. The GET and POST methods are specified in a. a CGI program b. a Java program c. an HTML form ..

.

symbol.

symbol.


d. a URL string Key:c # 7. Which of the following statements are true? a. When issuing a request from an HTML form, either a GET method or a POST method can be used. The form explicitly specifies which of the two is used. b. If the GET method is used, the data in the form are appended to the request string as if they were submitted using a URL. c. If the POST method is used, the data in the form are packaged as part of the request file. The server program obtains the data by reading the file. d. The POST method always triggers the execution of the corresponding CGI program. The GET method may not cause the CGI program to be executed if the previous same request is cached in the Web browser. Key:abcd # 8. The a. GET b. POST c. DELETE d. UPDATE Key:b

method ensures that a new Web page is generated.

# 9. If your request is not time-sensitive, such as finding the address of a student in the database, use the method to speed up the performance. a. GET b. POST c. DELETE d. UPDATE Key:a # 10. Java servlets are better than the CGI programs because . a. servlets are written in Java while CGI programs are written in Perl or other languages. you can develop servlets with the support of Java API for accessing databases and network resources b. servlets are dynamically executed c. for each CGI execution, the Web browser spawns a new process to execute a CGI program. However, all servlets are executed within the servlet engine. Each execution of a servlet is handled as a thread by the servlet engine. So, servlets runs faster than CGI programs d. servlet programs can run on any Web server Key:ac Both CGI and servlets are dynamically executed. Servlet programs can run only on Web server with Java servlet engine # Section 37.3 Creating and Running Servlets 11. Apache Tomcat is a . a. Servlet b. Java program c. Web server d. Web server that is capable of running Java programs Key:d # ..


12. A servlet is an instance of a. the Object class b. the Applet class c. the HttpServlet class d. the HTTPServlet class Key:c

.

# 13. To compile a Java servlet program, the a. TomcatRootDir\servlet.jar b. TomcatRootDir\common\servlet.jar c. TomcatRootDir\common\lib\servlet.jar d. TomcatRootDir\common\bin\lib\servlet.jar Key:c

file must be in the classpath.

# 14. If your servlet class file does not have a package statement, the servlet .class file must be placed in default. a. the same directory with the .java file. b. TomcatRootDir\webapps\WEB-INF\classes c. TomcatRootDir\webapps\examples\WEB-INF d. TomcatRootDir\webapps\examples\WEB-INF\classes Key:d # 15. If your servlet class file has a package statement package chapter33, the servlet .class file must be placed in by default. a. the same directory with the .java file. b. TomcatRootDir\webapps\WEB-INF\classes c. TomcatRootDir\webapps\examples\WEB-INF\classes d. TomcatRootDir\webapps\examples\WEB-INF\classes\chapter33 Key:d # 16. Before starting Tomcat, you have to set the environment variable JAVA_HOME to a. JDKHomeDir b. JDKHomeDir/bin c. JDKHomeDir/bin/java d. JDKHomeDir/java Key:a # 17. To start the Tomcat servlet engine, use the command a. java TomcatServlet b. start Tomcat c. start d. startup Key:d # 18. By default, Tomcat runs on port a. 8080 b. 80 c. 1080 ..

.

from the TomcatRootDir\bin directory.

by


d. 8888 Key:a # 19. Suppose the servlet class named Test does not have the package statement, by default, you use it. a. http://localhost:8080/examples/servlet/Test b. http://localhost:8080/examples/servlet/test c. http://localhost:8080/Test d. http://localhost:8080/test Key:a

to invoke

# Section 37.4 The Servlet API 20. The interface defines the methods that all servlets must implement. a. javax.servlet.Servlet b. HttpServlet c. ServletRequest d. ServletResponse Key:a # 21. The method is called when the servlet is first created, and is not called again as long as the servlet is not destroyed. a. init b. service c. destroy d. getServletInfo Key:a # 22. The class defines a servlet for the HTTP protocol. a. javax.servlet.http.HttpServlet b. Servlet c. HttpServletRequest d. HttpServletResponse Key:a # 23. is a subinterface of ServletRequest. a. HttpServletRequest b. HttpServletResponse c. HttpServlet d. Servlet Key:a # 24. Every doXxx method in the HttpServlet class has a parameter of the type, which is an object that contains HTTP request information, including parameter name and values, attributes, and an input stream. a. HttpServletRequest b. HttpServletResponse c. HttpSession d. Cookie Key:a ..


# 25. Every doXxx method in the HttpServlet class has a parameter of the assists a servlet in sending a response to the client. a. HttpServletRequest b. HttpServletResponse c. HttpSession d. Cookie Key:b

type, which is an object that

# Section 37.5 Creating Servlets 26. Suppose the two parameters in the doGet or doPost method are request and response. To specify HTML content type sent to the client, invoke . a. response.setContentType("text/html") b. request.setContentType("text/html") c. response.setContentType("html") d. request.setContentType("html") Key:a # 27. Suppose the two parameters in the doGet or doPost method are request and response. To send output to a client, create a PrintWriter using . a. response.getWriter() b. response.getPrintWriter() c. response.writer() d. response.getWrite() Key:a # Section 37.6 HTML Forms 28. Which of the following creates a text field in an HTML form? a. <input type="text" name="mi" size="1"> b. <input type="radio" name="gender" value="M" checked> c. Major <elect name="major" size="1"> <option value="CS">Computer Science<option value="Math">Mathematics<option>English<option>Chinese</select> d. <input type="checkbox" name="tennis"> Tennis e. <textarea name="remarks" rows="3" cols="56"></textarea> Key:a # 29. Which of the following creates a radio button in an HTML form? a. <input type="text" name="mi" size="1"> b. <input type="radio" name="gender" value="M" checked> c. Major <select name="major" size="1"> <option value="CS">Computer Science<option value="Math">Mathematics<option>English<option>Chinese</select> d. <input type="checkbox" name="tennis"> Tennis e. <textarea name="remarks" rows="3" cols="56"></textarea> Key:b # 30. Which of the following creates a list in an HTML form? a. <input type="text" name="mi" size="1"> b. <input type="radio" name="gender" value="M" checked> ..


c. Major <select name="major" size="1"> <option value="CS">Computer Science<option value="Math">Mathematics<option>English<option>Chinese</select> d. <input type="checkbox" name="tennis"> Tennis e. <textarea name="remarks" rows="3" cols="56"></textarea> Key:c # 31. Which of the following creates a check box in an HTML form? a. <input type="text" name="mi" size="1"> b. <input type="radio" name="gender" value="M" checked> c. Major <select name="major" size="1"> <option value="CS">Computer Science<option value="Math">Mathematics<option>English<option>Chinese</select> d. <input type="checkbox" name="tennis"> Tennis e. <textarea name="remarks" rows="3" cols="56"></textarea> Key:d # 32. Which of the following creates a text area in an HTML form? a. <input type="text" name="mi" size="1"> b. <input type="radio" name="gender" value="M" checked> c. Major <select name="major" size="1"> <option value="CS">Computer Science<option value="Math">Mathematics<option>English<option>Chinese</select> d. <input type="checkbox" name="tennis"> Tennis e. <textarea name="remarks" rows="3" cols="56"></textarea> Key:e # Section 37.7 Database Programming in Servlets 33. The code for loading a JDBC driver and connecting to a database should be invoked from a. the init method b. the doGet method c. the doPut method d. the destroy method Key:a

in a servlet.

# 34. To access Oracle or MySQL from servlet, where the Oracle and MySQL jar files should be placed? a. in the class directory of the servlet source code b. in the class directory of the servlet class code c. TomcatRootDir\webapps\WEB-INF\classes d. TomcatRootDir\common\lib Key:d # Section 37.8 Session Tracking 35. You can use to implement session tracking in servlets. a. HTML hidden values in a form b. the Cookie class c. the HttpSession class Key:abc # 36. To store a hidden value for lastName as Smith in an HTML form, use a. <input type=”text” name=”lastName” value=”Smith”> ..

.


b. <input type=”text area” name=”lastName” value=”Smith”> c. <input type=”radio” name=”lastName” value=”Smith”> d. <input type=”checkbox” name=”lastName” value=”Smith”> e. <input type=”hidden” name=”lastName” value=”Smith”> Key:e # 37. To create a cookie for lastName with value Smith, use a. new Cookie("Smith", "lastName"); b. new Cookie(Smith, lastName); c. new Cookie("lastName", "Smith"); d. new Cookie(lastName, \Smith); Key:c

.

# 38. Suppose the two parameters in the doGet or doPost method are request and response. To send a cookie to a client, use . a. response.addCookie(cookie) b. response.sendCookie(cookie) c. request.addCookie(cookie) d. request.sendCookie(cookie) Key:a # 39. Suppose the two parameters in the doGet or doPost method are request and response. To retrieve a cookie from a client, use . a. response.retrieveCookie() b. response.getCookie() c. You have to use request.getCookies() to obtain all cookies in an array d. You have to use request.getCookie() to obtain a cookie Key:c # 40. For an instance of Cookie, say cookie, to retrieve the name of the cookie, use a. cookie.getValue() b. cookie.getName() c. You have to use cookie.getNames() to obtain all values in an array. d. You have to use cookie.getValues() to obtain all values in an array. Key:b

.

# 41. By default, how long does a cookie last? a. 24 hours b. 30 days c. 365 days d. By default, a newly created cookie persists until the browser exits. Key:d You can use the setMaxAge method to set a time for a cookie on a local client. # 37. Suppose the two parameters in the doGet or doPost method are request and response. To create an HTTP session, use . a. request.createSession() b. request.getSession() c. response.createSession() ..


d. response.getSession() Key:b request.getSession() obtains the session or creates a new session if the client does not have a session on the server. # 43. For a HttpSession, say session, how do you set an attribute pair with name lastName and value Smith? a. session.setValue("lastName", "Smith") b. session.setAttribute("lastName", "Smith") c. session.value("lastName", "Smith") d. session.attribute("lastName", "Smith") Key:b # 44. For a HttpSession, say session, how do you get its attribute? a. session.getValue("lastName") b. session.getAttribute("lastName") c. session.value("lastName") d. session.attribute("lastName") Key:b

..


Chapter 38 JavaServer Pages Section 38.2 A Simple JSP Page 1. A JSP file ends with a. .java extension b. .html extension c. .shtml extension d. .jsp extension Key:d

.

# 2. You can run JSP from . a. any Web server b. any JVM c. any Web server that supports Java servlet and JSP d. any Web browser Key:c # Section 38.3 How Is a JSP Page Processed? 3. Which of the following statements are true? a. JSP is translated into Java servlet by a Web server when a JSP is called. b. JSP is translated into HTML by a Web server when a JSP is called. c. JSP is translated into XML by a Web server when a JSP is called. d. You can embed Java code in JSP. Key:ad # Section 38.4 JSP Scripting Constructs 4. is a JSP expression. a. <%= i %> b. <%= Math.pow(2, 3) %> c. <%= new Date().toString() %> d. <% for (int i = 0; i <= 10; i++) { %> Key:abc # 5. is a JSP scriptlet. a. <%= i %&gt b. <%= Math.pow(2, 3) %&gt c. <%! private long computeFactorial(int n) { if (n == 0)return 1;else return n * computeFactorial(n - 1); } %&gt d. <% for (int i = 0; i <= 10; i++) { %&gt e. <!-- HTML Comment --%&gt Key:d # 6. is a JSP declaration. a. <%= i %> b. <%= Math.pow(2, 3) %> c. <%! private long computeFactorial(int n) { if (n == 0) return 1; else return n * computeFactorial(n - 1); } %> d. <% for (int i = 0; i <= 10; i++) { %> e. <!-- HTML Comment --> Key:c ..


# 7. is a JSP comment. a. <%= i %> b. <%-- i --%> c. <%! private long computeFactorial(int n) { if (n == 0) return 1; else return n * computeFactorial(n - 1); } %> d. <% for (int i = 0; i <= 10; i++) { %> e. <!-- HTML Comment --> Key:b # Section 38.5 Predefined Variables 8. Which of the following is a JSP implicit object? a. request b. response c. out d. session e. application Key:abcde # 9. The JSP explicit object out is actually a. response.getOutputStream() b. response.getWriter() c. request.getOutputStream() d. request.getWriter() e. application Key:b

.

# Section 38.6 JSP Directives 10. is a statement that gives the JSP engine information about the JSP page. a. A JSP implicit object b. A JSP scriptlet c. A JSP expression d. A JSP directive Key:d # 11. The directive lets you provide information for the page, such as importing classes and setting up content type. The page directive can appear anywhere in the JSP file. a. page b. include c. tablib d. import Key:a # Section 38.7 Using JavaBeans in JSP 12. A class is a JavaBeans component if a. it is a public class b. it has a public constructor with no arguments c. it is serializable. Key:abc ..

.


Chapter 39 JavaServer Faces 1. completely separates Web UI from Java code so the application developed using JSF is easy to debug and maintain. a. Java servlet b. JSP c. JSF d. PHP e. JavaScript Key:c # 2. You can use NetBeans 6 to develop a. Java servlet b. JSP c. JSF d. PHP Key:abc

applications.

# 3. Which of the following are JSF life-cycle methods? a. init() b. preprocess() c. prerender() d. destroy() Key:abcd

..


Chapter 40 Remote Method Invocation Section 40.2 RMI Basics 1. RMI is about . a. passing primitive data between a server and a client b. passing objects between a server and a client c. accessing remote objects and invoking methods from remote objects. d. java.lang.Cloneable Key:c # 2. A remote object must be an instance of a. java.rmi.RemoteObject b. java.rmi.Remote c. java.io.Serializable d. java.lang.Cloneable Key:b

.

# 3. is a subinterface of java.rmi.Remote that defines the methods for the server object. a. Server object interface b. Server implementation c. RMI Registry d. Server stub e. Server Skeleton Key:a # 4. is a class that implements the remote object interface. a. Server object interface b. Server implementation c. RMI Registry d. Server stub e. Server Skeleton Key:b # 5. is a utility that registers remote objects and provides naming services for locating objects. a. Server object interface b. Server implementation c. RMI Registry d. Server stub e. Server Skeleton Key:c # 6. is an object that resides on the client host and serves as a surrogate for the remote server object. a. Server object interface b. Server implementation c. RMI Registry d. Server stub e. Server Skeleton Key:d ..


# 7. is an object that resides on the server host, communicates with the stub and the actual server object. a. Server object interface b. Server implementation c. RMI Registry d. Server stub e. Server Skeleton Key:e # 8. Which of the following statements are true when passing arguments in a remote method call. a. Primitive data types, such as char, int, double, or boolean, are passed by value like a local call. b. Local object types, such as java.lang.String, are also passed by value, but this is completely different from passing an object parameter in a local call. Any object can be used as a parameter in a remote call as long as it is serializable. The stub serializes the object parameter and sends it in a stream across the network. The skeleton deserializes the stream into an object. c. Remote object types are passed differently from local objects. When a client invokes a remote method with a parameter of a remote object type, the stub of the remote object is passed. The server receives the stub and manipulates the parameter through it. d. When a client invokes a remote method with parameters, passing the parameters is handled by the stub and the skeleton. Key:abcd # 9. provides the naming services for the server to register the object and for the client to locate the object. a. Server object interface b. Server implementation c. RMI Registry d. Server stub e. Server Skeleton Key:c # 10. Each remote object has a unique name identified by an URL with the protocol rmi as follows: a. rmi://host:port/name b. //host:port/name c. http://host:port/name d. http://host/name Key:b # Section 40.3 Developing RMI Applications 11. To register a remote object o with a name t at port 7000 on host panda.armstrong.edu, use a. Naming.bind("rmi://panda.armstrong.edu:7000/t", o); b. Naming.rebind("rmi://panda.armstrong.edu:7000/t", o); c. Name.rebind("rmi://panda.armstrong.edu:7000/t", o); d. Name.bind("rmi://panda.armstrong.edu:7000/t", o); Key:ab (A) and (B) are both fine. (B) rebinds the object if the name is already in use. # 12. To locate a remote object with a name t at port 7000 on host panda.armstrong.edu, use a. Remote remoteObj = Naming.lookup("rmi://panda.armstrong.edu:7000/t"); b. Remote remoteObj = Name.lookup("rmi://panda.armstrong.edu:7000/t"); ..


c. Remote remoteObj = Name.lookup("//panda.armstrong.edu:7000/t"); d. Remote remoteObj = Name.lookup("http://panda.armstrong.edu:7000/t"); Key:a # 13. To start an RMI registry, use from the command window. a. start rmiregistry b. start rmiregistry 7000 c. rmiregistry d. rmiregistry 7000 Key:ab (A) start an RMI registry at port 1099 and (B) starts an RMI registry at port 7000. # 14. Assume that the file named policy contains the permission for registering a remote object with an RMI registry. To run the program (e.g., RegisterWithRMIServer) that registers a remote object with an RMI registry, use the command from the command window. a. java –Djava.security.policy=policy RegisterWithRMIServer b. java RegisterWithRMIServer java –Djava.security.policy=policy c. java RegisterWithRMIServer d. java –Dpolicy=policy RegisterWithRMIServer Key:a

..


Chapter 41 Web Services 1. Which of the following statements are correct? a. The computer on which a Web service resides is referred to as a server. b. The server needs to make the service available to the client, known as publishing a Web service. c. Using a Web service from a client is known as consuming a Web service. d. A client interacts with a Web service through a proxy object. e. The proxy object facilitates the communication between the client and the Web service. Key:abcde

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


Chapter 42 2-4 Trees and B-Trees 1. Which of the following statements are correct? a. All leaf nodes are on the same level in a 2-4 tree. b. In a 2-4 tree, a node may have one, two, or three elements. c. An interior 2-node contains one element and two children. d. An interior 3-node contains two elements and three children. e. An interior 4-node contains three elements and four children. Key:abcde # 2. How many elements can a root of a 2-4 tree have? a. 0 b. 1 c. 2 d. 3 e. 4 Key:bcd # 3. How many elements can an interior node of a 2-4 tree have? a. 0 b. 1 c. 2 d. 3 e. 4 Key:bcd # 4. How many elements can a leaf node of a 2-4 tree have? a. 0 b. 1 c. 2 d. 3 e. 4 Key:bcd # 5. In a B-tree of order 6, how many elements can the root have? a. 0 b. 1 c. 2 d. 5 e. 6 Key:bcd # 6. In a B-tree of order 6, how many elements can a non-root have? a. 0 b. 3 c. 4 d. 5 e. 6 © 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


Key:bcd

© 2020 Pearson Education, Inc., Hoboken, NJ. All rights reserved. This material is protected under all copyright laws as they currently exist.


Chapter 43 Red-Black Trees 1. Which of the following statements are correct? a. A red-black tree is a binary search tree. b. All leaf nodes are colored black in a red-black tree. c. All leaf nodes are colored red in a red-black tree. d. All external nodes are leaf nodes. e. All leaf nodes are external nodes. Key:ae # 2. Which of the following statements are correct? a. The black depth of a node is defined as the number of black nodes in a path from the node to the root. b. The root is black. c. Two adjacent nodes cannot be both red. d. All external nodes have the same black depth. Key:abcd

..


Chapter 44 Testing Using JUnit 1. A test class must be placed in a named package. a. True b. False Key:a # 2. JUnit is part of the standard Java API? a. True b. False Key:b # 3. To test whether two values v1 and v2 are the same, use a. assertTrue(v1) b. assertTrue(v2) c. assertEquals(v1, v2) d. assertEquals(v2, v1) Key:cd # 4. To test whether an expression e is true, use a. assertTrue(e) b. asserttrue(e) c. assertEquals(e) d. assertequals(e) Key:a

..

.

.


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.