Java How to Program (early objects), 9E By Paul Deitel Harvey Deitel
Email: richard@qwconsultancy.com
Java How to Program, 9/e Multiple Choice Test Bank
1 of 5
Chapter 1 Introduction to Computers and Java Section 1.1 Introduction 1.1 Q1: Which of the following statements is false? a. Object-oriented programming is today's key programming methodology. b. Java has become the language of choice for implementing Internet-based applications and software for devices that communicate over a network. c. Software commands computer hardware to perform tasks. d. In use today are more than a trillion general-purpose computers and trillions more Java-enabled cellphones, smartphones and other handheld devices. ANS: d. In use today are more than a trillion general-purpose computers and trillions more Java-enabled cellphones, smartphones and other handheld devices. 1.1 Q2: Which edition of Java is geared toward developing large-scale, distributed networking applications and webbased applications? a. Standard Edition. b. Industrial Edition. c. Enterprise Edition. d. Micro Edition. ANS: c. Enterprise Edition.
Section 1.2 Computers: Hardware and Software 1.2 Q1: Which of the following is most closely associated with Moore's Law? a. Every year or two, the price of computers has approximately doubled. b. Object-oriented programming uses less memory than previous software-development methodologies. c. Demand for communications bandwidth is decreasing dramatically each year. d. Every year or two, the capacities of computers have approximately doubled without any increase in price. ANS: d. Every year or two, the capacities of computers have approximately doubled without any increase in price. 1.2 Q2: Which of the following statements is false? a. A quadrillion-instruction-per-section computer can perform in one second more than 100,000 instructions for every person on the planet. b. Today's key programming methodology is object-oriented programming. c. The vast majority of the microprocessors produced each year are used in general-purpose computers. d. Computers process data under the control of sets of instructions called computer programs.. ANS: c. The vast majority of the microprocessors produced each year are used in general-purpose computers. Actually, they're used in embedded systems.
Section 1.3 Data Hierarchy 1.3 Q1: Which of the following statements is false? a. The impressive functions performed by computers involve only the simplest manipulations of 1s and 2s . b. ASCII is a popular subset of Unicode. c. Fields are composed of characters or bytes. d. On some operating systems, a file is viewed simply as a sequence of bytes. ANS: a. The impressive functions performed by computers involve only the simplest manipulations of 1s and 2s . It's 1s and 0s. 1.3 Q2: Which of the following data items are arranged from the smallest to the largest in the data hierarchy. a. records, characters, fields, bits, files. b. bits, files, fields, records, characters. c. fields, characters, bits, files, records. d. bits, characters, fields, records, files. ANS: d. bits, characters, fields, records, files. ..
Java How to Program, 9/e Multiple Choice Test Bank
2 of 5
Section 1.4 Computer Organization 1.4 Q1: Which of the following is not one of the six logical units of a computer? a. Input unit. b. Output unit. c. Central processing unit. d. Printer. ANS: d. Printer. 1.4 Q2: Which of the following statements is false? a. Speaking to your computer is a form of input. b. Playing a video is an example of output. c. A multi-core processor implements several processors on a single integrated-circuit chip. d. Information in the memory unit is persistent—it is retained when the computer's power is turned off. ANS: Information in the memory unit is persistent—it is retained when the computer's power is turned off. Actually the information is volatile—it's lost when power is turned off.
Section 1.5 Machine Languages, Assembly Languages and High-Level Languages 1.5 Q1: Which of the following is not one of the three general types of computer languages? a. Machine languages. b. Assembly languages. c. High-Level languages. d. Spoken languages. ANS: d. Spoken languages. 1.5 Q2: Which of the following statements is true? a. Interpreted programs run faster than compiled programs. b. Compilers translate high-level language programs into machine language programs. c. Interpreter programs typically use machine language as input. d. None of the above. ANS: b. Compilers translate high-level language programs into machine language programs.
Section 1.6 Introduction to Object Technology 1. 6 Q1: ________ is a graphical language that allows people who design software systems to use an industry standard notation to represent them. a. The Unified Graphical Laguage b. The Unified Design Language c. The Unified Modeling Language d. None of the above ANS: c. The Unified Modeling Language. 1. 6 Q2: ________ models software in terms similar to those that people use to describe real-world objects. a. Object-oriented programming b. Object-oriented design c. Procedural programming d. None of the above ANS: b. Object-oriented design. 1.6 Q3: Which statement is false? a. Classes are reusable software components. b. A class is to an object as a blueprint is to a house. c. Performing a task in a program requires a method. d. A class is an instance of its object. ANS: A class is an instance of its object. The reverse is true. ..
Java How to Program, 9/e Multiple Choice Test Bank
3 of 5
Section 1.7 Operating Systems 1.7 Q1 Which of the following statements is false? a. The concepts of icons, menus and windows were originally developed by Xerox PARC. b. Windows is an open source operating system. c. The software that contains the core components of the operating system is called the kernel. d. Linux source code is available to the public for examination and modification. Ans: b. Windows is an open source operating system. Actually, Windows is a proprietary operating system. 1.7 Q2: Which of the following is not a key organization in the open-source community? a. Apache. b. SourceForge. c. Firefox. d. Eclipse. ANS: c. Firefox (it's a web browser made by the open source organization Mozilla).
Section 1.8 Programming Languages 1.8 Q1: Today, virtually all new major operating systems are written in: a. Objective-C. b. C or C++. c. Visual C#. d. Ada. ANS: b. C or C++. 1.8 Q2: Which of the following languages is used primarily for scientific and engineering applications? a. Fortran. b. COBOL. c. Pascal. d. Basic. ANS: a. Fortran. 1.8 Q3: Which language was developed by Microsoft in the early 1990s to simplify the development of Windows applications? a. Visual C#. b. Python. c. Objective-C. d. Visual Basic. ANS: d. Visual Basic.
Section 1.9 Java and a Typical Java Development Environment 1.9 Q1: Java was originally developed for: a. Operating systems development. b. Intelligent consumer devices. c. Personal computers. d. Distributed computing. ANS: b. Intelligent consumer devices. 1.9 Q2: Which of the following statements about Java Class Libraries is false: a. Java class libraries consist of classes that consist of methods that perform tasks. b. Java class libraries are also known as Java APIs (Application Programming Interfaces). c. An advantage of using Java class libraries is saving the effort of designing, developing and testing new classes. d. Java class libraries are not portable ANS: d. Java class libraries are not portable. (Java class libraries are portable.) ..
Java How to Program, 9/e Multiple Choice Test Bank
4 of 5
1.9 Q3: The .class extension on a file means that the file: a. Contains java source code b. Contains HTML c. is produced by the Java compiler (javac). d. None of the above. ANS: c. Is produced by the Java compiler (javac). 1.9 Q4 : The command ________ executes a Java application. a. run b. javac c. java d. None of the above ANS: c. java.
Section 1.10 Test-Driving a Java Application (none)
Section 1.11 Web 2.0: Going Social 1.11 Q1: ________ helps Internet-based applications perform like desktop applications. a. Ajax b. Blogging c. RSS d. Mashups ANS: a. Ajax. 1.11 Q2: Which of the following companies is widely regarded at the "signature" company of Web 2.0 ? a. Foursquare. b. Facebook. c. Google. d. Groupon. ANS: c. Google.
Section 1.12 Software Technologies 1.12 Q1: ________ involves reworking programs to make them clearer and easier to maintain while preserving their correctness and functionality. a. Object-oriented programming b. Refactoring c. Agile software development d. LAMP ANS: b. Refactoring. 1.12 Q2: Which software product release category is "generally feature complete and supposedly bug free, and ready for use by the community?" a. Alpha. b. Beta. c. Release candidate. d. Continuous beta. ANS: c. Release candidate.
Section 1.13 Keeping Up-to-Date with Information Technologies (none).
..
Java How to Program, 9/e Multiple Choice Test Bank
5 of 5
..
Chapter 2 Introduction to Java Applications Section 2.2 Your First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler are denoted using a. Two forward slashes ( // ). b. Three forward slashes ( /// ). c. A slash and a star ( /* ). d. A slash and two stars ( /** ). e. ANS: a. Two forward slashes ( // ). 2.2 Q2: Which of the following is not a valid Java identifier? a. b. c. d.
my Value $_AAA1 width m_x
ANS: a. my Value (Identifiers may not contain blanks). 2.2 Q3: Which of the following cannot cause a syntax error to be reported by the Java compiler? a. Mismatched {} b. Missing */ in a comment that begins with /* c. Missing ; d. An extra blank line. ANS: d. Extra blank lines. 2.2 Q4: Which of the following does not contain a syntax error? a. b. c. d.
System.out.println( 'Hello world!' ): System.out.println( "Hello world!" ); System.out.println( "Hello world!" ); System.out.println( Hello world! );
ANS: c. System.out.println( "Hello world!" ); Compiling and Executing Your First Java Application 2.2 Q5: Which command compiles the Java source code file Welcome.java? a. b. c. d.
cd Welcome.java javac Welcome.java java Welcome.java compile Welcome.java
ANS: b. javac Welcome.java 2.2 Q6: Which command executes the Java class file Welcome.class? a. b. c. d.
..
javac Welcome.class java Welcome.class java Welcome run Welcome.class
ANS: c. java Welcome
Section 2.3 Modifying Your First Java Program Displaying a Single Line of Text with Multiple Statements 2.3 Q1: Which is the output of the following statements? a. b. c. d.
System.out.print( "Hello "); System.out.println( "World" ); Hello World HelloWorld Hello World World Hello
ANS: a. Hello World Displaying Multiple Lines of Text with a Single Statement 2.3 Q2: Which of the following is the escape character? a. b. c. d.
* \ \n "
ANS: b. \ 2.3 Q3: Which of the following statements will print a single line containing "hello there"? a. b. c. d.
System.out.println( "hello" ); System.out.println( " there" ); System.out.println( "hello" , " there" ); System.out.println( "hello" ); System.out.print( " there" ); System.out.print( "hello" ); System.out.println( " there" );
ANS: d. System.out.print( "hello" ); System.out.println( " there" );
2.3 Q4: Which of the following escape sequences represents a carriage return? a. \n. b. \r. c. \cr. d. \c. ANS: b. \r. 2.3 Q5: Which of the following statements would display the phase Java is fun? a. b. c. d.
System.out.println( "hellois fun\rJava " ); System.out.println( 'Java is fun' ); System.out.println( "\"Java is fun\"" ); System.out.println( Java is fun );
ANS: a. System.out.println( "hellois fun\rJava " );
..
Section 2.4 Displaying Text with printf 2.4 Q1: When method printf requires multiple arguments, the arguments are separated with ________. a. colons (:). b. semicolons (;). c. commas (,). d. periods (.). ANS: c. commas (,). 2.4 Q2: Which of the following statement displays Hello World? a. b. c. d.
System.out.printf( "%2s", "Hello " "World" ); System.out.printf( "%s %s", "Hello", "World" ); System.out.printf( "%s%s", "Hello, World" ); System.out.printf( "s% s%", "Hello", "World" );
ANS: b. System.out.printf( "%s %s", "Hello", "World" );
Section 2.5 Another Application: Adding Integers 2.5 Q1: All import declarations must be placed a. inside the class declaration’s body. b. before the class declaration. c. after the class declaration. d. all of the above will work. ANS: b. before the class declaration. 2.5 Q2: Which of the following is a variable declaration statement? a. b. c. d.
int total; import java.util.Scanner; public static void main( String args[] ) // first string entered by user
ANS: a. int total; 2.5 Q3: A(n) ________ enables a program to read data from the user. a. printf. b. import declaration. c. Scanner. d. main. ANS: c. Scanner. 2.5 Q4: Which of the following is not a Java primitive type? a. b.
..
char byte
c. d.
real double
ANS: c. real 2.5 Q5: The format specifier ________ is a placeholder for an int value? a. b. c. d.
%a %d %int %s
ANS: b. %d
Section 2.6 Memory Concepts 2.6 Q1: Which of the following statements does not alter a memory location? a. b. c. d.
int a; number = 12; y = y + 2; width = Integer.parseInt(input);
ANS: a. int a;
Section 2.7 Arithmetic 2.7 Q1: What is the value of result after the following Java statements execute? int a, b, c, d, result; a = 4; b = 12; c = 37; d = 51; result = d % a * c + a % b + a;
119 51 c. 127 d. 59 ANS: a. 119 a.
b.
2.7 Q2: Which of the following is not an arithmetic operator? a. b. c. d.
+ . %
ANS: c. .
..
Section 2.8 Decision Making: Equality and Relational Operators 2.8 Q1: What will be output after the following Java statements have been executed? int a, b, c, d; a = 4; b = 12; c = 37; d = 51; if ( a < b ) System.out.println( "a < b" ); if ( a > b ) System.out.println( "a > b" ); if ( d <= c ) System.out.println( "d <= c" ); if ( c != d ) System.out.println( "c != d" ); a. b.
c. d.
a<b c != d a<b d <= c c != d a>b c != d a<b c<d a != b
ANS: a. a < b c != d
2.8 Q2: Which of the following is not a compilation error? a. Neglecting to initialize a local variable in a method before it is used. b. Placing a semicolon at the end of the first line of an if statement. c. Omitting the left and right parenthesis for the condition of an if statement. d. All are compilation errors. ANS: b. Placing a semicolon at the end of the first line of an if statement. 2.8 Q3: Each of the following is a relational or equality operator except: a. b. c. d.
<= =! == >
ANS: b. =!
..
Java How to Program, 9/e Multiple Choice Test Bank
1 of 4
Chapter 3 Introduction to Classes and Objects Section 3.2 Declaring a Class with a Method and Instantiating an Object of a Class Class GradeBook 3.2 Q1: Method headers contain all of the following except: a. Access modifier. b. Left brace. c. Name of method. d. Return type. ANS: b. Left brace. 3.2 Q2: Every Java application is composed of at least one: a. local variable b. instance variable c. public class declaration d. imported class ANS c. public class declaration
Class GradeBookTest 3.2 Q3: A class instance creation expression contains: a. Parentheses. b. The new keyword. c. The name of the class. d. All of the above. ANS: d. All of the above. 3.2 Q4: Calling a method of another object requires which item? a. The dot separator. b. Open and close braces. c. The new keyword. d. None of the above. ANS a. The dot separator.
Section 3.3 Declaring a Method with a Parameter 3.3 Q1: What is the name of the values the method call passes to the method for the parameters? a. Arguments. b. References. c. Objects. d. Values. ANS: a. Arguments. 3.3 Q2: Which of the following is a Scanner method? a. nextLine. b. nextText. c. nextWord. d. readNext. ANS: a. nextLine. © Copyright 1998-2012 by Deitel & Associates, Inc. and Pearson Education, Inc.
Java How to Program, 9/e Multiple Choice Test Bank
More on Arguments and Parameters 3.3 Q3: Multiple parameters are separated with what symbol? a. Dot separator b. Comma. c. Parentheses. d. Braces. ANS: b. Comma. Notes on import declaration 3.3 Q4: Which of the following is a valid fully qualified name? a. Scanner. b. java.Scanner. c. util.Scanner. d. java.util.Scanner. ANS: d. java.util.Scanner.
Section 3.4 Instance Variables, set Methods and get Methods 3.4 Q1: Attributes of a class are also known as: a. Constructors. b. Local variables. c. Fields. d. Classes. ANS: c. Fields. GradeBookTest Class That Demonstrates Class GradeBook
3.4 Q2: What is the default initial value of a String instance variable? a. "" b. "default" c. default d. null ANS: d. null set and get Methods 3.4 Q3: What type of methods allow a client of a class to assign values to a private instance variable? a. Get methods. b. Replace methods. c. Assign methods. d. Set methods. ANS: d. Set methods.
Section 3.5 Primitive Types vs. Reference Types 3.5 Q1: What is the default value of a reference? a. 0. b. "". c. null. d. default. ANS: c. null.
© Copyright 1998-2012 by Deitel & Associates, Inc. and Pearson Education, Inc.
2 of 4
Java How to Program, 9/e Multiple Choice Test Bank
3 of 4
Section 3.6 Initializing Objects with Constructors 3.6 Q1: A default constructor has how many parameters? a. 0. b. 1. c. 2. d. a variable number. ANS: a. 0.
Section 3.7 Floating-Point Numbers and Type double 3.7 Q1: Which two Java primitive types store floating-point numbers? a. decimal and float. b. point and double. c. float and double. d. decimal and point. ANS: c. float and double. 3.7 Q2: What is the difference between a float and a double? a. double variables store integers and float variables store floating-point numbers. b. double variables store numbers with smaller magnitude and coarser detail. c. double variables store numbers with larger magnitude and finer detail. d. None of the above. ANS: c. double variables store numbers with larger magnitude and finer detail. Floating-Point Number Precision and Memory Requirements 3.7 Q3: How many significant digits does a double variable have? a. 7. b. 8. c. 14. d. 15. ANS: d. 15.
Section 3.7 Floating-Point Numbers and Type double 3.8 Q1: How many significant digits does a double variable have? a. 7. b. 8. c. 14. d. 15. ANS: d. 15.
Section 3.8 (Optional) GUI and Graphics Case Study: Using Dialog Boxes 3.8 Q1: Which class provides prebuilt dialog boxes that enable programs to display windows containing messages (such windows are called message dialogs)? a. JDialogBox. b. JPrebuiltDialog. c. JMessageDialog. d. JOptionPane. ANS: d. JOptionPane.
© Copyright 1998-2012 by Deitel & Associates, Inc. and Pearson Education, Inc.
Java How to Program, 9/e Multiple Choice Test Bank
4 of 4
3.8 Q3: Which class provides prebuilt dialog boxes that enable programs to display windows containing messages (such windows are called message dialogs)? a. JDialogBox. b. JPrebuiltDialog. c. JMessageDialog. d. JOptionPane. ANS: d. JOptionPane. 3.8 Q2: Which of the following statements is false? a. You must create an object of class JOptionPane to use its static method showMessageDialog. b. JOptionPane method showInputDialog displays an input dialog containing a prompt and a field (known as a text field) in which a user can enter text. c. String method format works like method System.out.printf, except that format returns the formatted String rather than displaying it in a command window. d. An input dialog allows the user to enter data into a program. ANS: a. You must create an object of class JOptionPane to use its method showMessageDialog.
© Copyright 1998-2012 by Deitel & Associates, Inc. and Pearson Education, Inc.
Chapter 4 Control Statements: Part 1 Section 4.2 Algorithms 4.2 Q1: Which of the following is not an algorithm? a. A recipe. b. Operating instructions. c. Textbook index. d. Shampoo instructions (lather, rinse, repeat). ANS: c. Textbook index. A textbook index contains useful information, but does not specify actions and the order in which they are to be performed.
Section 4.3 Pseudocode 4.3 Q1: Which of the following is true? a. Pseudocode is used to describe an algorithm. b. Pseudocode is not an actual computer programming language. c. Pseudocode is used to describe executable statements that will eventually be translated by the programmer into a program. d. All of the above. ANS: d. All of the above.
Section 4.4 Control Structures 4.4 Q1: Which of the following is not a benefit of “goto-less programming”? a. Easier to debug and modify b. Shorter c. Clearer d. More likely to be bug free ANS: b. Shorter 4.4 Q2: Which of the following is not a control structure: a. Sequence structure. b. Selection structure. c. Repetition structure. d. Declaration structure. ANS: d. Declaration structure.
Sequence Structure in Java 4.4 Q3: Which of the following is the shape of an action-state symbol? a. Diamond. b. Circle. c. Rectangle with left and right sides replaced with arcs curving outward. d. Rounded rectangle. ANS: c. Rectangle with left and right sides replaced with arcs curving outward.
..
4.4 Q4: Which statement is false? a. Unless directed otherwise, the computer executes Java statements one after the other in the order in which they're written. b. Activity diagrams normally show the Java code that implements the activity. c. Like pseudocode, activity diagrams help programmers develop and represent algorithms. d. The arrows in the activity diagram represent transitions, which indicate the order in which the actions represented by the action states occur. ANS: b. Activity diagrams normally show the Java code that implements the activity.
Selection Statements in Java 4.4 Q5: Which of the following is a double-selection control statement? a. do…while. b. for. c. if…else. d. if. ANS: c. if…else.
Repetition Statements in Java 4.4 Q6: Which of the following is not a Java keyword? a. do b. next c. while d. for ANS: b. next
Section 4.5 if Single-Selection Statement 4.5 Q1: What is output by the following Java code segment? int temp = 200; if ( temp > 90 ) System.out.println( "This porridge is too hot." ); if ( temp < 70 ) System.out.println( "This porridge is too cold." ); if ( temp == 80 ) System.out.println( "This porridge is just right!" );
a. This porridge is too hot. b. This porridge is too cold. c. This porridge is just right! ..
d. None of the above. ANS: a. This porridge is too hot. 4.5 Q2: A decision symbol in an activity diagram takes the shape of a ________. a. Diamond. b. Rectangle. c. Circle. d. Triangle. ANS: a. Diamond. 4.5 Q3: Which of the following is not represented graphically in activity diagrams for control structures? a. Transition arrow. b. Attribute. c. Action state. d. Decision symbol. ANS: b. Attribute.
Section 4.6 if…else Double-Selection Statement Conditional Operator (?:) 4.6 Q1: Which of the following statements about the conditional operator ( ?: ) is false? a. The conditional operator is a ternary operator, meaning that it takes three operands. b. The first operand is a boolean expression. c. The second operand is the result value if the condition evaluates to false. d. The second operand is the result value if the condition evaluates to true. ANS: c. The second operand is the result value if the condition evaluates to false.
Nested if…else Statements 4.6 Q2: What is output by the following Java code segment? int temp = 180; if ( temp > 90 ) { System.out.println( "This porridge is too hot." ); // cool down temp = temp – ( temp > 150 ? 100 : 20 ); } // end if else { if ( temp < 70 ) { System.out.println("This porridge is too cold.");
..
// warm up temp = temp + (temp < 50 ? 30 : 20); } // end if } // end else if ( temp == 80 ) System.out.println( "This porridge is just right!" );
a. This porridge is too hot. b. This porridge is too cold.
This porridge is just right!
c. This porridge is just right! d. None of the above. ANS: d. None of the above. (The output will be This porridge is too hot. This porridge is just right!)
Dangling-else Problem 4.6 Q3: Which of the following would not be used to clarify a dangling-else? a. Indentation. b. Parentheses (). c. Braces {}. d. Comment //. ANS: b. Parentheses ().
Blocks 4.6 Q4: The empty statement is denoted by what symbol? a. Semicolon ;. b. Parentheses (). c. Braces {}. d. Colon :. ANS: a. Semicolon ;. 4.6 Q5: Which statement is false? a. Both syntax errors and logic errors are caught by the compiler. b. Both syntax errors and logic errors have effects at execution time. c. Syntax errors are caught by the compiler. Logic errors have effects at execution time. d. Logic errors are caught by the compiler. Syntax errors have effects at execution time. ANS: c. Syntax errors are caught by the compiler. Logic errors have their effects at execution time.
Section 4.7 while Repetition Statement 4.7 Q1: What is output by the following Java code segment? int temp = 180; ..
while ( temp != 80 ) { if ( temp > 90 ) { System.out.print( "This porridge is too hot! " ); // cool down temp = temp – ( temp > 150 ? 100 : 20 ); } // end if else { if ( temp < 70 ) { System.out.print( "This porridge is too cold! "); // warm up temp = temp + (temp < 50 ? 30 : 20); } // end if } // end else } // end while if ( temp == 80 ) System.out.println( "This porridge is just right!" );
a. This porridge is too cold! This porridge is just right! b. This porridge is too hot! This porridge is just right! c. This porridge is just right! d. None of the above. ANS: b. This porridge is too hot! This porridge is just right! 4.7 Q2: Which of the following is not an error (either a syntax error or a logic error)? a. Neglecting to include an action in the body of a while statement that will eventually cause the condition to become false. b. Spelling a keyword (such as while or if) with a capitalized first letter. c. Using a condition for a while statement that is initially false. d. An infinite loop. ANS: c. Using a condition for a while statement that is initially false. 4.7 Q3: In an activity diagram, the merge symbol has the same shape as what other symbol? a. Decision symbol. b. Action symbol. c. Transition arrows. d. Initial state. ANS: a. Decision symbol.
Section 4.8 Formulating Algorithms: Counter-Controlled Repetition Pseudocode Algorithm with Counter-Controlled Repetition
..
4.8 Q1: Counter-controlled repetition is also known as: a. Definite repetition b. Indefinite repetition c. Multiple-repetition structure d. Double-repetition structure ANS: a. Definite repetition
Implementing Counter-Controlled Repetition in Class GradeBook 4.8 Q2: How many times is the body of the loop below executed? int counter = 1; while ( counter > 20 ) { // body of loop counter = counter - 1; } // end while
a. 19. b. 20. c. 21. d. 0. ANS: d. 0. 4.8 Q3: Where can local variables declared within a method’s body be used? a. Only in that method between the line in which they were declared and the closing brace of that method. b. Same as (a), but not within while or if statements. c. Only within while or if statements within the method in which they were declared. d. Anywhere within the class. ANS: a. Only in that method between the line in which they were declared and the closing brace of that method.
Notes on Integer Division and Truncation 4.8 Q4: Which statement is true? a. Dividing two integers results in integer division. b. With integer division, any fractional part of the calculation is lost. c. With integer division, any fractional part of the calculation is truncated. d. All of the above. ANS: d. All of the above.
..
Section 4.9 Formulating Algorithms: Sentinel-Controlled Repetition 4.9 Q1: Which of the following terms is not used to refer to a sentinel value that breaks out of a while loop? a. signal value. b. maximum value. c. dummy value. d. flag value. ANS: b. maximum value. 4.9 Q2: Sentinel-controlled repetition is also known as: a. Definite repetition. b. Indefinite repetition. c. Multiple repetition. d. Double repetition. ANS: b. Indefinite repetition.
Developing the Pseudocode Algorithm with Top-Down, Stepwise Refinement: The Top and First Refinement 4.9 Q3: Which of the following is not a common name for one of the three phases that a program often can be split into using pseudocode? a. Termination phase b. Initialization phase c. Processing phase d. Action phase ANS: d. Action phase
Implementing Sentinel-Controlled Repetition in Class GradeBook 4.9 Q4: Which of the following segments is a proper way to call the method readData four times? a. double k = 0.0; while ( k != 4 ) { readData(); k = k + 1; } // end while b. int i = 0; while ( i <= 4 ) { readData(); i = i + 1; } // end while
..
c. int i = 0; while ( i < 4 ) { readData(); } // end while d. int i = 0; while ( i < 4 ) { readData(); i = i + 1; } // end while ANS: d. int i = 0; while ( i < 4 ) { readData(); i = i + 1; } // end while
Explicitly and Implicitly Converting Between Primitive Types 4.9 Q5: In an expression containing values of the types int and double, the ________ values are ________ to ________ values for use in the expression. a. int, promoted, double. b. int, demoted, double. c. double, promoted, int. d. double, demoted, int. ANS: a. int, promoted, double. 4.9 Q6: Which statement is false? a. To ensure that the operands are of the same type, Java performs implicit conversion on selected operands. b. Cast operators are unary operators. c. Cast operators associate from right to left and are one level lower in precedence than the multiplicative operators. d. Cast operators are formed by placing parentheses around the name of a type. ANS: c. Cast operators associate from right to left and are one level lower in precedence than the multiplicative operators.
Section 4.10 Formulating Algorithms: Nested Control Statements
..
Complete Second Refinement of Pseudocode and Conversion to Class Analysis 4.10 Q1: Local variables must be ________. a. initialized when they're declared. b. initialized before their values are used in an expression. c. declared and initialized in two steps. d. declared at the top of the method’s body. ANS: b. initialized before their values are used in an expression. 4.10 Q2: Which statement is true? a. A while statement cannot be nested inside another while statement. b. An if statement cannot be nested inside another if statement. c. A while statement cannot be nested inside an if statement. d. None of the above is true. ANS: None of the above is true.
Section 4.11 Compound Assignment Operators 4.11 Q1: Which of the following code segments does not increment val by 3: a. val += 3; b. val = val+1; val = val+1; val = val+1; c. c = 3; val = val + (c == 3 ? 2 : 3); d. All of the above increment val by 3. ANS: c. c = 3; val = val + (c == 3 ? 2 : 3);
4.11 Q2: What does the expression x %= 10 do? a. Adds 10 to the value of x, and stores the result in x. b. Divides x by 10 and stores the remainder in x. c. Divides x by 10 and stores the integer result in x. d. None of the above. ANS: b. Divides x by 10 and stores the remainder in x.
Section 4.12 Increment and Decrement Operators 4.12 Q1: Which of the following operators associates from left to right? a. = b. ?: c. %= d. / ANS: d. / ..
4.12 Q2: What is the result value of c at the end of the following code segment? int c = 8; c++; ++c; c %= 5;
a. 0. b. 1. c. 3. d. None of the above. ANS: a. 0.
Section 4.13 Primitive Types 4.13 Q1: Java is considered a strongly typed language because: a. The primitive types in Java are portable across all computer platforms that support Java. b. Java requires all variables to have a type before they can be used in a program. c. Instance variables of the primitive types are automatically assigned a default value. d. All of the above. ANS: b. Java requires all variables to have a type before they can be used in a program 4.13 Q2: Which of the following is not a primitive type? a. char b. float c. String d. int ANS: c. String 4.13 Q3: Which primitive type can hold the largest value? a. int b. long c. float d. double ANS: d. double 4.13 Q4: What is the size in bits of an int? a. 8 b. 16 c. 32 d. 64 ANS: c. 32
Section 4.14 (Optional) GUI and Graphics Case Study: Creating Simple Drawings 4.14 Q1: In Java graphics, coordinate units are measured in ________. a. pixlets. ..
b. pixels. c. points. d. pikels. ANS: b. pixels. 4.14 Q2: Keyword ________ indicates the inheritance relationship. a. extends b. inherits c. super d. parent ANS: a. extends
..
Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition 5.2 Q1: Counter-controlled repetition requires a. A control variable and initial value. b. A control variable increment (or decrement). c. A condition that tests for the final value of the control variable. d. All of the above. ANS: d. All of the above. 5.2 Q2: The control variable of a counter-controlled loop should be declared as ________to prevent errors. a. int. b. float. c. double. d. Any of the above. ANS: a. int.
Section 5.3 for Repetition Statement 5.3 Q1: Consider the following two Java code segments: Segment 1 int i = 0; while ( i < 20 ) { i++; System.out.println( i ); }
Segment 2 for ( int i = 0; i <= 20; i++ ) { System.out.println( i ); }
Which of the following statements are true? a. The output from these segments is not the same. b. The scope of the control variable i is different for the two segments. c. Both (a) and (b) are true. d. Neither (a) nor (b) is true. ANS: c. Both (a) and (b) are true. 5.3 Q2: Consider the classes below: public class TestA { public static void main( String args[] ) { int x = 2, y = 20, counter = 0; for ( int j = y % x; j < 100; j += ( y / x ) ) counter++; } // end main } // end class TestA public class TestB { public static void main(String args[]) ..
{ int counter = 0; for ( int j = 10; j > 0; --j ) ++counter; } // end main } // end class TestB Which of the following statements is true? a. The value of counter will be different at the end of each for loop for each class. b. The value of j will be the same for each loop for all iterations c. Both (a) and (b) are true. d. Neither (a) nor (b) is true. ANS: d. Neither (a) nor (b) is true.
Section 5.4 Examples Using the for Statement 5.4 Q1: Which of the following for-loop control headers results in equivalent numbers of iterations: A. for ( int q = 1; q <= 100; q++ ) B. for ( int q = 100; q >= 0; q-- ) C. for ( int q = 99; q > 0; q -= 9 ) D. for ( int q = 990; q > 0; q -= 90 ) a. A and B. b. C and D. c. A and B have equivalent iterations and C and D have equivalent iterations. d. None of the loops have equivalent iterations. ANS: b. C and D. 5.4 Q2: Which of the following will count down from 10 to 1 correctly? a. for ( int j = 10; j <= 1; j++ ) b. for ( int j = 1; j <= 10; j++ ) c. for ( int j = 10; j > 1; j-- ) d. for ( int j = 10; j >= 1; j-- ) ANS: d. for ( int j = 10; j >= 1; j-- )
Application: Summing the Even Integers from 2 to 20 5.4 Q3: Which of the following is equivalent to this code segment? int total = 0; for ( int i = 0; i <= 20; i += 2 ) total += i; a. int total = 0; for ( int i = 20; i < 0; i += 1 ) total += i; b. int total = 0; for ( int i = 0; i <= 20; total += i, i += 2 ); c. int total = 0; for ( int i = 0, i <= 20, total += i; i += 2 ); d. int total = 0; for ( int i = 2; i < 20; total += i, i += 2 ); ..
ANS: b. int total = 0; for ( int i = 0; i <= 20; total += i, i += 2 )
Application: Compound Interest Calculations 5.4 Q4: Which statement prints the floating-point value 123.456 right justified with a field width of 10? a. System.out.printf( “%d10.3”, 123.456 ); b. System.out.printf( “%10.3d”, 123.456 ); c. System.out.printf( “%f10.3”, 123.456 ); d. System.out.printf( “%10.3f”, 123.456 ); ANS: d. System.out.printf( “%10.3f”, 123.456 ); 5.4 Q5: Which formatting flag indicates that the floating-point values should be output with a thousands separator? a. plus (+). b. minus (-). c. comma (,). d. period (.). ANS: c. comma (,).
Section 5.5 do…while Repetition Statement 5.5 Q1: Which of the following statements about a do…while repetition statement is true? a. The body of a do…while loop is executed only if the terminating condition is true. b. The body of a do…while loop is executed only once. c. The body of a do…while loop is always executed at least once. d. None of the above ANS: c. The body of a do…while loop is always executed at least once. 5.5 Q2: Which of the following will not help prevent infinite loops? a. Include braces around the statements in a do…while statement. b. Ensure that the header of a for or while statement is not followed by a semicolon. c. If the loop is counter-controlled, the body of the loop should increment or decrement the counter as needed. d. If the loop is sentinel-controlled, ensure that the sentinel value is input eventually. ANS: a. Include braces around the statements in a do…while statement.
Section 5.6 switch Multiple-Selection Statement GradeBook Class with switch Statement to Count A, B, C, D and F Grades 5.6 Q1: For the two code segments below: Segment A int q = 5; switch( q ) { case 1: System.out.println( 1 ); ..
case 2: System.out.println( 2 ); case 3: System.out.println( 3 ); case 4: System.out.println( 4 ); case 5: System.out.println( 5 ); default: System.out.println( "default" ); } // end switch Segment B q = 4; switch( q ) { case 1: System.out.println( 1 ); case 2: System.out.println( 2 ); case 3: System.out.println( 3 ); case 4: System.out.println( 4 ); case 5: System.out.println( 5 ); default: System.out.println( "default" ); } // end switch Which of the following statements is true? a. The output for Segment A is: default b. The output for Segment B is: 4 c. The output for Segment B is: 45default d. The output for Segment A is: 5 default ANS: d. The output for Segment A is: 5 default 5.6 Q2: For the code segment below: switch( q ) { case 1: System.out.println( "apple" ); break; case 2: System.out.println( "orange" ); break; case 3: System.out.println( "banana" ); break; case 4: System.out.println( "pear" ); case 5: System.out.println( "grapes" ); ..
default: System.out.println( "kiwi" ); } // end switch Which of the following values for q will result in kiwi being included in the output? a. 2. b. Anything greater than or equal to 4. c. 1. d. 3. ANS: b. Anything greater than or equal to 4.
switch Statement UML Activity Diagram 5.6 Q1: Which of the following can be used in a switch statement in the expression after keyword case? A. a constant integral expression. B. a character constant. C. a string (but only in Java SE 7). D. an enumeration constant. a. A and B. b. A and C. c. B and C. d. All. ANS: d. All.
Using Strings in switch Statements (New in Java SE 7) 5.6 Q1: Which of the following statements about the switch statement (as used in Java SE 7) is false? a. You can use Strings in a switch statement's controlling expression. b. You can use a String in a switch statement's case label. c. You can use a comma-separated list of Strings in a switch statement's case label. d. You cannot use a String in a switch statement's default case. ANS: c. You can use a comma-separated list of Strings in a switch statement's case label.
Section 5.7 break and continue Statements break Statement 5.7 Q1: Which of the following statements about the break statement is false? e. The break statement is used to exit a repetition structure early and continue execution after the loop. f. A break statement can only break out of an immediately enclosing while, for, do…while or switch statement. g. The break statement, when executed in a while, for or do…while, skips the remaining statements in the loop body and proceeds with the next iteration of the loop. h. Common uses of the break statement are to escape early from a loop or to skip the remainder of a switch. ANS: c. The break statement, when executed in a while, for or do…while, skips the remaining statements in the loop body and proceeds with the next iteration of the loop.
..
continue Statement 5.7 Q2: Which of the following statements about the continue statement is true? a. The continue statement is used to exit a repetition structure early and continue execution after the loop. b. The continue statement is used to continue after a switch statement. c. The continue statement does not alter the flow of control. d. A continue statement proceeds with the next iteration of the immediately enclosing while, for, do…while statement. ANS: d. A continue statement proceeds with the next iteration of the immediately enclosing while, for, do…while statement. 5.7 Q3: To exit out of a loop completely, and resume the flow of control at the next line in the method, use _______. a. A continue statement. b. A break statement. c. A return statement. d. Any of the above. ANS: b. A break statement.
Section 5.8 Logical Operators Conditional OR (||) Operator 5.8 Q1: Consider the code segment below. if ( gender == 1 ) { if ( age >= 65 ) ++seniorFemales; } // end if This segment is equivalent to which of the following? a. if ( gender == 1 || age >= 65 ) ++seniorFemales; b. if ( gender == 1 && age >= 65 ) ++seniorFemales; c. if ( gender == 1 AND age >= 65 ) ++seniorFemales; d. if ( gender == 1 OR age >= 65 ) ++seniorFemales; ANS: b. if ( gender == 1 && age >= 65 ) ++seniorFemales;
Short-Circuit Evaluation of Complex Conditions 5.8 Q2: Suppose variable gender is MALE and age equals 60, how is the expression ( gender == FEMALE ) && ( age >= 65 ) evaluated? a. The condition ( gender == FEMALE ) is evaluated first and the evaluation stops immediately. ..
b. The condition ( age >= 65 ) is evaluated first and the evaluation stops immediately. c. Both conditions are evaluated, from left to right. d. Both conditions are evaluated, from right to left. ANS: a. The condition ( gender == FEMALE ) is evaluated first and the evaluation stops immediately.
Boolean Logical AND (&) and Boolean Logical OR (|) Operators 5.8 Q3: Which case of the following would warrant using the boolean logical inclusive OR (|) rather than the conditional OR (||)? a. Testing if two conditions are both true. b. Testing if at least one of two conditions is true. c. Testing if at least one of two conditions is true when the right operand has a required side effect. d. Testing if at least one of two conditions is true when the left operand has a required side effect. ANS: c. Testing if at least one of two conditions is true when the right operand has a required side effect.
Logical Negation (!) Operator 5.8 Q4: Which expression is equivalent to if ( ! ( grade == sentinelValue ) )? a. if ( grade !== sentinelValue ). b. if ( grade != sentinelValue ). c. ! if ( grade == sentinelValue ). d. ! if ( grade !== sentinelValue ). ANS: b. if ( grade != sentinelValue ).
Logical Operators Example 5.8 Q5: The boolean values can be displayed with the ________ format specifier. a. %bool. b. %b. c. %true. d. %boolean. ANS: b. %b.
Section 5.9 Structured Programming Summary 5.9 Q1: Which statement below is false? a. Structured programming produces programs that are easier to test. b. Structured programming requires four forms of control. c. Structured programming produces programs that are easier to modify d. Structured programming promotes simplicity. ANS: b. Structured programming requires four forms of control. (Only three forms are necessary: sequence, selection, repetition) 5.9 Q2: Which of the following is not a type of repetition statement in Java? a. while statement. b. do…while statement. c. for statement. ..
d. loop statement. ANS: d. loop statement.
Section 5.10 (Optional) GUI and Graphics Case Study: Drawing Rectangles and Ovals 5. 10 Q1: Method drawOval’s arguments specify ________. a. the upper-left and upper-right corners of the oval. b. the upper-left corner, scale and size of the oval. c. the position and size of the bounding rectangle for the oval. d. the position and size of the bounding cycle for the oval. ANS: c. the position and size of the bounding rectangle for the oval. 5.10 Q2: The first statement in every paintComponent method should be a call to ________. a. super b. super.paintComponent c. clear d. update ANS: b. super.paintComponent
..
Chapter 6 Methods: A Deeper Look Section 6.2 Program Modules in Java 6.2 Q1: Information is passed to a method in: a. the method name. b. that method's return. c. the method body. d. the arguments to the method. ANS: d. the arguments to the method. 6.2 Q2: Programs designed for maintainability are constructed from small simple pieces or modules. Modules in Java are called: a. methods. b. classes. c. arguments. d. both methods and classes. ANS: d. both methods and classes 6.2 Q3: A well-designed method a. performs multiple unrelated tasks. b. repeats code found in other methods. c. contains thousands of lines of code. d. performs a single, well-defined task. ANS: d. performs a single, well-defined task.
Section 6.3 static Methods, static Fields and Class Math 6.3 Q1: To declare a method as static, place the keyword static before ________ in the method’s declaration. a. the method modifier. b. the return type. c. the method name. d. the argument list. ANS: b. the return type. 6.3 Q2: Which is a correct static method call of Math class method sqrt? a. sqrt( 900 );. b. math.sqrt( 900 );. c. Math.sqrt( 900 );. d. Math math = new Math(); math.sqrt( 900 );. ANS: c. Math.sqrt( 900 );.
..
6.3 Q3: Which of the following methods is not in the Math class? a. ceil. b. abs. c. parseInt. d. log. ANS: c. parseInt 6.3 Q4: Which of the following can be an argument to a method? a. Constants. b. Variables. c. Expressions. d. All of the above. ANS: d. All of the above. 6.3 Q5: Method log takes the logarithm of its argument with respect to what base? a. 10 b. e c. 2 d. pi ANS: b. e
Math Class Constants PI and E 6.3 Q6: Any field declared with keyword ________ is constant. a. static. b. const. c. constant. d. final. ANS: d. final.
Why Is Method main Declared static? 6.3 Q7: Declaring main as ________ allows the JVM to invoke main without creating an instance of the class. a. public. b. void. c. static. d. final. ANS: c. static.
Section 6.4 Declaring Methods with Multiple Parameters 6.4 Q1: Variables should be declared as fields only if ..
a. they are local variables. b. they are used only within a method. c. they are required for use in more than one method or their values must be saved between calls to the class’s methods. d. they are arguments. ANS: c. they are required for use in more than one method or their values must be saved between calls to the class’s methods. 6.4 Q2: Consider the following Java statements: int x = 9; double y = 5.3; result = calculateValue( x, y );
Which of the following statements is false? a. A method is called with its name and parentheses. b. x and y are parameters. c. Copies of x and y are passed to the method calculateValue. d. x and y are arguments. ANS: b. x and y are paramters. 6.4 Q3: The parameter list in the method header and the arguments in the method call must agree in: a. number b. type c. order d. all of the above ANS: d. all of the above
Assembling Strings with String Concatenation 6.4 Q4: Which operator can be used in string concatenation? a. *. b. +=. c. ++. d. =+. ANS: b. +=. 6.4 Q5: When an object is concatenated with a String: a. a compilation error occurs. b. a runtime error occurs. c. the object’s toString method is implicitly called to obtain the String representation of the object. d. the object’s class name is used. ANS: c. the object’s toString method is implicitly called to obtain the String representation of the object. ..
Section 6.5 Notes on Declaring and Using Methods 6.5 Q1: A static method can ________. a. call only other static methods of the same class directly. b. manipulate only static fields in the same class directly. c. be called using the class name and a dot (.). d. All of the above. ANS: d. All of the above. 6.5 Q2: Which statement is false? a. If a method does not return a value, the return-value-type in the method declaration can be omitted. b. Placing a semicolon after the right parenthesis enclosing the parameter list of a method declaration is a syntax error. c. Redeclaring a method parameter as a local variable in the method’s body is a compilation error. d. Forgetting to return a value from a method that should return a value is a compilation error. ANS: a. If a method does not return a value, the return-value-type in the method declaration can be omitted.
Section 6.6 Method Call Stack and Activation Records 6.6 Q1: Stacks are known as ________ data structures. a. FIFO. b. FILO. c. LIFO. d. LILO. ANS: c. LIFO. 6.6 Q2: If more method calls occur than can have their activation records stored on the program execution stack, an error known as a ________ occurs. a. stack overflow. b. stack rewind. c. stack full. d. stack empty. ANS: a. stack overflow.
Section 6.7 Argument Promotion and Casting 6.7 Q1: Which of the following promotions of primitive types is not allowed to occur? a. char to int. b. int to double. ..
c. short to long. d. double to float. ANS: d. double to float. 6.7 Q2: Which of the following primitive types is never promoted to another type? a. double. b. byte. c. boolean. d. Both a and c. ANS: d. Both a and c.
Section 6.8 Java API Packages 6.8 Q1: Which statement is not true. a. The Java API consists of packages. b. The Java API helps programmers avoid "reinventing the wheel." c. The Java API consists of import declarations. d. The class javax.swing.JApplet is part of the Java API. ANS: c. The Java API consists of import declarations. (The Java API is built from packages.) 6.8 Q2: Which of the following is not a package in the Java API? a. java.component. b. java.awt. c. javax.swing.event. d. java.lang. ANS: a. java.component. 6.8 Q3: The java.text package contains classes for manipulating all of the following items except a. classes b. numbers c. strings d. characters ANS: a. classes
Section 6.9 Case Study: Random-Number Generation 6.9 Q1: Math static method random generates a random double value in the range from 0.0 a. up to but not including 1.0 b. up to and including 1.0 c. up to and including 100.0 d. up to but not including 100.0 ANS: a. up to but not including 1.0 6.9 Q2: Which statement below could be used to simulate the outputs of tossing a quarter to get heads or tails? Suppose randomNumbers is a Random object. ..
a. randomNumbers.nextInt( 7 ); b. randomNumbers.nextInt( 2 ); c. randomNumbers.nextInt( 1 ); d. randomNumbers.nextInt( 25 ); ANS: b. randomNumbers.nextInt( 2 );
Rolling a Six-Sided Die 6.9 Q3: Which statement below could be used to simulate the outputs of rolling a sixsided die? Suppose randomNumbers is a Random object. a. 1 + randomNumbers.nextInt( 6 ); b. 1 + randomNumbers.nextInt( 2 ); c. 6 + randomNumbers.nextInt( 1 ); d. 3 + randomNumbers.nextInt( 3 ); ANS: a. 1 + randomNumbers.nextInt( 6 );
Section 6.9.1 Generalized Scaling and Shifting of Random Numbers 6.9.1 Q1: Which statement creates a random value from the sequence 2, 5, 8, 11 and 14. Suppose randomNumbers is a Random object. a. 2 + 5 * randomNumbers.nextInt( 3 ); b. 3 + 2 * randomNumbers.nextInt( 5 ); c. 5 + 3 * randomNumbers.nextInt( 2 ); d. 2 + 3 * randomNumbers.nextInt( 5 ); ANS: d. 2 + 3 * randomNumbers.nextInt( 5 );
Section 6.9.2 Random-Number Repeatability for Testing and Debugging 6.9.2 Q1: You can set a Random object’s seed at any time during program execution by calling the object’s ________ methods. a. changeSeed. b. setSeed. c. resetSeed. d. updateSeed. ANS: b. setSeed.
Section 6.10 Case Study: A Game of Chance (Introducing Enumerations) 6.10 Q1: An enumeration is a special class that's introduced by the keyword ________ and a type name. a. class. b. enum. c. enumeration. d. classEnum. ..
ANS: b. enum. 6.10 Q2: The identifiers in an enumeration ________. a. must be unique. b. may be duplicated. c. must be lowercase letters and cannot contain numbers. d. must be uppercase letters and cannot contain numbers. ANS: a. must be unique.
Section 6.11 Scope of Declarations 6.11 Q1: Identifiers in Java have ________ and ________ scopes? a. method, class. b. class, block. c. block, statement. d. statement, file. ANS: b. class, block. 6.11 Q2: Which of the following statements describes block scope? a. It begins at the opening { of the class declaration and terminates at the closing } b. It limits label scope to only the method in which it is declared. c. It begins at the identifier's declaration and ends at the terminating right brace (}). d. It is valid for one statement only. ANS: c. It begins at the identifier's declaration and ends at the terminating right brace (}). 6.11 Q3: Which of these statements best defines scope? a. Scope refers to the classes that have access to a variable. b. Scope determines whether a variable’s value can be altered. c. Scoping allows the programmer to use a class without using its fully qualified name. d. Scope is the portion of a program that can refer to an entity by its simple name. ANS: d. Scope is the portion of a program that can refer to an entity by its simple name.
Section 6.12 Method Overloading 6.12 Q1: Overloaded methods always have the same _________. a. method name. b. return type. c. number of parameters. d. order of the parameters. ANS: a. method name. 6.12 Q2: An overloaded method is one that a. has a different name than another method, but the same parameters. b. has the same name as another method, but different parameters (by number, types or order of the types). c. has the same name and parameters as a method defined in another class. d. has the same name and parameters, but a different return type as another method. ..
ANS: b. has the same name as another method, but different parameters (by number, types or order of the types).
Declaring Overloaded Methods 6.12 Q3: Which of the following methods are overloaded with respect to one another? public int max ( int a, int b ) { … } public double max ( double a, double b ) { … } public int max ( int a, int b, int c ) { … } public double max ( double a, double b, double c ) { … }
a. A and B are overloaded; C and D are overloaded. b. A and C are overloaded; B and D are overloaded. c. A, B and C are overloaded. d. All these four methods are overloaded. ANS: d. All these four methods are overloaded.
Distinguishing Between Overloaded Methods 6.12 Q4: Suppose method1 is declared as void method1 ( int a, float b )
Which of the following methods correctly overloads method1? a. void method2 ( int a, float b ). b. void method2 ( float a, int b ). c. void method1 ( float a, int b ). d. void method1 ( int b, float a ). ANS: c. void method1 ( float a, int b ). 6.12 Q5: A Java class can have which of the following methods? A. void foo( int a ) B. void foo( int a, int b ) C. void foo( double a ) D. void foo( double a, double b ) E. void foo( int b )
a. All of the above. b. A, B, D, E. c. A, B, C, D. d. A, C, D, E. ANS: c. A, B, C, D.
Return Types of Overloaded Methods 6.12 Q6: Method calls cannot be distinguished by ________. ..
a. method name. b. return type. c. parameter lists. d. method signature. ANS: b. return type. 6.12 Q7: In a class containing methods with the same name, the methods are distinguished by: a. Number of arguments. b. Types of arguments. c. Return type. d. (a) and (b). e. (b) and (c). ANS: d. (a) and (b).
Section 6.13 (Optional) GUI and Graphics Case Study: Colors and Filled Shapes 6.13 Q1: Java uses class ________ to represent colors using their RGB values. a. Color. b. Colors. c. RGBColor. d. RGBColors. ANS: a. Color. 6.13 Q2: Filled rectangles and filled circles are drawn using Graphics method ________ and ________. a. fillRect, fillCircle. b. filledRect, filledCircle. c. fillRect, fillOval, d. filledRect, filledOval. ANS: c. fillRect, fillOval.
..
Chapter 7 Arrays and ArrayLists Section 7.1 Introduction 7.1 Q1: Arrays are: a. variable-length entities. b. fixed-length entities. c. data structures that contain up to 10 related data items. d. used to draw a sequence of lines, or “rays.” Ans: b. fixed-length entities.
Section 7.2 Arrays 7.2 Q1: Which of the following statements about arrays are true? A. An array is a group of variables containing values that all have the same type. B. Elements are located by index or subscript. C. The length of an array c is determined by the expression c.length();. D. The zeroth element of array c is specified by c[ 0 ]. a. A, C, D. b. A, B, D. c. C, D. d. A, B, C, D. Ans: b. A, B, D.
7.2 Q2: Consider the array: s[ 0 ] = 7 s[ 1 ] = 0 s[ 2 ] = -12 s[ 3 ] = 9 s[ 4 ] = 10 s[ 5 ] = 3 s[ 6 ] = 6
The value of s[ s[ 6 ] - s[ 5 ] ] is: a. 0. b. 3. c. 9. d. 0. Ans: c. 9.
..
Section 7.3 Declaring and Creating Arrays 7.3 Q1: A programmer must do the following before using an array: a. declare then reference the array. b. create then declare the array. c. create then reference the array. d. declare then create the array. Ans: d. declare then create the array.
7.3 Q2: Consider the code segment below. Which of the following statements is false? int[] g; g = new int[ 23 ];
a. The first statement declares an array reference. b. The second statement creates the array. c. g is a reference to an array of integers. d. The value of g[ 3 ] is -1. Ans: d. The value of g[ 3 ] is -1.
Section 7.4 Examples Using Arrays Creating and Initializing an Array 7.4 Q1: Which of the following statements about creating arrays and initializing their elements is false? a. The new keyword should be used to create an array. b. When an array is created, the number of elements must be placed in square brackets following the type of element being stored. c. The elements of an array of integers have a value of null before they are initialized. d. A for loop is commonly used to set the values of the elements of an array. Ans: c. The elements of an array of integers have a value of null before they are initialized.
7.4 Q2: What do the following statements do? double[] array; array = new double[ 14 ];
a. Create a double array containing 13 elements. b. Create a double array containing 14 elements. c. Create a double array containing 15 elements. d. Declare but do not create a double array. ..
Ans: b. Create a double array containing 14 elements.
Using an Array Initializer 7.4 Q3: Which of the following initializer lists would correctly set the elements of array n? a. int[] n = { 1, 2, 3, 4, 5 };. b. array n[ int ] = { 1, 2, 3, 4, 5 };. c. int n[ 5 ] = { 1; 2; 3; 4; 5 };. d. int n = new int( 1, 2, 3, 4, 5 );. Ans: a. int[] n = { 1, 2, 3, 4, 5 };.
Calculating a Value to Store in Each Array Element 7.4 Q4: Constant variables also are called a. write-only variables. b. finals. c. named constants. d. All of the above. Ans: c. named constants.
.
7.4 Q5: Which of the following will not produce a compiler error? a. Changing the value of a constant after it is declared. b. Changing the value at a given index of an array after it is created. c. Using a final variable before it is initialized. d. All of the above will produce compiler errors. Ans: b. Changing the value at a given index of an array after it is created.
Summing the Elements of an Array 7.4 Q6: Consider the program below: public class Test { public static void main( String[] args ) { int[] a; a = new int[ 10 ]; for ( int i = 0; i < a.length; i++ ) a[ i ] = i + 2; ..
int result = 0; for ( int i = 0; i < a.length; i++ ) result += a[ i ]; System.out.printf( "Result is: %d\n", result ); } // end main } // end class Test
The output of this program will be: a. Result is: 62. b. Result is: 64. c. Result is: 65. d. Result is: 67. Ans: c. Result is: 65.
7.4 Q7: Consider the class below: public class Test { public static void main( String[] args ) { int[] a = { 99, 22, 11, 3, 11, 55, 44, 88, 2, -3 }; int result = 0; for ( int i = 0; i < a.length; i++ ) { if ( a[ i ] > 30 ) result += a[ i ]; } // end for System.out.printf( "Result is: %d\n", result ); } // end main } // end class Test
The output of this Java program will be: a. Result is: 280. b. Result is: 154. c. Result is: 286. d. Result is: 332. Ans: c. Result is: 286.
Using Bar Charts to Display Array Data Graphically 7.4 Q8: Which flag in a format specifier indicates that values with fewer digits than the field width should begin with a leading 0? ..
a. p. b. l. c. w. d. 0. Ans: d. 0.
Using the Elements of an Array as Counters 7.4 Q9: Invalid possibilities for array indices include a. Positive integers. b. Negative integers. c. Zero. d. None of the above. Ans: b. Negative integers.
.
Using Arrays to Analyze Survey Results 7.4 Q10: Which expression adds 1 to the element of array arrayName at index i? a. ++arrayName[ i ]. b. arrayName++[ i ]. c. arrayName[ i++ ]. d. None of the above. Ans: a. ++arrayName[ i ].
7.4 Q11: Attempting to access an array element out of the bounds of an array, causes a(n) . a. ArrayOutOfBoundsException. b. ArrayElementOutOfBoundsException. c. ArrayIndexOutOfBoundsException. d. ArrayException. Ans: c. ArrayIndexOutOfBoundsException.
7.4 Q12: Which of the following statements is false? a. An exception indicates a problem that occurs while a program executes. b. Exception handling enables you to create fault-tolerant programs that can resolve (or handle) exceptions—in many cases, this allows a program to continue executing as if no problems were encountered. c. The catch block contains the code that might throw an exception, and the try block contains the code that handles the exception if one occurs. d. Inside the catch block, you can use the parameter’s identifier to interact with a ..
caught exception object. Ans: c. The catch block contains the code that might throw an exception, and the try block contains the code that handles the exception if one occurs.
Section 7.5 Case Study: Card Shuffling and Dealing Simulation Class DeckOfCards 7.5 Q1: Consider integer array values, which contains 5 elements. Which statements successfully swap the contents of the array at index 3 and index 4? a. values[ 3 ] = values[ 4 ]; values[ 4 ] = values[ 3 ];
b. values[ 4 ] = values[ 3 ]; values[ 3 ] = values[ 4 ];
c. int temp = values[ 3 ]; values[ 3 ] = values[ 4 ]; values[ 4 ] = temp;
d. int temp = values[ 3 ]; values[ 3 ] = values[ 4 ]; values[ 4 ] = values[ 3 ];
Ans: c. int temp = values[ 3 ]; values[ 3 ] = values[ 4 ]; values[ 4 ] = temp;
7.5 Q2: In this question, assume a class, Book, has been defined. Which set of statements creates an array of Book objects? a. Book[] books; books = new Book[ numberElements ]; ..
b. Book[] books]; books = new Book()[ numberElements ];
c. new Book() books[]; books = new Book[ numberElements ];
d. All of the above. Ans: a. Book[] books; books = new Book[ numberElements ];
Section 7.6 Enhanced for Statement 7.6 Q1: Assume array items contains the integer values 0, 2, 4, 6 and 8. Which of the following set of statements uses the enhanced for loop to display each value in array items? a. for ( int i = 0; i < items.length; i++ ) System.out.prinf( "%d\n", items[ i ] );
b. for ( int i : items ) System.out.prinf( "%d\n", items[ i ] );
c. for ( int i : items ) System.out.prinf( "%d\n", i );
d. for ( int i = 0 : items.length ) System.out.prinf( "%d\n", items[ i ] );
Ans: c. for ( int i : items ) System.out.prinf( "%d\n", i );
7.6 Q2: Which of the following tasks cannot be performed using an enhanced for ..
loop? a. Calculating the product of all the values in an array. b. Displaying all even element values in an array. c. Comparing the elements in an array to a specific value. d. Incrementing the value stored in each element of the array. Ans: d. Incrementing the value stored in each element of the array.
Section 7.7 Passing Arrays to Methods 7.7 Q1: Which statement correctly passes the array items to method takeArray? Array items contains 10 elements. a. takeArray( items[] ). b. takeArray( items ). c. takeArray( items[ 9 ] ). d. Arrays cannot be passed to methods—each item must be sent to the method separately. Ans: b. takeArray( items ).
7.7 Q2: Consider array items, which contains the values 0, 2, 4, 6 and 8. If method changeArray is called with the method call changeArray( items, items[ 2 ] ) , what values are stored in items after the method has finished executing? public static void changeArray( int[] passedArray, int value ) { passedArray[ value ] = 12; value = 5; } // end method changeArray
a. 0, 2, 5, 6, 12. b. 0, 2, 12, 6, 8. c. 0, 2, 4, 6, 5. d. 0, 2, 4, 6, 12. Ans: d. 0, 2, 4, 6, 12.
Notes on Passing Arguments to Methods 7.7 Q3: When an argument is passed by reference: a. a copy of the argument’s value is passed to the called method. b. changes to the argument do not affect the original variable’s value in the caller. c. the called method can access the argument’s value in the caller directly and modify that data. d. the original value is removed from memory. ..
Ans: c. the called method can access the argument’s value in the caller directly and modify that data.
Section 7.8 Case Study: Class GradeBook Using an Array to Store Grades Class GradeBookTest That Demonstrates Class GradeBook 7.8 Q1: What kind of application tests a class by creating an object of that class and calling the class’s methods? a. Pseudo application. b. Debugger. c. Tester. d. Test harness. Ans: d. Test harness.
Section 7.9 Multidimensional Arrays 7.9 Q1: In Java, multidimensional arrays: a. are not directly supported. b. are implemented as arrays of arrays. c. are often used to represent tables of values. d. All of the above. Ans: d. All of the above.
7.9 Q2: In array items, which expression below accesses the value at row 3 and column 4? a. items[ 3 ].[ 4 ]. b. items[ 3[ 4 ] ]. c. items[ 3 ][ 4 ]. d. items[ 3, 4 ]. Ans: d. All of the above.
7.9 Q3: An array with m rows and n columns is not: A. An m-by-n array. B. An n-by-m array. C. A two-dimensional array. D. A dual-transcripted array. ..
a. A and C. b. A and D. c. B and D. d. B and C. Ans: c. B and D.
Arrays of One-Dimensional Arrays 7.9 Q4: Which statement below initializes array items to contain 3 rows and 2 columns? a. int[][] items = { { 2, 4 }, { 6, 8 }, { 10, 12 } };. b. int[][] items = { { 2, 6, 10 }, { 4, 8, 12 } };. c. int[][] items = { 2, 4 }, { 6, 8 }, { 10, 12 };. d. int[][] items = { 2, 6, 10 }, { 4, 8, 12 };. Ans: a. int[][] items = { { 2, 4 }, { 6, 8 }, { 10, 12 } };.
7.9 Q5: For the array in the previous question, what is the value returned by items[ 1 ][ 0 ]? a. 4. b. 8. c. 12. d. 6. Ans: d. 6.
Two-Dimensional Arrays with Rows of Different Lengths 7.9 Q6: Which of the following statements creates a multidimensional array with 3 rows, where the first row contains 1 element, the second row contains 4 elements and the final row contains 2 elements? a. int[][] items = { { 1, null, null, null }, { 2, 3, 4, 5 }, { 6, 7, null, null } };. b. int[][] items = { { 1 }, { 2, 3, 4, 5 }, { 6, 7 } };. c. int[][] items = { { 1 }, { 2, 3, 4, 5 }, { 6, 7 }, {} );. d. int[][] items = { { 1 }, { 4 }, { 2 } };. Ans: b. int[][] items = { { 1 }, { 2, 3, 4, 5 }, { 6, 7 } };.
Creating Two-Dimensional Arrays with Array-Creation Expressions 7.9 Q7: Which of the following sets of statements creates a multidimensional array ..
with 3 rows, where the first row contains 1 value, the second row contains 4 items and the final row contains 2 items? a. int[][] items; items = new int[ 3 ][ ? ]; items[ 0 ] = new int[ 1 ]; items[ 1 ] = new int[ 4 ]; items[ 2 ] = new int[ 2 ];
b. int[][] items; items = new int[ 3 ][ ]; items[ 0 ] = new int[ 1 ]; items[ 1 ] = new int[ 4 ]; items[ 2 ] = new int[ 2 ];
c. int[][] items; items = new int[ ? ][ ? ]; items[ 0 ] = new int[ 1 ]; items[ 1 ] = new int[ 4 ]; items[ 2 ] = new int[ 2 ];
d. int[][] items; items[ 0 ] = new int[ 1 ]; items[ 1 ] = new int[ 4 ]; items[ 2 ] = new int[ 2 ];
Ans: b. int[][] items; items = new int[ 3 ][ ]; items[ 0 ] = new int[ 1 ]; items[ 1 ] = new int[ 4 ]; items[ 2 ] = new int[ 2 ];
Two-Dimensional Array Example: Displaying Element Values 7.9 Q8: The preferred way to traverse a two-dimensional array is to use a. a do while statement. b. a for statement. c. two nested for statements. ..
.
d. three nested for statements. Ans: c. two nested for statements.
Common Multidimensional-Array Manipulations Performed with for Statements 7.9 Q9: Which set of statements totals the items in each row of two-dimensional array items, and displays each total? a. int total = 0; for ( int row = 0; row < items.length; row++ ) { total = 0; for ( int column = 0; column < a[ row ].length; column++ ) total += a[ row ][ column ]; System.out.printf( "%d\n", total ); }
b. int total = 0; for ( int row = 0; row < items.length; row++ ) { for ( int column = 0; column < a[ row ].length; column++ ) total += a[ row ][ column ]; System.out.printf( "%d\n", total ); }
c. int total = 0; for ( int row = 0; row < items.length; row++ ) { for ( int column = 0; column < a[ column ].length; column++ ) total += a[ row ][ column ]; System.out.printf( "%d\n", total ); }
d. int total = 0; ..
for ( int row = 0; row < items.length; row++ ) { total = 0; for ( int column = 0; column < a[ column ].length; column++ ) total += a[ row ][ column ]; System.out.printf( "%d\n", total ); }
Ans: a. int total = 0; for ( int row = 0; row < items.length; row++ ) { total = 0; for ( int column = 0; column < a[ row ].length; column++ ) total += a[ row ][ column ]; System.out.printf( "%d\n", total ); }
Section 7.10 Case Study: Class GradeBook Using a Two-Dimensional Array Storing Student Grades in a Two-Dimensional Array in Class GradeBook 7.10 Q1: Which set of statements totals the values in two-dimensional int array items? a. int total = 0; for ( int subItems : items ) for ( int item : subItems ) total += item;
b. int total = 0; for ( int item: int[] subItems : items ) total += item; ..
c. int total = 0; for ( int[] subItems : items ) for ( int item : items ) total += item;
d. int total = 0; for ( int[] subItems : items ) for ( int item : subItems ) total += item;
Ans: d. int total = 0; for ( int[] subItems : items ) for ( int item : subItems ) total += item;
Section 7.11 Variable-Length Argument Lists 7.11 Q1: An argument type followed by a(n) in a method’s parameter list indicates that the method receives a variable number of arguments of that particular type. a. square brackets ([]). b. ellipsis (…). c. varargs keyword. d. All of the above are acceptable to indicate a variable number of arguments. Ans: b. ellipsis (…).
Section 7.12 Using Command-Line Arguments 7.12 Q1: Which command below runs TestProgram, and passes in the values files.txt and 3? a. java TestProgram files.txt 3. b. java TestProgram files.txt, 3. c. java TestProgram "files.txt", "3". d. java TestProgram (the arguments files.txt and 3 were passed in when the application was compiled). Ans: a. java TestProgram files.txt 3. ..
7.12 Q2: Which method call converts the value in variable stringVariable to an integer? a. Convert.toInt( stringVariable ). b. Convert.parseInt( stringVariable ). c. Integer.parseInt( stringVariable ). d. Integer.toInt( stringVariable ). Ans: c. Integer.parseInt( stringVariable ).
Section 7.13 Class Arrays 7.13 Q1: Class Arrays methods sort, binarySearch, equals and fill are overloaded for primitive-type arrays and Object arrays. In addition, methods __________ and __________ are overloaded with generic versions. a. sort, binarySearch. b. sort, fill. c. binarySearch, equals. d. binarySearch, fill. ANS: c. binarySearch, equals. 7.13 Q2: Class Arrays provides method __________ for comparing arrays. a. compare. b. compares. c. equal. d. equals. ANS: d. equals.
Section 7.14 Introduction to Collections and Class ArrayList 7.14 Q1: Class ________ represents a dynamically resizable array-like data structure. a. Array. b. ArrayList. c. Arrays. d. None of the above. ANS: b. ArrayList. 7.14 Q1: Which of the following is false?
a. The size of an ArrayList can be determined via its length instance variable. b. The size of an ArrayList can be determined via its size method. c. You can add a new item to the end of an ArrayList with its add method. c. You can get an item from a specified index in an ArrayList with its get method. Ans: a. ..
Section 7.15 (Optional) GUI and Graphics Case Study: Drawing Arcs 7.13 Q1: Which method sets the background color of a JPanel? a. setBack. b. setBackground. c. setBackgroundColor. d. setColor. Ans: b.
7.13 Q2: Which of the following statements about an arc is false? a. An arc is a section of an oval. b. The sweep is the amount of arc to cover. c. Method drawArc draws the edges of an arc. d. The fillArc method draws an oval, with the section that is an arc filled in. Ans: d. The fillArc method draws an oval, with the section that is an arc filled in.
..
Chapter 8 Classes and Objects: A Deeper Look Section 8.2 Time Class Case Sudy Time1 Class Declaration 8.2 Q1: The _________ of a class are also called the public services or the public interface that the class provides to its clients. a. public constructors. b. public instance variables. c. public methods. d. All of the above. ANS: c. public methods. 8.2 Q2: The static method ________ of class String returns a formatted String. a. printf. b. format. c. formatString. d. toFormatString. ANS: b. format.
Notes on the Time1 Class Declaration 8.2 Q3: Which statement is false? a. The actual data representation used within the class is of no concern to the class’s clients. b. Clients generally care about what the class does but not how the class does it. c. Clients are usually involved in a class’s implementation. d. Hiding the implementation reduces the possibility that clients will become dependent on classimplementation details. ANS: c: Clients are usually involved in a class’s implementation.
Section 8.3 Controlling Access to Members 8.3 Q1: Which of the following should usually be private? a. Methods. b. Constructors. c. Variables (or fields). d. All of the above. ANS: c. Variables (or fields). 8.3 Q2: Which of the following statements is true? a. Methods and instance variables can both be either public or private. b. Information hiding is achieved by restricting access to class members via keyword public. c. The private members of a class are directly accessible to the client of a class. d. None of the above is true. ANS: a. Methods and instance variables can both be either public or private.
Section 8.4: Referring to the Current Object’s Member with the this Reference 8.4 Q1: When should a program explicitly use the this reference? a. Accessing a private variable. ..
b. Accessing a public variable. c. Accessing a local variable. d. Accessing a field that is shadowed by a local variable. ANS: c. Accessing a field that is shadowed by a local variable. 8.4 Q2: Having a this reference allows: a. a method to refer explicitly to the instance variables and other methods of the object on which the method was called. b. a method to refer implicitly to the instance variables and other methods of the object on which the method was called. c. an object to reference itself. d. All of the above. ANS: d. All of the above.
Section 8.5 Time Class Case Study: Overloaded Constructors 8.5 Q1: A constructor cannot: a. be overloaded. b. initialize variables to their defaults. c. specify return types or return values. d. have the same name as the class. ANS: c. specify return types or return values.
Class Time2 with Overloaded Constructors 8.5 Q2: Constructors: a. Initialize instance variables. b. When overloaded, can have identical argument lists. c. When overloaded, are selected by number, types and order of types of parameters. d. a and c. ANS: d. a and c.
Class Time2’s Constructors 8.5 Q3: A programmer-defined constructor that has no arguments is called a(n) ________. a. empty constructor. b. no-argument constructor. c. default constructor. d. null constructor. ANS: b. no-argument constructor. 8.5 Q4: What happens when this is used in a constructor’s body to call another constructor of the same class if that call is not the first statement in the constructor? a. A compilation error occurs. b. A runtime error occurs. c. A logic error occurs. d. Nothing happens. The program compiles and runs. ANS: a. A compilation error occurs.
Notes Regarding Class Time2’s Set and Get Methods and Constructors 8.5 Q5: When implementing a method, use the class’s set and get methods to access the class’s ________ data. a. public. b. private. c. protected. ..
d. All of the above. ANS: b. private.
Section 8.6 Default and No-Argument Constructors 8.6 Q1: Which statement is false? a. The compiler always creates a default constructor for a class. b. If a class’s constructors all require arguments and a program attempts to call a no-argument constructor to initialize an object of the class, a compilation error occurs. c. A constructor can be called with no arguments only if the class does not have any constructors or if the class has a public no-argument constructor. d. None of the above. ANS: a. The compiler always creates a default constructor for a class.
Section 8.7 Notes on Set and Get Methods 8.7 Q1: Set methods are also commonly called ________ methods and get methods are also commonly called ________ methods. a. query, mutator. b. accessor, mutator. c. mutator, accessor. d. query, accessor. ANS: c. mutator, accessor.
Validity Checking in Set Methods 8.7 Q3: Using public set methods provides data integrity if: a. The instance variables are public. b. The instance variables are private. c. The methods perform validity checking. d. Both b and c. ANS: d. Both b and c.
Section 8.8 Composition 8.8 Q1: Composition is sometimes referred to as a(n) ________. a. is-a relationship. b. has-a relationship. c. many-in-one relationship. d. one-to-many relationship. ANS: b. has-a relationship.
Section 8.9 Enumerations 8.9 Q1: enum types are implicitly ________ and enum constants are implicitly ________. a. final, static. b. static, static. c. static, final. d. final, final. ANS: a. final, static. 8.9 Q2: Which statement is false? a. An enum declaration is a comma-separated list of enum constants and may optionally include other components of traditional classes, such as constructors, fields and methods. b. Any attempt to create an object of an enum type with operator new results in a compilation error. c. An enum constructor cannot be overloaded. d. An enum constructor can specify any number of parameters. ..
ANS: c. An enum constructor cannot be overloaded. 8.9 Q3: Which method returns an array of the enum’s constants? a. values. b. getValues. c. constants. d. getConstants. ANS: a. values.
Section 8.10 Garbage Collection and Method finalize 8.10 Q1: Which of the following is false? a. Method finalize does not take parameters and has return type void. b. Memory leaks using Java are rare because of automatic garbage collection. c. Objects are marked for garbage collection by method finalize. d. The garbage collector reclaims unused memory. ANS: c. Objects are marked for garbage collection by method finalize. (Objects are marked for garbage collection when there are no more references to the object).
Section 8.11 static Class Members 8.11 Q1: Static class variables: a. are final. b. are public. c. are private. d. are shared by all objects of a class. ANS: d. are shared by all objects of a class. 8.11 Q2: Which of the following is false? a. A static method must be used to access private static instance variables. b. A static method has no this reference. c. A static method can be accessed even when no objects of its class have been instantiated. d. A static method can call instance methods directly. ANS: d. A static method can call instance methods directly.
Section 8.12 static Import 8.12 Q1: Which syntax imports all static members of class Math? a. static import java.lang.Math.*. b. import static java.lang.Math.*. c. static import java.lang.Math. d. import static java.lang.Math. ANS: b. import static java.lang.Math.*.
Section 8.13 final Instance Variables 8.13 Q1: Instance variables declared final do not or cannot: a. Cause syntax errors if used as a left-hand value. b. Be initialized. c. Be modified. d. None of the above. ANS: c. Be modified. 8.13 Q2: A final field should also be declared ________ if it is initialized in its declaration. a. private. b. public. ..
c. protected. d. static. ANS: d. static.
Section 8.14 Time Class Case Study: Creating Packages 8.16 Q1: A package is: a. A directory structure used to organize classes and interfaces. b. A mechanism for software reuse. c. A group of related classes and interfaces. d. All of the above. ANS: d. All of the above.
Steps for Declaring a Reusable Class 8.16 Q2: A class within a package must be declared public if a. It will be used only by other classes in the same package. b. It will be used by classes that are not in the same package. c. It is in the same directory as the other classes in the package. d. It has a unique name. ANS: b. It will be used by classes that are not in the same package. Classes outside the package cannot use a class if the class is not declared public.
Step 3: Compiling the Packaged Class 8.16 Q4: When compiling a class in a package, the javac command-line option ________ causes the javac compiler to create appropriate directories based on the class’s package declaration. a. -p. b. -a. c. -d. d. -dir. ANS: c. -d.
Step 4: Importing the Reusable Class 8.16 Q5: The import declaration import java.util.*; is known as a ________. a. single-type-import declaration. b. all-type-import declaration. c. multiple-import declaration. d. type-import-on-demand declaration. ANS: d. type-import-on-demand declaration. 8.16 Q6: The import declaration import *; ________. a. causes a compilation error. b. imports all classes in the library. c. imports the default classes in the library. d. imports the classes in package java.lang. ANS: a. causes a compilation error.
Specifying the Classpath During Compilation 8.16 Q7: The classpath consists of a list of directories or archive files, each separated by a ________ on Windows or a ________ on UNIX/Linux/Max OS X. a. colon (:), semicolon (;). b. semicolon (;), colon (:). c. comma (,), semicolon (;). d. semicolon (;), comma (,). ANS: b. semicolon (;), colon (:). ..
8.16 Q8: By default, the classpath consists only of the ________. However, the classpath can be modified by providing the ________ option to the javac compiler. a. root directory of the package, -d. b. current directory, -d. c. root directory of the package, -classpath. d. current directory, -classpath. ANS: d. current directory, -classpath.
Section 8.15 Package Access 8.17 Q1: When no access modifier is specified for a method or variable, the method or variable: a. Is public. b. Is private. c. Has package access. d. Is static. ANS: c. Has package access.
..
Chapter 9 Object Oriented Programming: Inheritance Section 9.1 Introduction 9.1 Q1: Which of the following statements is false? a. A subclass is often larger than its superclass. b. A superclass object is a subclass object. c. The class following the extends keyword in a class declaration is the direct superclass of the class being declared. d. Java uses interfaces to provide the benefits of multiple inheritance. ANS: b. A superclass object is a subclass object. 9.1 Q2: Inheritance is also known as the a. “knows-a” relationship. b. “has-a” relationship. c. “uses-a” relationship. d. “is-a” relationship. ANS: d. “is-a” relationship
Section 9.2 Superclasses and Subclasses 9.2 Q1: Which of the following is not a superclass/subclass relationship? a. Ford/Taurus. b. University/Boston University. c. Sailboat/Tugboat. d. Country/USA. ANS: c. Sailboat/Tugboat. A Sailboat is not a superclass for Tugboats. Both sailboat and tugboats would be subclasses of Boat. 9.2 Q2: An advantage of inheritance is that: a. All methods can be inherited. b. All instance variables can be uniformly accessed by subclasses and superclasses. c. Objects of a subclass can be treated like objects of their superclass. d. None of the above. ANS: c. Objects of a subclass can be treated like objects of their superclass.
Section 9.3 protected Members 9.3 Q1: Which of the following keywords allows a subclass to access a superclass method even when the subclass has overridden the superclass method? a. base. b. this. c. public. d. super. ANS: d. super. 9.3 Q2: Using the protected keyword gives a member: a. public access. b. package access. c. private access. d. block scope. ANS: b. package access. 9.3 Q3: Superclass methods with this level of access cannot be called from subclasses. ..
a. private. b. public. c. protected. d. package. ANS: a. private.
Section 9.4 Relationship between Superclasses and Subclasses Section 9.4.1 Creating and Using a CommissionEmployee Class 9.4.1 Q1: Every class in Java, except ________, extends an existing class. a. Integer. b. Object. c. String. d. Class. ANS: b. Object. 9.4.1 Q2: Overriding a method differs from overloading a method because: a. Overloaded methods have the same signature. b. Overridden methods have the same signature. c. Both of the above. d. Neither of the above. ANS: b. Overridden methods have the same signature.
Section 9.4.2 Creating a BasePlusCommissionEmployee Class without Using Inheritance 9.4.2 Q1: To avoid duplicating code, use ________, rather than ________. a. inheritance, the “copy-and-past” approach. b. the “copy-and-past” approach, inheritance. c. a class that explicitly extends Object, a class that does not extend Object. d. a class that does not extend Object, a class that explicitly extends Object. ANS: a. inheritance, the “copy-and-past” approach.
Section 9.4.3 Creating a CommissionEmployeeBasePlusCommissionEmployee Inheritance Hierarchy 9.4.3 Q1: Consider the classes below, declared in the same file: class A { int a; public A() { a = 7; } } class B extends A { int b; public B() ..
{ b = 8; } } Which of the statements below is false? a. Both variables a and b are instance variables. b. After the constructor for class B executes, the variable a will have the value 7. c. After the constructor for class B executes, the variable b will have the value 8. d. A reference of type A can be treated as a reference of type B. ANS: d. A reference of type A can be treated as a reference of type B. 9.4.3 Q2: Which of the following is the superclass constructor call syntax? a. keyword super, followed by a dot (.) . b. keyword super, followed by a set of parentheses containing the superclass constructor arguments. c. keyword super, followed by a dot and the superclass constructor name. d. None of the above. ANS: b. keyword super, followed by a set of parentheses containing the superclass constructor arguments.
Section 9.4.4 CommissionEmployeeBasePlusCommissionEmployee Inheritance Hierarchy Using protected Instance Variables 9.4.4 Q1: Which superclass members are inherited by all subclasses of that superclass? a. private instance variables and methods. b. protected instance variables and methods. c. private constructors. d. protected constructors. ANS: b. protected instance variables and methods. 9.4.4 Q2: Which statement is true when a superclass has protected instance variables? a. A subclass object can assign an invalid value to the superclass’s instance variables, thus leaving an object in an inconsistent state. b. Subclass methods are more likely to be written so that they depend on the superclass’s data implementation. c. We may need to modify all the subclasses of the superclass if the superclass implementation changes. d. All of the above. ANS: d. All of the above.
Section 9.4.5 CommissionEmployeeBasePlusCommissionEmployee Inheritance Hierarchy Using private Instance Variables 9.4.5 Q1: private fields of a superclass can be accessed in a subclass a. by calling private methods declared in the superclass. b. by calling public or protected methods declared in the superclass. c. directly. d. All of the above. ANS: b. by calling public or protected methods declared in the superclass. 9.4.5 Q2: Failure to prefix the superclass method name with the keyword super and a dot (.) separator when referencing the superclass’s method causes ________. a. a compile-time error. ..
b. a syntax error. c. infinite recursion. d. a runtime error. ANS: c. infinite recursion.
Section 9.5 Constructors in Subclasses 9.5 Q1: When a subclass constructor calls its superclass constructor, what happens if the superclass’s constructor does not assign a value to an instance variable? a. A syntax error occurs. b. A compile-time error occurs. c. A run-time error occurs. d. The program compiles and runs because the instance variables are initialized to their default values. ANS: d. The program compiles and runs because the instance variables are initialized to their default values.
Section 9.6 Software Engineering with Inheritance 9.6 Q1: Which of the following statements is (are) true? A. We can use inheritance to customize existing software. B. A superclass specifies commonality. C. A superclass can be modified without modifying subclasses D. A subclass can be modified without modifying its superclass. a. All of the above. b. None of the above. c. A, B and C. d. A, B and D. ANS: a. All of the above. 9.6 Q2: Which of the following is an example of a functionality that should not be “factored out” to a superclass? a. Both ducks and geese are birds that know how to start flying from the water. b. All vehicles know how to start and stop. c. All animals lay eggs, except for mammals. d. All paints have a color. ANS: c. All animals lay eggs except for mammals.
Section 9.7 Object Class 9.7 Q1: The default implementation of method clone of Object performs a ________. a. empty copy. b. deep copy. c. full copy. d. shallow copy. ANS: d. shallow copy. 9.7 Q2: The default equals implementation of class Object determines: a. whether two references refer to the same object in memory. b. whether two references have the same type. c. whether two objects have the same instance variables. d. whether two objects have the same instance variable values. ANS: a. whether two references refer to the same object in memory.
..
Section 9.8 (Optional) GUI and Graphics Case Study: Displaying Text and Images Using Labels 9.8 Q1: Class ________ represents an image that can be displayed on a JLabel. a. Image. b. Icon. c. ImageIcon. d. IconImage. ANS: c. ImageIcon. 9.8 Q2: Which method changes the text the label displays? a. changeText. b. setText. c. changeLabel. d. setLabel. ANS: b. setText.
..
Chapter 10: Object-Oriented Programming: Polymorphism Section 10.1 Introduction 10.1 Q1: Polymorphism enables you to: a. program in the general. b. program in the specific. c. absorb attributes and behavior from previous classes. d. hide information from the user. Ans: a. program in the general.
10.1 Q2: Which of the following statements about interfaces is false? a. An interface describes a set of methods that can be called on an object, providing a default implementation for the methods. b. An interface describes a set of methods that can be called on an object, not providing concrete implementation for the methods. c. Interfaces are useful when attempting to assign common functionality to possibly unrelated classes. d. Once a class implements an interface, all objects of that class have an is-a relationship with the interface type. Ans: a. An interface describes a set of methods that can be called on an object, providing a default implementation for the methods.
Section 10.2 Polymorphism Examples 10.2 Q1: For which of the following would polymorphism not provide a clean solution? a. A billing program where there is a variety of client types that are billed with different fee structures. b. A maintenance log program where data for a variety of types of machines is collected and maintenance schedules are produced for each machine based on the data collected. c. A program to compute a 5% savings account interest for a variety of clients. d. An IRS program that maintains information on a variety of taxpayers and determines who to audit based on criteria for classes of taxpayers. Ans: c. A program to compute a 5% savings account interest for a variety of clients. Because there is only one kind of calculation, there is no need for polymorphism.
10.2 Q2: Polymorphism allows for specifics to be dealt with during: ..
a. execution. b. compilation. c. programming. d. debugging. Ans: a. execution
Section 10.3 Demonstrating Polymorphic Behavior 10.3 Q1: Which statement best describes the relationship between superclass and subclass types? a. A subclass reference cannot be assigned to a superclass variable and a superclass reference cannot be assigned to a subclass variable. b. A subclass reference can be assigned to a superclass variable and a superclass reference can be assigned to a subclass variable. c. A superclass reference can be assigned to a subclass variable, but a subclass reference cannot be assigned to a superclass variable. d. A subclass reference can be assigned to a superclass variable, but a superclass reference cannot be assigned to a subclass variable. Ans: d. A subclass reference can be assigned to a superclass variable, but a superclass reference cannot be assigned to a subclass variable.
Section 10.4 Abstract Classes and Methods 10.4 Q1: A(n) a. final. b. concrete. c. abstract. d. polymorphic. Ans: c. abstract.
class cannot be instantiated.
10.4 Q2: Non-abstract classes are called: a. real classes. b. instance classes. c. implementable classes. d. concrete classes. Ans: d. concrete classes.
Section 10.5 Case Study: Payroll System ..
Using Polymorphism 10.5 Q1: It is a UML convention to denote the name of an abstract class in: a. bold. b. italics. c. a diamond. d. there is no convention of the UML to denote abstract classes—they are listed just as any other class. Ans: b. italics. 10.5 Q2: If the superclass contains only abstract method declarations, the superclass is used for: a. implementation inheritance. b. interface inheritance. c. Both. d. Neither. Ans: b. interface inheritance.
Section 10.5.1 Abstract Superclass Employee 10.5.1 Q1: Which of the following could be used to declare abstract method method1 in abstract class Class1 (method1 returns an int and takes no arguments)? a. public int method1(); b. public int abstract method1(); c. public abstract int method1(); d. public int nonfinal method1(); Ans: c. public abstract int method1();
10.5.1 Q2: Which of the following statements about abstract superclasses is true? a. abstract superclasses may contain data. b. abstract superclasses may not contain implementations of methods. c. abstract superclasses must declare all methods as abstract. d. abstract superclasses must declare all data members not given values as abstract. Ans: a. abstract superclasses may contain data.
Section 10.5.2 Concrete Subclass SalariedEmployee 10.5.2 Q1: Consider the abstract superclass below: ..
public abstract class Foo { private int a; public int b; public Foo( int aVal, int bVal ) { a = aVal; b = bVal; } // end Foo constructor public abstract int calculate(); } // end class Foo
Any concrete subclass that extends class Foo: a. Must implement a method called calculate. b. Will not be able to access the instance variable a. c. Neither (a) nor (b). d. Both (a) and (b). Ans: d. Both (a) and (b).
Section 10.5.5 Indirect Concrete Subclass BasePlusCommissionEmployee 10.5.5 Q1: Consider classes A, B and C, where A is an abstract superclass, B is a concrete class that inherits from A and C is a concrete class that inherits from B. Class A declares abstract method originalMethod, implemented in class B. Which of the following statements is true of class C? a. Method originalMethod cannot be overridden in class C—once it has been implemented in concrete class B, it is implicitly final. b. Method originalMethod must be overridden in class C, or a syntax error will occur. c. If method originalMethod is not overridden in class C but is called by an object of class C, an error occurs. d. None of the above. Ans: d. None of the above.
Section 10.5.6 Polymorphic Processing, Operator instanceof and Downcasting 10.5.6 Q1: When a superclass variable refers to a subclass object and a method is called on that object, the proper implementation is determined at execution time. What is the process of determining the correct method to call? a. early binding. b. non-binding. ..
c. on-time binding. d. late binding. Ans: d. late binding (also called dynamic binding).
10.5.6 Q2: Every object in Java knows its own class and can access this information through method . a. getClass. b. getInformation. c. objectClass. d. objectInformation. Ans: a. getClass.
Section 10.5.7 Summary of the Allowed Assignments Between Superclass and Subclass Variables 10.5.7 Q1: Assigning a subclass reference to a superclass variable is safe: a. because the subclass object has an object of its superclass. b. because the subclass object is an object of its superclass. c. only when the superclass is abstract. d. only when the superclass is concrete. Ans: b. because the subclass object is an object of its superclass.
Section 10.6 final Methods and Classes 10.6 Q1: Classes and methods are declared final for all but the following reasons: a. final methods allow inlining the code. b. final methods and classes prevent further inheritance. c. final methods are static. d. final methods can improve performance. Ans: c. final methods are static. 10.6 Q2: All of the following methods are implicitly final except: a. a method in an abstract class. b. a private method. c. a method declared in a final class. d. static method. Ans: a. a method in an abstract class.
10.6 Q3: Declaring a method final means: ..
a. it will prepare the object for garbage collection. b. it cannot be accessed from outside its class. c. it cannot be overloaded. d. it cannot be overridden. Ans: d. it cannot be overridden.
Section 10.7 Case Study: Creating and Using Interfaces 10.7 Q1: An interface may contain: a. private static data and public abstract methods. b. only public abstract methods. c. public static final data and public abstract methods. d. private static data and public final methods. Ans: c. public static final data and public abstract methods.
10.7 Q2: Which of the following does not complete the sentence correctly? An interface . a. forces classes that implement it to declare all the interface methods. b. can be used in place of an abstract class when there is no default implementation to inherit. c. is declared in a file by itself and is saved in a file with the same name as the interface followed by the .java extension. d. can be instantiated. Ans: d. can be instantiated.
Section 10.7.1 Developing a Payable Hierarchy 10.7.1 Q1: The UML distinguishes an interface from other classes by placing the word “interface” in above the interface name. a. italics. b. carets. c. guillemets. d. bold. Ans: c. guillemets.
Section 10.7.2 Interface Payable 10.7.2 Q1: Interfaces can have a. 0
methods. ..
b. 1 c. 2 d. any number of Ans: d. any number of
Section 10.7.3 Class Invoice 10.7.3 Q1: Which keyword is used to specify that a class will define the methods of an interface? a. uses. b. implements. c. defines. d. extends. Ans: b. implements.
10.7.3 Q2: Which of the following is not possible? a. A class that implements two interfaces. b. A class that inherits from two classes. c. A class that inherits from one class, and implements an interface. d. All of the above are possible. Ans: b. A class that inherits from two classes.
Section 10.7.4 Modifying Class Employee to Implement Interface Payable 10.7.4 Q1: A class that implements an interface but does not declare all of the interface’s methods must be declared: a. public. b. interface. c. abstract. d. final. Ans: c. abstract.
..
Chapter 11: Exception Handling Section 11.1 Introduction 11.1 Q1: Which of the following statements is false? a. Exception handling enables programmers to write robust and fault-tolerant programs. b. Exception handling can catch but not resolve exceptions. c. Exception handling can resolve exceptions. d. All of the above are true. Ans: b. Exception handling can catch but not resolve exceptions.
Section 11.2 Example: Divide By Zero Without Exception Handling 11.2 Q1: When an exception occurs it is said to have been: a. caught. b. thrown. c. declared. d. handled. Ans: b. thrown. 11.2 Q2: Which of the following is not included in an exception’s stack trace? a. A descriptive message for the exception. b. The method-call stack at the time the exception occurred. c. The name of the exception. d. Instructions on handling the exception. Ans: d. Instructions on handling the exception.
11.2 Q3: Which of the following statements regarding the throw point of an exception is false? a. It specifies the point at which the exception must be handled. b. It is the initial point at which the exception occurs. c. It is specified as the top row of the method-call stack at the time the exception occurred. d. All of the above statements are true. Ans: a. It specifies the point at which the exception must be handled.
Section 11.3 Example: Handling ArithmeticExceptions and ..
InputMismatchExceptions Enclosing Code in a try Block 11.3 Q1: To catch an exception, the code that might throw the exception must be enclosed in a a. throws block. b. catch block. c. try block. d. finally block. Ans: c. try block. 11.3 Q2: Exceptions can be thrown by: a. the Java Virtual Machine. b. code in a try block. c. calls from a try block to other methods. d. All of the above. Ans: d. All of the above.
Catching Exceptions 11.3 Q3: In the catch block below, what is arithmeticException? catch ( ArithmeticException arithmeticException ) { System.err.printf( arithmeticException ); } // end catch
a. The type of the exception being caught. b. The name of catch block’s exception parameter. c. A finally block. d. An exception handler. Ans: b. The name of catch block’s exception parameter. 11.3 Q4: An uncaught exception: a. is a possible exception that never actually occurs during the execution of the program. b. is an exception that occurs for which the matching catch clause is empty. c. is an exception that occurs for which there are no matching catch clauses. d. is another term for a thrown exception. Ans: c. is an exception that occurs for which there are no matching catch clauses. 11.3 Q5: Which of the following statements about try blocks is true? a. The try block must be followed by at least one catch block. b. The try block must be followed by a finally block. c. The try block should contain statements that may process an exception. d. The try block should contain statements that may throw an exception. ..
Ans: d. The try block should contain statements that may throw an exception.
Termination Model of Exception Handling 11.3 Q6: In Java, after an exception is handled, control resumes . This is known as the model of exception handling. a. after the last catch block (or the finally block, if there is one), termination b. after the last catch block (or the finally block, if there is one), resumption c. just after the throw point, termination d. just after the throw point, resumption Ans: a. after the last catch block (or the finally block, if there is one), termination 11.3 Q7: What is the difference between a try block and a try statement? a. There is no difference; the terms can be used interchangeably. b. A try statement refers to the block of code following the keyword try, while the try block refers to the try keyword and the block of code following this keyword. c. The try block refers to the keyword try followed by a block of code. The try block and its corresponding catch and/or finally clauses together form a try statement. d. The try statement refers to the keyword try followed by a block of code. The try statement and its corresponding catch and/or finally clauses together form a try block. Ans: c. The try block refers to the keyword try followed by a block of code. The try block and its corresponding catch and/or finally clauses together form a try statement.
Using the throws Clause 11.3 Q8: The throws clause of a method: a. specifies the exceptions a method catches. b. specifies the exceptions thrown by the calling method. c. specifies the exceptions a method throws. d. specifies the exceptions a method throws and catches. Ans: c. specifies the exceptions a method throws.
Section 11.4 When to Use Exception Handling 11.4 Q1: Which of the following errors is synchronous? a. Divide by zero. b. Arithmetic overflow. c. Unsuccessful memory allocation. d. All of the above. Ans: d. All of the above.
..
Section 11.5 Java Exception Hierarchy 11.5 Q1: All exception classes inherit, either directly or indirectly, from: a. class Error. b. class RuntimeException. c. class Throwable. d. None of the above. Ans: c. class Throwable. 11.5 Q2: Which of the following exceptions is a checked exception? a. ArithmeticException. b. IOException. c. RuntimeException. d. InputMismatchException. Ans: b. IOException. 11.5 Q3: If the catch-or-declare requirement for a checked exception is not satisfied: a. the compiler will issue an error message indicating that the exception must be caught. b. the compiler will issue an error message indicating that the exception must be caught or declared. c. a stack trace will be displayed indicating the exception that has occurred and where it occurred. d. a stack trace will be displayed, along with a message indicating that the exception must be caught. Ans: b. the compiler will issue an error message indicating that the exception must be caught or declared.
Section 11.6 finally block 11.6 Q1: Which of the following statements is false? a. A finally block is placed after the last catch block. b. A finally block typically releases resources acquired in the corresponding try block. c. The finally block and try block can appear in any order. d. A finally block is optional. Ans: c. The finally block and try block can appear in any order. 11.6 Q2: Which of the following statements is true? a. The code in a finally block is executed only if an exception occurs. b. The code in a finally block is executed only if an exception does not occur. c. The code in a finally block is executed only if there are no catch blocks. d. None of the above are true. Ans: d. None of the above are true. ..
11.6 Q3: After a finally block has finished executing (and there are no exceptions to be handled): a. control proceeds to the first statement after the finally block. b. control returns to the throw point. c. the application exits. d. control proceeds to the first statement after the last catch block. Ans: a. control proceeds to the first statement after the finally block.
Throwing Exceptions Using the throw Statement 11.6 Q4: Which of the following statements is true? a. The throw statement is used to throw an exception. b. The throw statement is used to specify that a method will throw an exception. c. The throw statement is used to access an exception parameter. d. All of the above. Ans: a. The throw statement is used to throw an exception.
Section 11.7 Stack Unwinding and Obtaining Information from an Exception Object 11.7 Q1: When an unchecked exception occurs in a method but is not caught: a. the method-call stack is “unwound.” b. the method terminates. c. all local variables in that method go out of scope. d. All of the above. Ans: d. All of the above. 11.7 Q1: Which of the following statements is false? a. All exceptions must derive from the class Throwable. b. The class Throwable provides the method getStackTrace that outputs the stack trace to the standard error stream. c. The class Throwable provides the method getMessage that returns the descriptive string stored in an exception. d. The string returned from class Throwable’s getMessage method contains the name of the exception’s class. Ans: b. The class Throwable provides the method getStackTrace that outputs to the standard error stream the stack trace.
Section 11.8 Chained Exceptions 11.8 Q1: Chained exceptions are useful for finding out about: a. exceptions thrown using the chained keyword. b. checked exceptions only. ..
c. an original exception that was caught before the current exception was thrown. d. the current exception’s chain of superclasses. Ans: c. an original exception that was caught before the current exception was thrown.
Section 11.9 Declaring New Exception Types 11.9 Q1: Which of the following statements is true? a. Using existing exceptions makes the program less robust. b. Always create your own exception classes. c. Like any other class, an exception class can contain fields and methods. d. The new exception class should extend RuntimeException if the program should be required to handle the exception. Ans: c. Like any other class, an exception class can contain fields and methods.
Section 11.10 Preconditions and Postconditions 11.10 Q1: Which of the following is true? a. A precondition must be true when a method is invoked. b. A postcondition must be true when a method successfully returns to its caller. c. Both of the above. d. Neither of the above. Ans: Both of the above.
Section 11.11 Assertions 11.11 Q1: Which of the following are types of assertions? a. Preconditions. b. Postconditions. c. Conditions in control statements. d. (a), (b) and (c). e. (a) and (b). Ans: e. (a) and (b).
Section 11.12 (New in Java SE 7) Multi-catch: Handling Multiple Exceptions in One Catch 11.12 Q1: Java SE 7’s multi-catch enables you to catch multiple exception types in a single catch handler and perform the same task for each type of exception. The syntax for a multi-catch is: a. catch ( Type1 or Type2 or Type3 e ) b. catch ( Type1 e1 | Type2 e2 | Type3 e3 ) ..
c. catch ( Type1 | Type2 | Type3 e ) d. catch ( Type1 e1 or Type2 e2 or Type3 e ) Ans: c. catch ( Type1 | Type2 | Type3 e )
Section 11.13 (New in Java SE 7) try-withResources: Automatic Resource Deallocation 11.13 Q1: Which of the following statements about the try-with-resources statement is false? a. The try-with-resources statement simplifies writing code in which you obtain a resource, use it in a try block and release the resource in a corresponding finally block.. b. You allocate the resource in the parentheses following the try keyword and use the resource in the try block; then the statement implicitly calls the resource’s close method at the end of the try block. c. You allocate the resource in the parentheses following the try keyword and use the resource in the try block; then you explicitly call the resource’s close method at the end of the try block. d. Each resource must be an object of a class that implements the AutoCloseable interface—such a class has a close method. Ans: c. You allocate the resource in the parentheses following the try keyword and use the resource in the try block; then you explicitly call the resource’s close method at the end of the try block.
..
Chapter 12 ATM Case Study, Part 1: Object-Oriented Design with the UML Section 12.1 Introduction Section 12.2 Examining the Requirements Document Analyzing the ATM System 12.2 Q1: Which of the following is the first stage of the software life cycle? a. design. b. implementation. c. requirements gathering. d. testing. ANS: c. requirements gathering. Use Case Diagrams 12.2 Q2: The use case diagram models ________. a. the interactions between a system’s client and one of the system’s capabilities. b. each software life cycle stage in succession. c. each software life cycle by repeating one or more stages several times via use cases. d. the interactions between implementations and testing. ANS: a. the interactions between a system’s client and one of the system’s capabilities. 12.2 Q3: Which of the following is not an actor of the ATM system? a. A user who views an account balance. b. A user who provides requirements for building the ATM system. c. A user who withdraws cash from the ATM. d. A user who deposits funds into the ATM. ANS: b. A user who provides requirements for building the ATM system. Designing the ATM System 12.2 Q4: Which diagram models system structure? a. State machine diagram. b. Class diagram. c. Activity diagram. d. Sequence diagram. ANS: b. Class diagram. 12.2 Q5: Which diagram is also called a collaboration diagram. a. State machine diagram. b. Communication diagram. c. Activity diagram.
..
Sequence diagram. ANS: b. Communication diagram. d.
Section 12.4 Identifying Class Attributes Identifying Attributes 12.4 Q1: Which of the following is not an attribute? a. The height of a person. b. The volume of a radio. c. The speed of a car. d. The user of an ATM system. ANS: d. The user of an ATM system.
Modeling Attributes 12.4 Q2: In the UML, a class’s attributes are placed in the ________ compartment of the class’s rectangle. a. first. b. second. c. third. d. bottom. ANS: b. second.
Section 12.5 (Optional) Identifying Objects’ States and Activities State Machine Diagrams 12.5 Q1: UML ________ model several states of an object and show under what circumstances the object changes state. a. diagrams. b. activity diagrams. c. state machine diagrams. d. machine diagrams. ANS: c. state machine diagrams. 12.5Q2: An initial state is represented with a(n) ________. a. solid circle with an attached stick arrowhead. b. empty circle with an attached stick arrowhead. c. solid rectangle with an attached stick arrowhead. d. rounded rectangle with an attached stick arrowhead. ANS: a. solid circle with an attached stick arrowhead.
..
Activity Diagrams 12.5 Q3: An activity diagram models ________. a. the states of an object. b. the attributes of an object. c. the behaviors of an object. d. the transactions of an object. ANS: c. the behaviors of an object. 12.5 Q4: A final state in an activity diagram is represented with a(n) ________. a. solid circle. b. empty circle. c. solid circle enclosed in an open circle. d. solid rectangle enclosed in an open rectangle. ANS: c. solid circle enclosed in an open circle.
Section 12.6 (Optional) Identifying Class Operations Identifying Operations 12.6 Q1: We can derive many of the operations of each class by examining the key ________ and ________ in the requirements documents. a. verbs, verb phrases. b. nouns. noun phrases. c. objectives, objective phrases. d. Both a and b. ANS: a. verbs, verb phrases.
Modeling Operations 12.6 Q2: The UML represents operations by listing the operation name, followed by a ________-separated list of parameters in parentheses, a ________ and the return type. a. colon, semicolon. b. colon, colon. c. comma, colon. d. comma, semicolon. ANS: c. comma, colon.
Section 12.7 Collaboration Among Objects 12.7 Q1: A collaboration between objects consists of . a. an object of one class sending a message to an object of another class. b. an object of one class repeating messages sent to it from an object of another class. c. two objects in the same application, but not necessarily sending messages to each other.
..
d. None of the above. Ans: a. an object of one class sending a message to an object of another class.
Interaction Diagrams 12.7 Q2: In the UML, the collaborations. a. participation. b. communication. c. collaboration. d. sequence. Ans: b. communication.
diagram emphasizes which objects participate in
Communication Diagrams 12.7 Q3: Objects are modeled in the UML as form . a. ovals, : ClassName. b. ovals, objectName : ClassName. c. rectangles, : ClassName. d. rectangles, objectName : ClassName. Ans: d. rectangles, objectName : ClassName.
containing names in the
12.7 Q4: What is a message between collaborating objects called in the UML? a. asynchronous call. b. communication call. c. synchronous call. d. collaboration call. Ans: c. synchronous call.
Sequence of Messages in a Communication Diagram 12.7 Q5: The sequence of messages in a communication diagram progresses: a. alphabetically. b. in numerical order from least to greatest. c. Both of the above. d. None of the above. Ans: b. in numerical order from least to greatest.
Sequence Diagrams 12.7 Q6: Communication diagrams contain an object’s lifeline. Which of the following is true of the object’s lifeline? a. Actions occur along an object’s lifeline in chronological order from top to bottom. b. The line is dotted. c. The lifeline represents the progression of time. d. All of the above are true. Ans: d. All of the above are true.
..
12.7 Q7: An activation indicates that: a. an object is sending a message. b. an object is being created. c. an object is executing. d. an object has completed executing. Ans: c. an object is executing.
..
Chapter 13 ATM Case Study, Part 2: Implementing an Object-Oriented Design Section 13.2 Starting to Program the Classes of the ATM System Visibility 13.2 Q1: In the UML, public visibility is indicated by placing a ________ before an operation or an attribute, whereas a ________ indicates private visibility. a. letter p, letter n. b. letter n, letter p. c. plus sign (+), minus sign (-). d. minus sign (-), plus sign (+). ANS: c. plus sign (+), minus sign (-).
Navigability 13.2 Q2: Associations in a class diagram that do not have navigability arrows at both ends indicate ________. a. no navigability. b. one-way clockwise navigability. c. one-way counterclockwise navigability. d. bidirectional navigability. ANS: d. bidirectional navigability.
Section 13.3 Incorporating Inheritance into the ATM System 13.3 Q1: The UML specifies a relationship called a a. inheritization. b. specialization. c. generalization. d. All of the above. Ans: c. generalization.
to model inheritance.
13.3 Q2: In UML diagrams, abstract methods are . a. displayed in italics. b. displayed in bold. c. not shown, as they have yet to be implemented. d. displayed, but without the parentheses following the method name. Ans: a. displayed in italics.
..
Chapter 14: GUI Components: Part 1 14.1 Introduction 14.1 Q1: Which of the following is not a GUI component (control or widget)? a. String. b. Button. c. Menu. d. Combo box. Ans: a. String.
14.1 Q2: Which component contains menus? a. Menu button. b. Title bar. c. Menu bar. d. Combo box. Ans: c. Menu bar.
14.2 Java’s New Nimbus Look-and-Feel [*** NONE ***]
14.3 Simple GUI-Based Input/Output with JOptionPane 14.3 Q1: Which of the following is the method used to display a dialog box to gather input? a. showMessageDialog. b. getInput. c. inputDialog. d. showInputDialog. Ans: d. showInputDialog. 14.3 Q2: The text “Hello there, my friend.” is an example of what type of capitalization? a. sentence-style capitalization. b. book-title capitalization. c. Neither of the above. d. Both of the above. ..
Ans: a. sentence-style capitalization. JOptionPane Message Dialog Constants 14.3 Q3: The JOptionPane constant used to display an icon prompting the user for
input is: a. JOptionPane.ERROR_MESSAGE. b. JOptionPane.INFORMATION_MESSAGE. c. JOptionPane.QUESTION_MESSAGE. d. JOptionPane.WARNING_MESSAGE. Ans: c. JOptionPane.QUESTION_MESSAGE.
14.4 Overview of Swing Components 14.4 Q1: Which of the following statements for a JTextField is false? a. Can be used to display uneditable text. b. Can be used to display editable text. c. Enables users to enter data from the keyboard. d. Displays a list of fields. Ans: d. Displays a list of fields.
Swing vs. AWT 14.4 Q2: Together, the appearance and the way in which the user interacts with the application are known as that application’s . a. abstract window toolkit. b. look-and-feel. c. swing factor. d. All of the above. Ans: b. look-and-feel.
14.4 Q3: Which of the following statements about Swing GUI components is false? a. Swing components are less portable but more flexible than the original Java GUI components from package java.awt. b. Most Swing components are written completely in Java. c. Swing components allow the user to specify a uniform look-and-feel across all platforms. d. Swing components allow the user to change the look-and-feel while the program is running. Ans: a. Swing components are less portable but more flexible than the original Java GUI components from package java.awt.
..
Lightweight vs. Heavyweight GUI Components 14.4 Q4: Which of the following statements about heavyweight components is false? a. AWT components are not heavyweight components. b. Several Swing components are heavyweight components. c. The look-and-feel may vary across platforms. d. The functionality may vary across platforms. Ans: a. AWT components are not heavyweight components.
Superclasses of Swing’s Lightweight GUI Components 14.4 Q5: Which pair of words does not complete the sentence below correctly? A ________ is a ________. a. Container, Component. b. Container, JPanel. c. JComponent, Container. d. Component, Object. ANS: b. Container, JPanel.
14.4 Q6: Some common lightweight component features supported by JComponent include: a. support for user-interface localization. b. shortcut keys. c. tool tips. d. All of the above. Ans: d. All of the above.
14.4 Displaying Text and Images in a Window 14.5 Q1: provides the basic attributes and behaviors of a window—a title bar at the top of the window, and buttons to minimize, maximize and close the window. a. JLabel. b. JFrame. c. JSwing. d. JWindowControl. Ans: b. JFrame.
Labeling GUI Components 14.5 Q2: Which of the following statements about a JLabel is false? a. Applications rarely change a label’s contents after creating it. b. A JLabel can display text and an image. c. A JLabel can display text and a button. d. A JLabel is a subclass of JComponent. ..
Ans: c. A JLabel can display text and a button.
Specifying the Layout 14.5 Q3: Method a. setManager. b. setLayout. c. setLayoutManager. d. setGUILayout. Ans: b. setLayout.
can be used to set the layout manager of a container.
Creating and Attaching label1 14.5 Q4: A JLabel can be attached to a JFrame using method: a. attach. b. contain. c. append. d. add. Ans: d. add.
14.5 Q5: Which method sets the text that's displayed when the user hovers over a JLabel? a. setHover. b. setHoverText. c. setToolTip. d. setToolTipText. Ans: d. setToolTipText.
Creating and Attaching label2 14.5 Q6: Which of the following expressions creates a JLabel that displays the text "Here is what I look like!" The JLabel should display Icon object face, and the JLabel’s contents should be left aligned. a. new JLabel( "Here is what I look like!", face, SwingConstants.LEFT ) b. new JLabel( "Here is what I look like!", face, SwingJustification.LEFT ) c. new JLabel( "Here is what I look like!", SwingConstants.LEFT, face ) d. new JLabel( "Here is what I look like!", SwingJustification.LEFT, face ) Ans: a. new JLabel( "Here is what I look like!", face, SwingConstants.LEFT )
14.5 Q7: Which expression returns the location of a file as a URL? a. getURL( "file.txt" ). ..
b. getResource( "file.txt" ). c. findResource( "file.txt" ). d. getClass( "file.txt" ). Ans: b. getResource( "file.txt" ).
Creating and Attaching label3 14.5 Q8: Which methods retrieve and set the image that's displayed in a JLabel? a. getIcon, setIcon. b. getResource, setResource. c. getText, setText. d. getImageIcon, setImageIcon. Ans: a. getIcon, setIcon.
Creating and Displaying a LabelFrame Window 14.5 Q9: Which JFrame constant indicates that the program should terminate when the window is closed by the user? a. TERMINATE_ON_CLOSE. b. IMMEDIATELY_CLOSE. c. EXIT_ON_CLOSE. d. All of the above. Ans: c. EXIT_ON_CLOSE.
14.6 Text Fields and an Introduction to Event Handling with Nested Classes 14.6 Q1: Which of the following does not generate GUI events? a. Typing in a text field. b. Selecting an item from a menu. c. Viewing the text in a label. d. Moving the mouse. Ans: c. Viewing the text in a label.
14.6 Q2: Which of the following is false? a. A JPasswordField shows that characters are being entered, but hides the actual character with an echo character. b. Class JTextField extends JTextComponent; Class JPasswordField extends JTextField. c. Both JTextFields and JPasswordFields are single-line areas in which the user can enter text via the keyboard. d. JPasswordFields generate events; JTextFields do not. Ans: d. JPasswordFields generate events; JTextFields do not. ..
Creating the GUI 14.6 Q3: Which of the following statements makes the text in a JTextField uneditable? a. textField.setEditable( true ); b. textField.setEditable( false ); c. textField.setUneditable( true ); d. textField.setUneditable( false ); Ans: b. textField.setEditable( false );
Steps Required to Set Up Event Handling for a GUI Component 14.6 Q4: Which of the following most completely describes the steps for setting up event handling for a GUI component? a. Create a class that represents the event handler, attach the JFrame to a JWindow object and register the event handler. b. Implement an appropriate event-listener interface and register the event handler. c. Create a class that represents the event handler and implement an appropriate eventlistener interface. d. Create a class that represents the event handler, implement an appropriate eventlistener interface and register the event handler. Ans: d. Create a class that represents the event handler, implement an appropriate eventlistener interface and register the event handler.
Using a Nested Class to Implement an Event Handler 14.6 Q5: Which of the following answers does not complete the sentence correctly? An anonymous inner class . a. is frequently used for GUI event handling. b. is non-static. c. does not need a handle to its outer class to access its methods and variables. d. cannot be declared private. ANS: d. cannot be declared private. 14.6 Q6: When the user presses Enter in a JPasswordField, the GUI component generates an , which is processed by an object that implements the interface . a. ActionEvent, ActionListener. b. ActionEvent, ActionEventListener. c. TextEvent, TextListener. d. TextEvent, TextEventListener. Ans: a. ActionEvent, ActionListener.
Registering the Event Handler for Each Text Field 14.6 Q7: Forgetting to register an event-handler object for a particular GUI component’s event type causes . a. events of that type to be ignored. b. all of the GUI component's events to be ignored. ..
c. a compilation error. d. None of the above. Ans: a. events of that type to be ignored.
Details of Class TextFieldHandler’s actionPerformed Method 14.6 Q8: JPasswordField contains method a. getInput. b. getPassword. c. getText. d. getEcho. Ans: b. getPassword.
to obtain the data entered.
14.6 Q9: The GUI event with which the user interacts is the a. event effector. b. event container. c. event raiser. d. event source. Ans: d. event source.
.
14.7 Common GUI Event Types and Listener Interfaces 14.7 Q1: Which of the following is not necessary to use the event delegation model? a. An event listener must be registered. b. An event handler must be implemented. c. The appropriate interface must be implemented. d. The appropriate interface must be registered. Ans: d. The appropriate interface must be registered.
14.7 Q2: Which of the following completes the sentence below correctly? A(n) is a(n) . a. InputEvent, MouseEvent. b. ActionEvent, AdjustmentEvent. c. FocusEvent, WindowEvent. d. ContainerEvent, ComponentEvent. Ans: d. ContainerEvent, ComponentEvent.
..
14.8 How Event Handling Works Registering Events 14.8 Q1: Every JComponent has an instance variable called object to maintain references to all its registered listeners. a. registeredListenerList. b. listenerList. c. registeredList. d. eventListenerList. Ans: b. listenerList.
that enables the
Event-Handler Invocation 14.8 Q2: How many event-listener interfaces correspond to each event type? a. one. b. two. c. one or more. d. zero. Ans: c. one or more.
14.9 JButton 14.9 Q1: Which of the following choices completes the sentence correctly? A(n) is a(n) . a. JToggleButton, JCheckBox. b. JToggleButton, JRadioButton. c. JButton, JToggleButton. d. JButton, AbstractButton. Ans: d. JButton, AbstractButton.
14.9 Q2: The method setRolloverIcon is used to: a. Handle a key event. b. Change the button text. c. Change the button icon. d. All of the above. Ans: c. Change the button icon.
14.9 Q3:Which of the following is not a type of button? a. command buttons. b. toggle buttons. ..
c. check boxes. d. All of the above are types of buttons. Ans: d. All of the above are types of buttons.
14.10 Buttons That Maintain State 14.10 Q1: Which of the following is stateless? a. JButton. b. JToggleButton. c. JRadioButton. d. JCheckBox. Ans: a. JButton.
14.10 Q2: A JRadioButton is different from a JCheckBox in that . a. a JRadioButton is a subclass of JToggleButton, JCheckBox is not. b. normally several JRadioButtons are grouped together and are mutually exclusive. c. a JRadioButton is a type of button, JCheckBox is not. d. a JRadioButton is a state button, JCheckBox is not. Ans: b. normally several JRadioButtons are grouped together and are mutually exclusive.
14.10.1 JCheckBox 14.10.1 Q1: When the user clicks a JCheckBox, a(n) a. CheckedEvent. b. ButtonEvent. c. ItemEvent. d. ActionEvent. Ans: c. ItemEvent.
occurs.
14.10.1 Q2: Which method determines if a JCheckBox is selected? a. isSelected. b. getSelected. c. selected. d. None of the above. Ans: a. isSelected.
14.10.2 JRadioButton 14.10.2 Q1: The logical relationship between radio buttons is maintained by objects of what class? a. MutualExclusionGroup. ..
b. RadioButtonGroup. c. Group. d. ButtonGroup. Ans: d. ButtonGroup.
14.10.2 Q2: Adding a ButtonGroup object to a container: a. is necessary for the functionality of the ButtonGroup to work properly. b. causes all the JRadioButtons in the group to have their event handlers registered. c. results in a compilation error. d. None of the above. Ans: c. results in a compilation error.
14.10 JComboBox and Using an Anonymous Inner Class for Event Handling 14.11 Q1: When the arrow on a JComboBox is clicked: a. an ItemEvent occurs. b. a scrollbar always appears. c. an ActionEvent occurs. d. The JComboBox expands to a list. Ans: d. The JComboBox expands to a list.
14.11 Q2: The setMaximumRowCount method is used for: a. Button. b. JComboBox. c. JRadioButton. d. JToggleButton. Ans: b. JComboBox.
Using an Anonymous Inner Class for Event Handling 14.11 Q3: Which of the following statements about anonymous inner classes is false? a. They are declared without a name. b. They typically appear inside a method declaration. c. They are declared with the anonymous keyword. d. They can access their top-level class’s members. Ans: c. They are declared with the anonymous keyword.
14.11 Q4: Method getSelectedIndex of class JComboBox returns: ..
a. the index of the selected item in the JComboBox. b. the selected item in the JComboBox, as a String. c. the index of the previously selected item. d. None of the above. Ans: a. the index of the selected item in the JComboBox.
14.12 JList 14.12 Q1: A JScrollPane is provided automatically for which of the following? a. JToggleButton. b. JRadioButton. c. JList. d. None of the above. Ans: d. None of the above.
14.12 Q2: Selecting a JList item generates: a. an ActionEvent. b. a ListItemEvent. c. a ListSelectionEvent. d. a ListSelectionItemEvent. Ans: c. a ListSelectionEvent.
14.12 Multiple-Selection Lists 14.13 Q1: Consider the list below: January February March April May June July August September October November December
What type of JList selection mode would allow the user to select March, June and July in one step? a. SINGLE_SELECTION. b. SINGLE_INTERVAL_SELECTION. c. MULTIPLE_INTERVAL_SELECTION. d. All of the above. ..
Ans: c. MULTIPLE_INTERVAL_SELECTION.
14.13 Q2: Method getSelectedValues of class JList returns: a. an array of ints representing the indices of the selected items. b. an array of doubles representing the indices of the selected items. c. an array of Strings representing the selected items. d. an array of Objects representing the selected items. Ans: d. an array of Objects representing the selected items.
14.14 Mouse Event Handling 14.14 Q1: Which of the following objects cannot trap mouse events? a. JTextField. b. ButtonGroup. c. JButton. d. JComponent. Ans: b. ButtonGroup.
14.14 Q2: Which of the following is a MouseMotionListener method? a. mousePressed. b. mouseExited. c. mouseDragged. d. mouseClicked. Ans: c. mouseDragged.
Tracking Mouse Events on a JPanel 14.14 Q3: The BorderLayout layout manager: a. divides an area into five regions: NORTH, SOUTH, EAST, WEST and CENTER. b. divides an area into five regions: UP, DOWN, LEFT, RIGHT and MIDDLE. c. orders components vertically. d. order components horizontally. Ans: a. divides an area into five regions: NORTH, SOUTH, EAST, WEST and CENTER.
14.14 Q4: A MouseHandler object implements which two interfaces? a. MouseListener and MouseActionListener. b. MouseListener and MouseMotionListener. c. MouseListener and MouseEventListener. ..
d. MouseListener only. Ans: b. MouseListener and MouseMotionListener.
14.15 Adapter Classes 14.15 Q1: Which of the following statements about adapters is false? a. An adapter class implements an interface. b. An adapter class provides a default (empty) implementation of every method in the interface. c. Programmers override selected adapter methods. d. A ComponentListener is a ComponentAdaptor. Ans: d. A ComponentListener is a ComponentAdaptor.
14.15 Q2: In what cases are adapter classes useful? a. When an adapter GUI control is clicked. b. When every method in the event-listener interface is to use the same functionality. c. When it is not desirable to declare every method in the event-listener interface. d. None of the above. Ans: c. When it is not desirable to declare every method in the event-listener interface.
Extending MouseAdapter 14.15 Q3: A user of a one-button mouse can simulate pushing the middle button on a three-button mouse by holding the while clicking the left mouse button. a. Alt key. b. Meta key. c. Ctrl key. d. Shift key. Ans: a. Alt key. 14.15 Q4: Which MouseEvent method can be used to determine if the Alt key is pressed? a. isAltPressed. b. isAltDown. c. getClickCount. d. AltPressed. Ans: b. isAltDown.
..
14.16 JPanel Subclass for Drawing with the Mouse Method paintComponent 14.16 Q1: Method paintComponent is called when: a. a lightweight Swing component is created. b. a lightweight Swing component is displayed. c. a lightweight Swing component is clicked. d. an application exits. Ans: b. a lightweight Swing component is displayed. 14.16 Q2: When a component is , paintComponent clears the component’s background before the component is displayed. a. transparent. b. opaque. c. oblique. d. concave. Ans: b. opaque.
Defining the Custom Drawing Area 14.16 Q3: Class Point represents: a. a filled oval. b. an x-y coordinate. c. an object used to draw. d. a period in a sentence. Ans: b. an x-y coordinate.
14.16 Q4: Method indicates that a Component should be refreshed on screen as soon as possible with a call to that control’s paintComponent method. a. refresh. b. repaint. c. repaintComponent. d. redraw. Ans: b. repaint.
Using the Custom JPanel in an Application [*** None ***]
14.17 Key-Event Handling 14.17 Q1: Which of the following is not a KeyListener method? ..
a. keyPressed. b. keyReleased. c. keyClicked. d. keyTyped. Ans: c. keyClicked.
14.17 Q2: The Shift key is a(n) a. modifier. b. action. c. output. d. None of the above. Ans: a. modifier.
key.
14.18 Layout Managers 14.18 Q1: Using layout managers: a. provides the greatest level of control over a GUI’s appearance. b. can be faster than creating a GUI with absolute positioning. c. allows the programmer to specify the exact location of each GUI component with respect to the upper-left corner of the Container. d. allows the programmer to specify the exact location of each GUI component with respect to the lower-left corner of the Container. Ans: b. can be faster than creating a GUI with absolute positioning.
14.18 Q2: All layout managers implement the interface: a. LayoutInterface. b. InterfaceLayoutManager. c. LayoutManagerInterface. d. LayoutManager. Ans: d. LayoutManager.
14.18 Q3: Which layout manager is the default for JFrame? a. FlowLayout. b. BorderLayout. c. GridLayout. d. None of the above. Ans: b. BorderLayout.
14.18.1 FlowLayout 14.18.1 Q1: FlowLayout method
changes the alignment for the ..
FlowLayout. a. setLayout. b. modifyAlignment. c. setAlignment. d. setAlign. Ans: c. setAlignment.
14.18.1 Q2: Each container can have: a. only one layout manager. b. one or more layout managers. c. zero or more layout managers. d. only one or two layout managers. Ans: a. only one layout manager.
14.18.1 Q3: FlowLayout is: a. an abstract class. b. a way of organizing components vertically. c. the simplest layout manager. d. left-aligned by default. Ans: c. the simplest layout manager.
14.18.2 BorderLayout 14.18.2 Q1: BorderLayout implements interface: a. ActionListener. b. FlowLayout. c. Layout. d. LayoutManager2. Ans: d. LayoutManager2.
14.18.2 Q2: Which region is used by default when a Component is added to a BorderLayout? a. NORTH. b. CENTER. c. WEST. d. LEFT. Ans: b. CENTER.
14.18.3 GridLayout 14.18.3 Q1: The class GridLayout constructs ..
to hold components.
a. a horizontal grid with one row. b. a vertical grid with one column. c. a grid with multiple rows and columns. d. a square grid with the same number of rows as columns. Ans: c. a grid with multiple rows and columns.
14.18.3 Q2: When components are added to a container with a GridLayout, the component: a. fills the next spot in the row, continuing in the first position of the next row if the current row is full. b. fills the next spot in the column, continuing in the first position of the next column if the column is full. c. fills in row x, column y if x and y are two integers passed to the Container method add. d. fills in a random empty position in the grid. Ans: a. fills the next spot in the row, continuing in the first position of the next row if the current row is full.
14.19 Using Panels to Manage More Complex Layouts 14.19 Q1: Which of the following statements about JPanels is false? a. A JPanel is a JComponent. b. A JPanel is a Container. c. A JPanel does not have a content pane. d. A JPanel has a fixed size. Ans: d. A JPanel has a fixed size.
14.20 JTextArea 14.20 Q1: A JTextArea: a. provides a bounding box used for the layout of JTextFields. b. wraps lines by default. c. provides an area for manipulating multiple lines of text. d. provides scrollbars for JTextFields. Ans: c. provides an area for manipulating multiple lines of text. 14.20 Q2: Class JTextArea’s getSelectedText method: a. returns the text in the JTextArea. ..
b. returns the selected text in the JTextArea. c. displays only the selected text in the JTextArea. d. sets the selected text in the JTextArea. Ans: b. returns the selected text in the JTextArea. JScrollPane Scrollbar Policies 14.20 Q3: By default JScrollPane:
a. always displays scrollbars. b. never displays scrollbars. c. only displays scrollbars if they are needed. d. None of the above. Ans: c. only displays scrollbars if they are needed.
14.20 Q4: Which methods can be used to change the scrollbar policies? a. setHoizontalPolicy, setVerticalPolicy. b. setHorizontal, setVertical. c. setHPolicy, setVPolicy. d. setHorizontalScrollBarPolicy, setVerticalScrollBarPolicy. Ans: d. setHorizontalScrollBarPolicy, setVerticalScrollBarPolicy.
..
Chapter 15: Graphics and Java 2D 15.1 Introduction 15.1 Q1: In the Java coordinate system, the point (0, 0) is: a. The lower-right corner of the screen. b. The upper-right corner of the screen. c. The lower-left corner of the screen. d. The upper-left corner of the screen. Ans: d. The upper-left corner of the screen.
15.2 Graphics Contexts and Graphics Objects 15.2 Q1: The fact that class Graphics is abstract contributes to Java’s portability because: a. drawing is performed differently on every platform that supports Java. A subclass of Graphics must be created that uses the drawing capabilities of the current platform. b. objects of non-abstract classes can only be instantiated on the Windows platform. c. drawing should not be performed on non-Linux platforms. d. Class Graphics is not abstract. Ans: a. drawing is performed differently on every platform that supports Java. A subclass of Graphics must be created that uses the drawing capabilities of the current platform. 15.2 Q2: Which of the following statements about the Graphics object is true? A. The Graphics object is an argument to class Component’s repaint method. B. The Graphics object is instantiated by the user. C. The Graphics object is the argument to a lightweight GUI component's paintComponent method. D. The Graphics class is abstract. E. The Graphics object manages a graphics context. a. A, C, E. b. C, D, E. c. A, B, D, E. d. All are true. Ans: b. C, D, E.
15.3 Color Control 15.3 Q1: Which of the following are valid Java statements? A. Color c = new Color( 0, 255, 0 ); B. Color c = new Color( 0.0f, 1.0f, 0.0f ); C. Color c = new Color( 0.0d, 1.0d, 0.0d ); D. setGreen( c.getGreen() - 2 ); ..
a. All of the above. b. A, B, C. c. A, B, D. d. A, B. Ans: d. A, B. 15.3 Q2: The JColorChooser dialog allows colors to be chosen by all but which of the following? a. Swatches. b. Hue, saturation, brightness. c. Gradient, cycle, brightness. d. Red, Green, Blue. Ans: c. Gradient, cycle, brightness.
15.4 Font Control 15.4 Q1: Which of the following properly create and initialize a Font object? A. Font f = new Font(); B. Font f = new Font( "Serif", Font.Bold + Font.Italic, 19 ); C. Font f = new Font( Font.Bold, 20, "SansSerif" ); D. Font f = new Font( 20, Font.Bold, "Monospaced" ); a. A and B. b. B and C. c. B. d. D. Ans: c. B. 15.4 Q2: Method getFont of class Graphics returns: a. the current font name as a string. b. the font size in points. c. a Graphics object representing the current font. d. a Font object representing the current font. Ans: d. a Font object representing the current font.
Font Metrics 15.4 Q3: Which of the following is correct for font metrics? a. height = descent + ascent + leading. b. The amount the character dips below the baseline is the ascent. c. The amount the character can be above the baseline is the leading. d. The amount the character rises above the baseline is the descent. Ans: a. height = descent + ascent + leading.
..
15.4 Q4: Class FontMetrics declares methods that can be used to obtain the following font metrics: a. ascent, descent and height. b. ascent, descent and leading. c. height and leading. d. All of the above. Ans: d. All of the above.
15.5 Drawing Lines, Rectangles and Ovals 15.5 Q1: The Java statement: g.fillOval( 290, 100, 90, 55 );
a. Draws a filled oval with its center at coordinates x=290, y=100, with height=90 and width=55. b. Draws a filled oval with its left most point at coordinates x=290, y=100, with height=90 and width=55. c. Draws a filled oval bounded by a rectangle with its upper left corner at coordinates x=290, y=100, with width=90 and height=55. d. Draws a filled oval bounded by a rectangle with its upper left corner at coordinates x=290, y=100, with height=90 and width=55. Ans: c. Draws a filled oval bounded by a rectangle with its upper left corner at coordinates x=290, y=100, with width=90 and height=55.
15.5 Q2: The Java statement: g.draw3DRect( 290, 100, 90, 55, true );
a. draws a rectangle that appears to be raised (the top and left edges of the rectangle are slightly darker than the rectangle). b. draws a rectangle that appears to be lowered (the bottom and right edges of the rectangle are slightly darker than the rectangle). c. draws a rectangle that appears to be raised (the bottom and right edges of the rectangle are slightly darker than the rectangle). d. draws a rectangle that appears to be lowered (the top and left edges of the rectangle are slightly darker than the rectangle). Ans: c. draws a rectangle that appears to be raised (the bottom and right edges of the rectangle are slightly darker than the rectangle).
15.6 Drawing Arcs 15.6 Q1: Which of the following statements about arcs is false? a. An arc is drawn as a part of an oval. b. Arcs sweep from a starting angle the number of degrees specified by their arc angle. c. Arcs that sweep clockwise are measured in positive degrees. d. None of the above statements are false. ..
Ans: c. Arcs that sweep clockwise are measured in positive degrees. 15.6 Q2: Which of the following statements draws an arc that sweeps from the top of an oval to the left-most edge? a. g.drawArc( 200, 100, 100, 50, 90, 90 ); b. g.drawArc( 100, 200, 50, 100, 90, 180 ); c. g.drawArc( 100, 200, 50, 100, 180, 90 ); d. g.drawArc( 200, 100, 100, 50, 180, 90 ); Ans: a. g.drawArc( 200, 100, 100, 50, 90, 90 );
15.7 Drawing Polygons and Polylines 15.7 Q1: Consider the code segment below: int xValues[] = { 100, 150, 200, 100 }; int yValues[] = { 30, 130, 30, 30 }; g.drawPolyline( xValues, yValues, 4 );
What kind of figure does it draw? a. A rectangle. b. A triangle. c. A V with its corner at the top. d. A square. Ans: b. A triangle.
15.7 Q2: Consider the Java code segment below: Polygon poly2 = new Polygon(); poly2.addPoint( 100, 30 ); poly2.addPoint( 100, 130 );
Which of the following will create a polygon that is a square? a. poly2.addPoint( 100, 60 ); poly2.addPoint( 100, 130 );
b. poly2.addPoint( 200, 130 ); poly2.addPoint( 200, 30 );
c. poly2.addPoint( 200, 60 ); poly2.addPoint( 200, 130 );
d. poly2.addPoint( 100, 130 ); poly2.addPoint( 100, 230 );
Ans: b. poly2.addPoint( 200, 130 ); poly2.addPoint( 200, 30 );
15.8 Java 2D API 15.8 Q1: Which of the following statements about the Java 2D API is true? ..
a. A Graphics2D object is instantiated to draw Java 2D figures. b. Class Graphics2D is a subclass of class Graphics. c. To access Graphics2D capabilities, cast the Graphics reference passed to paintComponent to a Graphics2D reference. d. All of the above are true. Ans: d. All of the above are true.
Lines, Rectangles, Round Rectangles, Arcs and Ellipses 15.8 Q2: The Graphics2D method(s) that determine(s) the color and texture for the shape to display is/are: a. setStroke b. setPaint c. setTexture and setColor d. setTexturePaint Ans: b. setPaint 15.8 Q3: Which of the following statements is false? a. A BufferedImage object uses the image stored in its associated TexturePaint object as the fill texture for a filled-in shape. b. Class BufferedImage can be used to produce images in color and gray scale. c. Class GradientPath draws a shape in a gradually changing color. d. All of the above are true. Ans: a. A BufferedImage object uses the image stored in its associated TexturePaint object as the fill texture for a filled-in shape.
General Paths 15.8 Q4: A general path is: a. a set of polylines that do not result in a closed shape. b. a shape constructed from straight lines and complex curves. c. the shape of the curve in a font’s characters. d. represented by an object of class GraphicsPath. Ans: b. a shape constructed from straight lines and complex curves. 15.8 Q5: GeneralPath method lineTo a. draws a line from the previous point in the GeneralPath object to the current point. b. draws a line with an arrow head to point to a GeneralPath object. c. moves the drawing origin around a line. d. specifies the first point in a GeneralPath object. Ans: a. draws a line from the previous point in the GeneralPath object to the current point.
..
Java How to Program, 9/e Multiple Choice Test Bank
1 of 6
Chapter 16 Section 16.2 Fundamentals of Characters and Strings 16.2 Q1: Consider the examples below: A. a string. B. 'a string'. C. "a string". D. "1234". E. integer. Which could be the value of a Java variable of type String? a. A and B. b. B and E. c. B and C. d. C and D. ANS: d. C and D. 16.2 Q2: An anonymous String: a. has no value. b. is a string literal. c. can be changed. d. none of the above. ANS: b. is a string literal.
Section 16.3 Class String None
Section 16.3.1 String Constructors 16.3.1 Q1: A String constructor cannot be passed variables of type: a. char arrays. b. int arrays. c. byte arrays. d. Strings. ANS: b. int arrays. 16.3.1 Q2: String objects are immutable. This means they: a. Must be initialized. b. Cannot be deleted. c. Cannot be changed. d. None of the above ANS: c. Cannot be changed.
Section 16.3.2 String Methods length, charAt and getChars 16.3.2 Q1: The length of a string can be determined by: a. The String method length(). b. The String instance variable length. c. The String method strlen(). d. All of the above. ANS: a. The String method length(). 16.3.2 Q2: How many String objects are instantiated by the following code segment (not including the literals)? String s1, output; s1 = "hello";
output = "\nThe string reversed is: "
;
for ( int i = s1.length() - 1; i >= 0; i-- ) output += s1.charAt( i ) + " " ;
a. 1. ..
Java How to Program, 9/e Multiple Choice Test Bank
2 of 6
b. 4. c. 5. d. 7. ANS: d. 7.
Section 16.3.3 Comparing Strings 16.3.3 Q1: The statement
s1.equalsIgnoreCase( s4 )
is equivalent to which of the following? a. s1.regionMatches( true, 0, s4, 0, s4.length() ); b. s1.regionMatches( 0, s4, 0, s4.length() ); c. s1.regionMatches( 0, s4, 0, s4.length ); d. s1.regionMatches( true, s4, 0, s4.length ); ANS: a. s1.regionMatches( true, 0, s4, 0, s4.length() );
16.3.3 Q2: The statement s1.startsWith( "art" )
has the same result as which of the following? a. s1.regionMatches( 0, "art", 0, 3 ); b. s2 = s1.getChars( 0, 3 ); s2.equals( "art" ); c. s1.regionMatches( true, 0, "art", 0, 3 );
d. All of the above ANS: d. All of the above
Section 16.3.4 Locating Characters and Substrings in Strings 16.3.4 Q1: For
String c = "hello world";
The Java statements
int i = c.indexOf( 'o' ); int j = c.lastIndexOf( 'l' );
will result in: a. i = 4 and j = 8. b. i = 5 and j = 8. c. i = 4 and j = 9. d. i = 5 and j = 9. ANS: c. i = 4 and j = 9. 16.3.4 Q2: For
String c = "Hello. She sells sea shells";
The Java statements
int i = c.indexOf( "ll" ); int j = c.lastIndexOf( "ll" );
will result in: a. i = 2 and j = 24. b. i = 3 and j = 24. c. i = 2 and j = 25. d. i = 3 and j = 23. ANS: a. i = 2 and j = 24.
Section 16.3.5 Extracting Substrings from Strings 16.3.5 Q1: For
String c = "Now is the time for all";
The Java statements
String i = c.substring( 7 ); String j = c.substring( 4, 15 );
will result in: a. i = "he time for all" and j = "is the time". b. i = "the time for all" and j = "s the time". c. i = "the time for all" and j = "is the time ". d. i = "he time for all" and j = "s the time". ..
Java How to Program, 9/e Multiple Choice Test Bank
3 of 6
ANS: c. i = "the time for all" and j = "is the time ". 16.3.5 Q2: The String method substring returns: a. A char. b. A String. c. void. d. A char[]. ANS: b. A String.
Section 16.3.6 Concatenating Strings 16.3.6 Q1: Consider the statements below: String a = "JAVA: "; String b = "How to "; String c = "Program";
Which of the statements below will create the String r1 = "JAVA: How to Program"? a. String r1 = c.concat( b.concat( a ) ); b. String r1 = a.concat( b.concat( c ) ); c. String r1 = b.concat( c.concat( a ) ); d. String r1 = c.concat( c.concat( b ) ); ANS: b. String r1 = a.concat( b.concat( c ) );
Section 16.3.7 Miscellaneous String Methods 16.3.7 Q1: Consider the String below: String r = "a toyota";
Which of the following will create the String r1 = "a TOYOTa"? a. String r1 = r.replace( "toyot", TOYOT" ); b. String r1 = r.replace( 't','T' ); r1 = r.replace( 'o','0' ); r1 = r.replace( 'y','Y' ); c. String r1 = r.replace( 't','T' ).replace( 'o', '0' ).replace( 'y', 'Y' ); d. String r1 = r.substring( 2, 4 ).toUpperCase(); ANS: c. String r1 = r.replace( 't','T' ).replace( 'o', '0' ).replace( 'y', 'Y' );
16.3.7 Q2: Which of the following is not a method of class String? a. toUpperCase. b. trim. c. toCharacterArray. d. All of the above are methods of class String. ANS: c. toCharacterArray.
Section 16.3.8 String Method valueOf 16.3.8 Q1: Which of the following will create a String different from the other three? a. String r = "123456" b. int i = 123; int j = 456; String r = String.valueOf(j) + String.valueOf(i); c. int i = 123; int j = 456; String r = String.valueOf(i) + String.valueOf(j); d. int i = 123; int j = 456; String r = i + j; ANS: b. int i = 123; int j = 456; String r = String.valueOf(j) + String.valueOf(i);
Section 16.4 Class StringBuilder 16.4 Q1: StringBuilder objects can be used in place of String objects if: a. The string data is not constant. b. The string data size may grow. c. The programs frequently perform string concatenation. d. All of the above. ..
Java How to Program, 9/e Multiple Choice Test Bank
4 of 6
ANS: d. All of the above.
Section 16.4.1 StringBuilder Constructors 16.4.1 Q1: Given the following declarations:
StringBuilder buf; StringBuilder buf2 = new StringBuilder(); String c = new String( "test" ); Which of the following is not a valid StringBuilder constructor? a. buf = new StringBuilder(); b. buf = new StringBuilder( buf2, 32 ); c. buf = new StringBuilder( 32 ); d. buf = new StringBuilder( c ); ANS: b. buf = new StringBuilder( buf2, 32 );
16.4.1 Q2: Given the following declaration:
StringBuilder buf = new StringBuilder();
What is the capacity of buf? a. 0 b. 10 c. 16 d. 20 ANS: c. 16
Section 16.4.2 StringBuilder Methods length, capacity, setLength and ensureCapacity 16.4.2 Q1: Which of the following statements is true? a. The capacity of a StringBuilder is equal to its length. b. The capacity of a StringBuilder cannot exceed its length. c. The length of a StringBuilder cannot exceed its capacity. d. Both a and b are true. ANS: c. The length of a StringBuilder cannot exceed its capacity. 16.4.2 Q2: Given the following declarations:
StringBuilder buffer = new StringBuilder( “Testing Testing” ); buffer.setLength( 7 ); buffer.ensureCapacity( 5 );
Which of the following is true? a. buffer has capacity 5. b. buffer has capacity 31. c. buffer has content “Testin”. d. buffer has length 15. ANS: b. buffer has capacity 31.
Section 16.4.3 StringBuilder Methods charAt, setCharAt, getChars and reverse 16.4.3 Q1: Consider the statement below:
StringBuilder sb1 = new StringBuilder( "a toyota" );
Which of the following creates a String object with the value "toy"? a. String res = sb1.subString( 2, 5 ); b. char dest[] = new char[ sb1.length() ]; sb1.getChars( 2, 5, dest, 0 ); String res = new String( dest ); c. char dest[] = new char[ sb1.length ]; dest = sb1.getChars( 2, 5 ); String res = new String( dest ); d. char dest[] = new char[ sb1.length() ]; dest = sb1.getChars( 0, 3 ); String res = new String( dest ); ANS: b. char dest[]; sb1.getChars( 2, 4, dest, 0 ); String res = new String( dest );
16.4.3 Q2: To find the character at a certain index position within a String, use the method: a. getChars, with the index as an argument. ..
Java How to Program, 9/e Multiple Choice Test Bank
5 of 6
b. getCharAt, with the index as an argument. c. charAt, with the index as an argument. d. charAt, with the character you are searching for as an argument. ANS: c. charAt, with the index as an argument.
Section 16.4.4 StringBuilder append Methods 16.4.4 Q1: Which of the following creates the string of the numbers from 1 to 1000 most efficiently? a. String s; for ( int i = 1; i <= 1000; i++ ) s += i; b. StringBuilder sb = new StringBuilder( 10 ); for ( int i = 1; i <= 1000; i++ ) sb.append( i ); String s = new String( sb ); c. StringBuilder sb = new StringBuilder( 3000 ); for ( int i = 1; i <= 1000; i++ ) sb.append( i ); String s = new String( sb );
d. All are equivalently efficient. ANS: c. StringBuilder sb = new StringBuilder( 3000 ); for ( int i = 1; i <= 1000; i++ ) sb.append( i ); String s = new String( sb );
Section 16.4.5 StringBuilder Insertion and Deletion Methods 16.4.5 Q1: Consider the statements below:
StringBuilder sb = new StringBuilder( "a toyota" ); sb.insert( 2, "landrover" ); sb.delete( 11, 16 ); sb.insert( 11, " " ); The StringBuilder contents at the end of this segment will be: a. a landrovertoyota. b. a landrover a. c. a landrov a. d. a landrover toy a. ANS: b. a landrover a.
Section 16.5 Class Character 16.5 Q1: Which of the following are static Character methods? a. Character.hashcode( char c ); b. Character.isDigit( char c ); c. Character.equals( char c );
d. All of the above. ANS: b. Character.isDigit( char c ); 16.5 Q2: Which class is not a type-wrapper class? a. Character b. Int c. Double d. Byte ANS: b. Int
Section 16.6 Class StringTokenizer 16.6 Q1: Consider the Java segment:
String line1 = new String( "c = 1 + 2 + 3" ) ; StringTokenizer tok = new StringTokenizer( line1, delimArg ); For the String line1 to have 4 tokens, delimArg should be: a. String delimArg = "+="; b. String delimArg = "123" c. String delimArg = "c+"; d. String delimArg = " "; ANS: a. String delimArg = "+=";
16.6 Q2: Consider the Java segment: ..
Java How to Program, 9/e Multiple Choice Test Bank
6 of 6
String line1 = new String( "c = 1 + 2 + 3" ) ; StringTokenizer tok = new StringTokenizer( line1 ); int count = tok.countTokens();
The value of count is: a. 8. b. 7. c. 13. d. 4. ANS: b. 7. 16.6 Q3: Consider the Java segment:
String line1 = new String( "c = 1 + 2 + 3" ) ; StringTokenizer tok = new StringTokenizer( line1, "+=" );
String foo = tok.nextToken(); String bar = tok.nextToken(); The values of foo and bar are: a. foo is “c ”, bar is “ = ”. b. foo is “c”, bar is “ ”. c. foo is “ = ”, bar is “ + ”. d. foo is “c ”, bar is “ 1 ”. ANS: d. foo is “c ”, bar is “ 1 ”.
Section 16.7 Regular Expressions, Class Pattern and Class Matcher 16.7: Q1: Which of the following is not a word character? a. w b. 0 c. _ d. & ANS: d. &. 16.7 Q2: Which of the following statements is true? a. Ranges of characters can be represented by placing a ~ between two characters. b. [^Z] is the same as [A~Y]. c. Both “A*” and “A+” will match “AAA”, but only “A*” will match an empty string. d. All of above. ANS: c. Both “A*” and “A+” will match “AAA”, but only “A*” will match an empty string.
Replacing Substrings and Splitting Strings 16.7: Q3: Which of the Java strings represent the regular expression ,\s*? a. “\,\s\*”. b. “,\\s*”. c. “,\\s\\*”. d. “.\\s\*”. ANS: b. “,\\s*”.
Classes Pattern and Matcher 16.7: Q4: Which of the following statements is true? a. Class Matcher provides methods find, lookingAt, replaceFirst and replaceAll. b. Method matches (from class String, Pattern or Matcher) will return true only if the entire search object matches the regular expression. c. Methods find and lookingAt (from class Matcher) will return true if a portion of the search object matches the regular expression. d. All of above. ANS: d. All of above.
..
Chapter 17: Files, Streams and Object Serialization 17.1 Introduction 17.1 Q1: Which of the following statements is false? a. Storage of data variables and arrays is temporary. b. Data is lost when a local variable “goes out of scope.” c. Files are used for long-term retention of large amounts of data. d. Data maintained in files is often called transient data. Ans: d. Data maintained in files is often called transient data.
17.2 Data Hierarchy 17.2 Q1: Which of the following statements is false? a. The smallest data item a computer can assume is the value 0 or the value 1. b. The term “bit” is short for “byte digit.” c. Java uses the Unicode character set. d. A record is typically composed of several fields. Ans: b. The term “bit” is short for “byte digit.” 17.2 Q2: Which of the following is arranged in increasing size order? a. field, bit, file, record. b. byte, file, database, record. c. byte, field, file, record. d. bit, field, record, file. Ans: d. bit, field, record, file.
17.3 Files and Streams 17.3 Q1: Which of the following classes is not used for file input? a. FileInputStream b. FileReader c. ObjectInputStream d. Formatter Ans: d. Formatter 17.3 Q2: How do methods setIn, setOut and setErr affect the standard input, output and error streams? a. They output data to the standard input, output and error streams. b. They provide the only way to access the standard input, output and error streams. c. They redirect the standard input, output and error streams. d. They empty the standard input, output and error streams. Ans: c. They redirect the standard input, output and error streams.
..
17.3 Q3: Streams that input bytes from and output bytes to files are known as: a. bit-based streams b. byte-based streams c. character-based streams d. Unicode-based streams Ans: b. byte-based streams
17.4 Class File Creating File Objects 17.4 Q1: Relative paths normally start from which directory? a. The directory in which the application began executing. b. The root directory. c. The directory in which the Java interpreter is installed. d. None of the above. Ans: a. The directory in which the application began executing. 17.4 Q2: Which of the following statements is not equivalent to File name = new File( "c:\\books\\2009\\files.txt" );
Assume we are currently in the directory c:\books. a. File name = new File( "c:\\books\\2009", "files.txt" ); b. File name = new File( "files.txt" ); c. File name = new File( "2009", "files.txt" ); d. All of the above are equivalent to the statement in the question. Ans: b. File name = new File( "files.txt" );
Demonstrating Class File 17.4 Q3: Which of the following is not an application of a File object? a. Open or edit a file. b. Determine if a file exists. c. Determine whether a file is readable. d. Determine whether a file is writable. Ans: a. Open or edit a file.
17.5 Sequential-Access Text Files 17.5.1 Creating a Sequential-Access Text File 17.5.1 Q1: Which statement regarding Java files is false? a. Java imposes no structure on a file. b. Notions like “record” do not exist in Java files. c. The programmer must structure files to meet the requirements of applications. d. Records in a Java sequential file are stored in order by record key. Ans: d. Records in a Java sequential file are stored in order by record key. ..
17.5.1 Q2: When all the contents of a file are truncated, this means that: a. the data in the file is saved to a backup file. b. the file is deleted. c. a FileNotFoundException occurs. d. All the data in the file is discarded. Ans: d. All the data in the file is discarded.
17.5.2 Reading Data from a Sequential-Access Text File 17.5.2 Q1: What does the following statement do? Scanner scanner = new Scanner( new File( "test.txt" ) );
a. Opens a binary file for input. b. Opens a binary file for output. c. Opens a text file for input. d. Opens a text file for output. Ans: c. Opens a text file for input.
17.5.3 Case Study: A Credit-Inquiry Program 17.5.3 Q1: Which of the following statements is true? a. Class Scanner provides the ability to reposition to the beginning of a file with method seek. b. Class Scanner provides the ability to reposition to the beginning of a file with method reposition. c. Class Scanner does not provide the ability to reposition to the beginning of the file. d. If it is necessary to read a sequential file again, the program can simply keep reading— when the end of the file is reached, the Scanner is automatically set to point back to the beginning of the file. Ans: c. Class Scanner does not provide the ability to reposition to the beginning of the file.
17.5.4 Updating Sequential-Access Files 17.5.4 Q1: Records in a sequential file are not usually updated in place. Instead: a. the updated data is placed in a “surrogate” file. b. the entire file is usually rewritten. c. the file is truncated. d. The above statement is false—records in sequential files are usually updated in place. Ans: b. the entire file is usually rewritten.
17.6 Object Serialization 17.6 Q1: Which of the following classes enable input and output of entire objects to or from a file? A. SerializedInputStream ..
B. SerializedOutputStream C. ObjectInputStream D. ObjectOutputStream E. Scanner F. Formatter a. A and B. b. C and D. c. C, D, E, F. d. E and F. Ans: b. C and D. 17.6 Q2: A serialized object is: a. an object represented as a sequence of bytes used to store the object’s data in a file. b. an object in memory that has been recreated from data in a file. c. a standard output stream object used to convert objects in code to data in a file. d. None of the above. Ans: a. an object represented as a sequence of bytes used to store the object’s data in a file. 17.6 Q3: Adding the services of one stream to another is known as a. chaining. b. wrapping. c. adding. d. sequencing. Ans: b. wrapping.
17.6.1 Creating a Sequential-Access File Using Object Serialization Defining the AccountRecordSerializable Class 17.6.1 Q1: What interface must a class implement to indicate that objects of the class can be output and input as a stream of bytes? a. Synchronize. b. Deserializable. c. Serializable. d. IOOutput. Ans: c. Serializable.
17.6.1 Q2: Instance variables that are not to be output with a Serializable object are declared using which keyword? a. private. b. ignoreme. c. transient. ..
d. persistent. Ans: c. transient.
17.6.2 Reading and Deserializing Data from a SequentialAccess File 17.6.2 Q1: What happens when an end-of-file marker is reached (and the program is using an ObjectInputStream to read data from a file)? a. Nothing occurs. b. An end-of-file character is read by the program. c. Method readObject returns the value 0. d. An EOFException is thrown. Ans: d. An EOFException is thrown.
17.8 Opening Files with JFileChooser 17.8 Q1: Which method call enables users to specify that a user can select files and directories from a JFileChooser? a. setFileSelectionMode( FILES_OR_DIRECTORIES ); b. showOpenDialog( FILES_AND_DIRECTORIES ); c. showOpenDialog( FILES_OR_DIRECTORIES ); d. None of the above. Ans: d. None of the above.
17.8 Q2: Which JFileChooser method returns the file the user selected. a. getSelectedFile. b. getFile. c. getOpenDialog. d. showOpenDialog. Ans: a. getSelectedFile.
..
Chapter 18: Recursion 18.1 Introduction 18.1 Q1: A recursive method . a. is a method that calls itself. b. can be called directly. c. can be called indirectly through another method. d. All of the above. Ans: d. All of the above.
18.2 Recursion Concepts 18.2 Q1: When a recursive method is called to solve a problem, the method actually is capable of solving only the simplest case(s), or . a. base case(s). b. base step(s). c. recursive call(s). d. recursion step(s). Ans: a. base case(s). 18.2 Q1: When the recursion step executes: a. this is known as indirect recursion. b. all of the computer’s processes halt until the recursion step has completed executing. c. the original call to the method is still active. d. All of the above. Ans: c. the original call to the method is still active.
18.3 Example Using Recursion: Factorials 18.3 Q1: Which of the following statements about recursion are true? a. Recursion can occur infinitely. b. Recursion uses a termination test. c. Both a and b. d. Neither a nor b. Ans: c. Both a and b. 18.3 Q2: The recursion step should: a. check for the base case. b. call a fresh copy of the recursive method to work on a smaller problem. c. make two calls to the recursive method. d. iterate until it reaches a termination condition. Ans: b. call a fresh copy of the recursive method to work on a smaller problem.
..
18.4 Example Using Recursion: Fibonacci Series 18.4 Q1: The number of calls to recursively calculate the Fibonacci value of 7 is: a. 7 b. 13 c. 41 d. 39 Ans: c. 41 18.4 Q2: The operands of an operator are evaluated: a. from right to left. b. from left to right. c. at the same time. d. in an order that is specific to each operator. Ans: b. from left to right.
18.5 Recursion and the Method Call Stack 18.5 Q1: The current method executing is always the method whose activation record is: a. at the bottom of the stack. b. at the top of the stack. c. never placed on the stack. d. second from the top of the stack, just below the previous method call. Ans: b. at the top of the stack.
18.6 Recursion vs. Iteration 18.6 Q1: Recursion is often less efficient than iteration because: a. it can cause an explosion of method calls. b. it is not as intuitive. c. recursive methods are harder to debug. d. recursive methods take longer to program. Ans: a. it can cause an explosion of method calls. 18.6 Q2: All of the following are true for both recursion and iteration except: a. they have a base case. b. they can cause infinite loops or infinite recursion. c. they are based on a control statement. d. both gradually approach termination. Ans: a. they have a base case.
18.6 Q3: Recursion often is preferable to iteration because a. it is faster. b. it requires less memory. c. it models the problem more logically. d. All of the above. ..
Ans: c. it models the program more logically.
18.7 Towers of Hanoi [*** None ***]
18.8 Fractals 18.8 Q1: Fractals that yield an exact copy of the original when a portion of the original image is magnified are called . a. strictly self similar fractals. b. Koch Curve fractals. c. similar fractals. d. mirror fractals. Ans: a. strictly self similar fractals. 18.8 Q2: Each time a fractal’s pattern is applied to it, the fractal is said to be at a new: a. level. b. depth. c. order. d. All of the above. Ans: d. All of the above. 18.8 Q3: After a fractal’s pattern is applied several times, the shape of the fractal will generally become: a. disjointed and less detailed. b. stabilized and more detailed. c. identical to the original fractal. d. None of the above. Ans: b. stabilized and more detailed.
18.9 Recursive Backtracking 18.9 Q1: In recursive backtracking, if one set of recursive calls does not result in a solution to the problem, what happens? a. The program returns to a previous decision point and makes a different decision. b. The program backs up to the previous decision point and throws an exception. c. The program continues, with unexpected results. d. The program backs up to the original method call. Ans: a. The program returns to a previous decision point and makes a different decision.
..
Java How to Program, 9/e Multiple Choice Test Bank
1 of 3
Chapter 19: Searching, Sorting and Big O
Section 19.1 Introduction 19.1 Q1: Which of the following is a way to sort data? a. Alphabetically. b. In increasing numerical order. c. Based on an account number. d. All of the above. ANS: d. All of the above.
Section 19.2 Searching Algorithms Section 19.2.1 Linear Search 19.2.1 Q1: How many comparisons will the linear search algorithm make if the search key is not in an array of 10 elements? a. 0. b. 10. c. 9. d. 5. ANS: b. 10.
Efficiency of Linear Search 19.2.1 Q3: Which of the following is not a name for a big O run time? a. Constant run time. b.Variable run time. c. Linear run time. d. Quadratic run time. ANS: b. Variable run time. 19.2.1 Q4: What is the efficiency of linear search? a. O(1). b. O(log n). c. O(n). d. O(n2). ANS: c. O(n).
Section 19.2.2 Binary Search 19.3.1 Q1: What is the maximum number of comparisons required to find a search key in a 31-element array? a. 4. b. 5. c. 32. d. 1. ANS: b. 5. 19.3.1 Q2: Which of the following is a negative of binary search? a. It requires significantly more memory than linear search. b. It is slower than linear search. c. The data must be in sorted order. d. None of the above. ANS: c. The data must be in sorted order.
Efficiency of Binary Search 19.2.2 Q3: What is the term used for binary search’s run time? a. Linear run time. b. Quadratic run time. ..
Java How to Program, 9/e Multiple Choice Test Bank
2 of 3
c. Constant run time. d. Logarithmic run time. ANS: d. Logarithmic run time.
Section 19.3 Sorting Algorithms Section 19.3.1 Selection Sort 19.3.1 Q1: What does the first pass of selection sort do? a. Splits the array into two approximately equal pieces. b. Orders the first two elements of the array. c. Partitions the array into two unequal pieces depending on whether each element in the array is greater or less that some pivot element. d. Locates the smallest element in the array and swaps it into the zeroth position. ANS: d. Locates the smallest element in the array and swaps it into the zeroth position. Efficiency of Selection Sort 19.3.1 Q2: What is the efficiency of selection sort? a. O(n2). b. O(n log n). c. O(n). d. O(1). ANS: a. O(n2).
Section 19.3.2 Insertion Sort 19.3.2 Q1: What does each iteration of the insertion sort algorithm do? a. Each iteration takes the next smallest element and inserts it at the beginning of the array. b. Each iteration takes the next element in the unsorted portion of the array and inserts it into the sorted portion. c. Sorted subarrays are inserted into the larger array. d. Each iteration determines the location of a pivot and inserts it into place. ANS: b. Each iteration takes the next element in the unsorted portion of the array and inserts it into the sorted portion.
Efficiency of Insertion Sort 19.3.2 Q3: How much faster is insertion sort with a 15-element array than with a 60-element array? a. 60 times. b. 4 times. c.15 times. d. 19 times. ANS: d. 19 times.
Section 19.3.3 Merge Sort 19.3.3 Q1: What is the base case for the recursive merge sort algorithm? a. Any array that is already sorted. b. A two-element array. c. A one-element array. d. A zero-element array. ANS: c. A one-element array.
Efficiency of Merge Sort 19.3.3 Q2: What is the efficiency of merge sort? a. O(log n). b. O(n). c. O(n log n). d. O(n2). ANS: c. O(n log n). 19.3.3 Q3: Which of the following sorting algorithms is the fastest? a. Selection sort. b. Insertion sort. ..
Java How to Program, 9/e Multiple Choice Test Bank
3 of 3
c. Merge sort. d. They all run at roughly the same speed. ANS: c. Merge sort.
..
Chapter 20 Generic Collections Section 20.1 Introduction 20.1 Q1: Which of these is not an example of a "real-life" collection? a. The cards you hold in a card game. b. Your favorite songs stored in your computer. c. The players on a soccer team. d. The number of pages in a book. ANS: d. The number of pages in a book. Section 20.2 Collections Overview 20.2 Q1: Which statement is false? a. A collection is an object that can hold references to other objects. b. The collection interfaces declare the operations that can be performed on each type of collection. c. Unfortunately, collections discourage software reuse because they are non-portable. d. Collections are carefully constructed for rapid execution and efficient use of memory. ANS: c. Unfortunately, collections discourage software reuse because they are non-portable. 20.2 Q2: The classes and interfaces which comprise the collections framework are members of package ________. a. java.util. b. javax.swing. c. java.collections. d. java.collection. ANS: a. java.util.
Section 20.3 Type-Wrapper Classes for Primitive Types 20.3 Q1: Which statement is false? a. Each primitive type has a corresponding type-wrapper class. b. The type-wrapper classes enable you to manipulate primitive-type values as objects. c. Type-wrapper classes are final, so you cannot extend them. d. The methods for primitive types correspond to the methods for the corresponding type-wrapper classes. ANS: d. The methods for primitive types correspond to the methods for the corresponding type-wrapper classes.
Section 20.4 Autoboxing and Auto-Unboxing 20.4 Q1: Which of the following performs a boxing conversion? a. int x = 7; b. Integer x = 7; c. Neither of the above. d. Both of the above. ANS: b. Integer x = 7; 20.4 Q2: Which of the following performs an unboxing conversion? Assume x refers to an Integer object. a. int y = x; b. Integer y = x; c. Neither of the above. d. Both of the above. ANS: a. int y = x;
..
Section 20.5 Interface Collection and Class Collections 20.5 Q1: A(n) __________ allows a program to walk through the collection and remove elements from the collection. e. Set. f. Queue. g. Iterator. h. List. ANS: c. Iterator. 20.5 Q2: Interface Collection contains __________ operations (i.e., operations performed on the entire collection). a. aggregate. b. composite. c. integral. d. bulk. ANS: d. bulk. Section 20.6 Lists 20.6 Q1: Which statement is false? a. A List is an ordered Collection. b. A List cannot contain duplicate elements. c. A List is sometimes called a sequence. d. Lists are zero based. ANS: b. A List cannot contain duplicate elements. 20.6 Q2: Which of the following does not implement interface List? a. ArrayList. b. LinkedList. c. Vector. d. ListIterator. ANS: d. ListIterator. Section 20.6.1 ArrayList and Iterator 20.6.1 Q1: Which statement is false? a. A ListIterator accesses the elements of a List. b. Class ArrayList is a fixed-size array. c. A LinkedList is a linked list implementation of a List. d. ArrayLists execute faster than Vectors because they are not thread safe. ANS: b. Class ArrayList is a fixed-size array. 20.6.1 Q2: Iterator method __________ determines whether the Collection contains more elements. a. hasNext. b. next. c. contains. d. containsNext. ANS: a. hasNext. THIS QUESTION IS FOR COURSES USING JAVA SE 7: 20.6.1 Q3: Java SE 7 supports type inferencing with the <> notation in statements that declare and create generic type variables and objects. For example, the following line: List< String > list = new ArrayList< String >();
can be written as: a. List<> list = new ArrayList<>(); b. List<> list = new ArrayList< String >(); c. List< String > list = new ArrayList<>();
..
d. List< String > list = new ArrayList(); ANS: c. List< String > list = new ArrayList<>(); Section 20.6.2 LinkedList 20.6.2 Q1: LinkedList method listIterator returns a(n) __________. a. Iterator. b. List. c. sub list. d. bidirectional iterator. ANS: d. bidirectional iterator. 20.6.2 Q2: Which statement is false? a. When a List is backed up with an array, any modifications made through the List view change the array. b. When a List is backed up with an array, any modifications made to the array change the List view. c. The only operation permitted on the view returned by Arrays method asList is delete, which deletes the value from the view and the backing array. d. Adding elements to the view returned by Arrays method asList results in an UnsupportedOperationException. ANS: c. The only operation permitted on the view returned by Arrays method asList is delete, which deletes the value from the view and the backing array.
Section 20.7 Collections Methods 20.7 Q1: The collections framework algorithms are __________, i.e., each of these algorithms can operate on objects that offer given interfaces without concern to the underlying implementations. a. stable. b. lexicographical. c. polymorphic. d. implementation dependent. ANS: c. polymorphic. Section 20.7.1 Method sort 20.7.1 Q1: Collections method sort that accepts a List as an argument sorts the elements of a List, which must implement the __________ interface. a. Comparable. b. Comparator. c. Compare. d. Ordering. ANS: a. Comparable. Sorting in Ascending Order None. Sorting in Descending Order 20.7.1 Q2: Collections method ___________ returns a Comparator object that orders the collection’s elements in reverse order. a. rotate. b. shuffle. c. reverse. d. reverseOrder. ANS: d. reverseOrder. Sorting with a Comparator 20.7.1 Q3: Comparator method compare should return ________ if the first argument is greater than the second argument.
..
a. a positive int value. b. zero. c. a negative int value. d. a String. ANS: a. a positive int value. Section 20.7.2 Method shuffle 20.7.2 Q1: Algorithm __________ randomly orders a List's elements. a. randomShuffle. b. randomPlacement. c. fiftyTwoCardPickup. d. shuffle. ANS: d. shuffle. 20.7.2 Q2: Method shuffle is a member of __________. a. class Arrays. b. class Collections. c. interface Collection. d. Interface List. ANS: b. Class Collections. Section 20.7.3 Methods reverse, fill, copy, max and min 20.7.3 Q1: Class Collections provides algorithms for reversing, filling and copying ________. a. Lists. b. Collections. c. Arrays. d. Stacks. ANS: a. Lists. 20.7.3 Q2: To find the smallest and largest element of a Collection, use Collections methods _________ and __________. a. least, greatest. b. small, large. c. first, last. d. min, max. ANS: d. min, max.
Section 20.7.4 Method binarySearch 20.7.4 Q1: If the desired Object is not found, binarySearch returns __________. a. a positive value b. zero c. a negative value d. an ObjectNotFoundError. ANS: c. A negative value. 20.7.4 Q2: Which statement is false? a. Java does not guarantee which item will be found first when a binarySearch is performed on a List containing multiple elements equivalent to the search key. b. If the search key is found, method binarySearch returns the List index (position relative to 1) of the element containing the search key. c. The binary search algorithm is fast. d. Method binarySearch takes a List as the first argument. ANS: b. If the search key is found, method binarySearch returns the List index (position relative to 1) of the element containing the search key.
..
Section 20.7.5 Methods addAll, frequency and disjoint 20.7.5 Q1: Collections method __________ returns true if two Collections have no elements in common. a. shuffle. b. contains. c. hasCommon. d. disjoint. ANS: d. disjoint. Section 20.8 Stack Class of Package java.util 20.8 Q1: Stack method __________ looks at the top element of a stack without removing that element. a. glance. b. peek. c. look. d. sample. ANS: b. peek. 20.8 Q2: If no elements are in the Stack, method pop throws an __________. a. OutOfMemoryError. b. OutOfMemoryException. c. EmptyStackError. d. EmptyStackException. ANS: d. EmptyStackException. Section 20.9 Class PriorityQueue and Interface Queue 20.9 Q1: Which statement is false? a. Queue is a new collection interface introduced in J2SE 5.0. b. Queue and PriorityQueue are included in the java.util package. c. PriorityQueue orders elements in increasing order, so that smallest value will be the first element removed from PriorityQueue. d. Queue extends interface Collection. ANS: c. PriorityQueue orders elements in increasing order, so that smallest value will be the first element removed from PriorityQueue. 20.9 Q2: PriorityQueue method __________ inserts an element at the appropriate location in the queue. a. offer. b. push. c. poll. d. peek. ANS: a. offer. Section 20.10 Sets Sorted Sets 20.10 Q1: __________ methods enable a program to view a portion of a collection. a. Focus-view. b. Range-view. c. Delimiter-view. d. Subset-view. ANS: b. Range-view. 20.10 Q2: Which statement is false? a. SortedSet extends Set. b. Class SortedSet implements TreeSet.
..
c. When a HashSet is constructed, it removes any duplicates in the Collection. d. By definition, a Set object does not contain any duplicates. ANS: b. Class SortedSet implements TreeSet. Section 20.11 Maps 20.11 Q1: Maps allocate keys to values and cannot contain duplicate keys, i.e., the key-to-value mapping is a __________ mapping. a. many-to-many. b. many-to-one. c. one-to-many. d. one-to-one. ANS: d. one-to-one.
Map Implementation with Hash Tables 20.11 Q2: Which statement about hashing is false? a. Hashing facilitates high-speed storing and retrieval of data. b. Two different data items can hash to the same cell; this is called a collision. c. A load factor of 0.5 usually results in good hashing performance, but less efficient utilization of memory. d. A load factor of 1.0 usually results in good hashing performance, but less efficient utilization of memory. ANS: d. A load factor of 1.0 usually results in good hashing performance, but less efficient utilization of memory. 20.11 Q3: Map method ________ is used to determine whether a map contains a mapping for the specified key. a. containsKey. b. hasKey. c. containsMapping. d. hasMapping. ANS: a. containsKey. Section 20.12 Properties Class 20.12 Q1: A Properties object is a __________ Hashtable object. a. transient. b. persistent. c. polymorphic. d. protected. ANS: b. Persistent. 20.12 Q2: Most objects in Java can now be output and input with Java's object __________. a. encapsulation. b. overloading. c. Serialization. d. reflection. ANS: c. serialization. Section 20.13 Synchronized Collections 20.13 Q1: Which statement is false? a. All built-in collections are synchronized. b. Concurrent access to a Collection by multiple threads could cause indeterminate results or fatal errors. c. To prevent potential threading problems, synchronization wrappers are used around collection classes that might be accessed by multiple threads. d. A synchronization wrapper class receives method calls, adds some functionality for thread safety and then delegates the calls to the wrapped class.
..
ANS: a. All built-in collections are synchronized. Section 20.14 Unmodifiable Collections 20.14 Q1: Which statement is false? a. The Collections API provides a set of public static methods for converting collections to unmodifiable versions. b. Unmodifable wrappers throw ModificationExceptions if attempts are made to modify the collection. c. You can use an unmodifiable wrapper to create a collection that offers read-only access to others while allowing read-write access to yourself. d. You can create the kind of collection mentioned in part (c) simply by giving others a reference to the unmodifiable wrapper while you also retain a reference to the wrapped collection itself. ANS: b. Unmodifable wrappers throw ModificationExceptions if attempts are made to modify the collection. Section 20.15 Abstract Implementations 20.15 Q1: The collections framework provides various __________ collection interfaces from which the programmer can quickly "flesh out" complete customized implementations. a. abstract. b. concrete. c. structured. d. unstructured. ANS: a. abstract.
20.15 Q2: Which of the following is not an abstract implementation provided by the collections framework? a. AbstractCollection. b. AbstractTree. c. AbstractMap. d. AbstractList. ANS: b. AbstractTree.
..
Chapter 21 Generic Classes and Methods Section 21.1 Introduction 21.1 Q1: __________ enable programmers to specify, with a single method declaration, a set of related methods. a. Overloaded methods. b. Overriden methods. c. Generic methods. d. Generics. ANS: c. Generic methods. 21.1 Q2: Generics provide __________ that allows programmers to catch invalid types at compile time. a. compile-time type safety. b. compile-time exception handling. c. compile-time error checking. d. run-time type safety. ANS: a. compile-time type safety. Section 21.2 Motivation for Generic Methods None. Section 21.3 Generic Methods: Implementation and Compile-Time Translation 21.3 Q1: All generic method declarations have a type parameter section delimited by __________. a. curly brackets ({ and }). b. angle brackets (< and >). c. square brackets ([ and ] ). d. parenthesis. ANS: b. angle brackets (< and >). 21.3 Q2: Which statement is false? a. When declaring a generic method, the type parameter section is placed before the return type of the method. b. Each type parameter section contains only one type parameter. c. A type parameter is an identifier that specifies a generic type name. d. Type parameters can represent only reference types. ANS: b. Each type parameter section contains only one type parameter. Section 21.4 Additional Compile-Time Translation Issues: Methods That Use a Type Parameter as the Return Type 21.4 Q1: __________ is the default upper bound of a type parameter. a. String. b. Comparable. c. Class. d. Object. ANS: d. Object. 21.4 Q2: When the compiler translates a generic method into Java bytecodes, it uses __________ to replace the type parameters with actual types. a. erasure. b. compile-time type replacement. c. compile-time type checking. d. compile-time type safety. ANS: a. erasure.
Section 21.5 Overloading Generic Methods
..
21.5 Q1: Which statement is false? a. A generic method may be overloaded. b. A class can provide two or more generic methods that specify the same method name but different method parameters. c. A generic method cannot be overloaded by non-generic methods. d. When the compiler encounters a method call, it searches for the method declaration that most precisely matches the method name and the argument types specified in the call. ANS: c. A generic method cannot be overloaded by non-generic methods. Section 21.6 Generic Classes 21.6 Q1: One generic Stack class could be the basis for creating many Stack classes, e.g., Stack<Double>, Stack<Integer> and Stack<Employee>. These classes are known as __________. a. subclasses. b. generic subclasses. c. concrete classes. d. parameterized classes. ANS: d. parameterized classes. 21.6 Q2: When compiling a generic class, the __________ option should be used to view the unchecked warning message. a. -Xlint:unchecked. b. -X:unchecked. c. -warning:unchecked. d. -unchecked. ANS: a. –Xlint:unchecked. Creating Generic Methods to Test Class Stack< E > None. Section 21.7 Raw Types 21.7 Q1: When a generic class is instantiated without specifying a type argument, it is said to have a __________. a. empty type. b. raw type. c. null type. d. abstract type. ANS: b. raw type. 21.7 Q2: Suppose Stack is a generic class that has one type parameter. The following assignment Stack< Integer > integerStack = new Stack( 10 );
is __________. a. illegal. b. permitted and safe. c. permitted but unsafe, the compiler issues a warning message. d. permitted but unsafe, the runtime environment issues a warning message. ANS: c. permitted but unsafe, the compiler issues a warning message. Section 21.8 Wildcards in Methods That Accept Type Parameters None.
Implementing Method sum With a Wildcard Type Argument in Its Parameter 21.8 Q1: A wildcard type argument is denoted by a(n) __________. a. asterisk (*). b. underscore (_).
..
c. question mark (?). d. caret (^). ANS: c. question mark (?). 21.8 Q2: Which statement is false? a. Parameterized type ArrayList< Number > is a supertype of ArrayList< Integer >. b. ArrayList implements a dynamically resizable, array-like data structure. c. A wildcard represents an “unknown type”. d. Because the wildcard in a method’s header does not specify a type parameter name, you cannot use it as a type name throughout the method’s body. ANS: a. Parameterized type ArrayList< Number > is a supertype of ArrayList< Integer >. Section 21.9 Generics and Inheritance: Notes 21.9 Q1: Which statement is false? a. A generic class can be derived from a non-generic class. b. A non-generic class cannot be derived from a generic class. c. A generic class can be derived from another generic class. d. A generic method in a subclass can override a generic method in a superclass if both methods have the same signatures. ANS: b. A non-generic class cannot be derived from a generic class.
..
Chapter 22: Custom Generic Data Structures Section 22.1 Introduction 22.1 Q1: Which statement is false? a. Linked lists are collections of data items "lined up in a row"⎯insertions and deletions can be made anywhere in a linked list. b. Insertions and deletions are made only at one end of a stack, its top. c. Insertions and deletions are made only at one end of a queue, its tail. d. Binary trees facilitate high-speed searching and sorting of data. ANS: c. Insertions and deletions are made only at one end of a queue, its tail. Section 22.2 Self-Referential Classes 22.2 Q1: A __________ class contains a reference member that refers to an object of the same class type. a. self-determining. b. self-pointing. c. self-linking. d. self-referential. ANS: d. Self-referential. 22.2 Q2: Usually a _________ indicates the end of a data structure. a. backslash character. b. forward slash character c. null reference. d. null pointer. ANS: c. null reference. Section 22.3 Dynamic Memory Allocation 22.3 Q1: Java performs automatic __________ of objects that are no longer referenced in a program. a. memory distribution. b. garbage collection. c. storage compression. d. trash aggregation. ANS: b. Garbage collection. 22.3 Q2: If no memory is available, keyword new throws an __________. a. OutOfMemoryException. b. OutOfMemoryEvent. c. OutOfMemoryExhaustion. d. OutOfMemoryError. ANS: d. OutOfMemoryError. Section 22.4 Linked Lists 22.4 Q1: Which statement is false? a. A linked list is a linear collection of self-referential class objects called nodes connected by reference links. b. A linked list is appropriate when the number of data elements to be represented in the data structure is unpredictable. c. The java.util package contains class LinkedList. d. By convention, the link reference in the last node of a list is set to null to mark the end of the list. ANS: c. The java.util package contains class LinkedList. 22.4 Q2: An isEmpty method you write to test whether a linked list is empty is called a __________ method. a. predefined. b. predicate.
..
c. preemption. d. preorder. ANS: b. predicate. Section 22.5 Stacks 22.5 Q1: A stack is a __________ data structure. a. FILO. b. FOLI. c. LOFI. d. LIFO. ANS: d. LIFO. Stack Class That Inherits from List None. Stack Class That Contains a Reference to a List 22.5 Q2: The technique of implementing each stack method as a call to a List method is called __________. a. delegation. b. delimiting. c. assigning. d. shifting responsibility. ANS: a. Delegation. 22.5 Q3: Which statement is false? a. When a method call is made, the called method must know how to return to its caller, so the return address is pushed onto the program execution stack. b. Stacks support recursive method calls in the same manner as conventional, nonrecursive method calls. c. The program execution stack contains the space created for a method's global variables on each invocation of that method during a program's execution. d. When a method returns to its caller, the memory for that method's local variables is popped off the stack and those variables are no longer known to the program. ANS: c. The program execution stack contains the space created for a method's global variables on each invocation of that method during a program's execution. Section 22.6 Queues 22.6 Q1: A queue is a __________ data structure. a. FOFI. b. FIFO. c. OFIF. d. IFOF. ANS: b. FIFO. 22.6 Q2: Queue nodes are removed only from the __________ of the queue, and are inserted only at the __________ of the queue. a. tail, tail. b. tail, head. c. head, tail. d. head, head. ANS: c. head, tail. 22.6 Q3: Which is not a typical application of queues? a. Routing packets in a computer network. b. File server handling file access requests from many clients. c. High-speed sorting.
..
d. Print spooling. ANS: c. High-speed sorting. Section 22.7 Trees 22.7 Q1: Which statement about trees is false? a. A tree is a nonlinear, two-dimensional data structure. b. Each node in a tree contains two links. c. The children of a node are called siblings. d. A node with no children is called a leaf node. ANS: b. Each node in a tree contains two links. 22.7 Q2: Which statement is false? a. The shape of a binary search tree that corresponds to a set of data can vary, depending on the order in which the values are inserted into the tree. b. A node can be inserted at any point in a binary search tree. c. The process of creating a binary search tree actually sorts the data, and thus this process is called the binary tree sort. d. The binary search tree facilitates duplicate elimination. ANS: b. A node can be inserted at any point in a binary search tree. 22.7 Q3: Which statement is false? a. In a tightly packed binary tree, each level contains about twice as many elements as the previous level. b. When searching a tightly packed 1,000,000-element binary search tree, approximately 20 comparisons need to be made. c. The level-order traversal of a binary tree visits the nodes of the tree row-by-row starting at the root node level. d. Searching a binary tree for a value that matches a key value is slow for loosely packed trees. ANS: d. Searching a binary tree for a value that matches a key value is slow for loosely packed trees.
..
Chapter 23 Applets and Java Web Start Section 23.1 Introduction 23.1 Q1: The browser that executes an applet is generically known as the ________. a. applet storage. b. applet container. c. applet viewer. d. applet executer. ANS: b. applet container.
Section 23.2 Sample Applets Provided with the JDK TicTacToe Applet 23.2 Q1: You can start an applet initially by using the appletviewer. The applet can be restarted by using which of the following Applet menu items? a. save. b. quit. c. tag. d. reload. ANS: d. reload.
DrawTest Applet None.
Java2D Applet None.
Section 23.3 Simple Java Applet: Drawing a String Creating the Applet Class 23.3 Q1: Every Java applet or application is composed of at least one: a. public method b. data member c. public class declaration d. imported class ANS c. public class declaration 23.3 Q2: When an applet container loads an applet, the container calls three of the applet’s methods. In sequence, these three methods are: a. start, init, stop. b. start, init, paint. c. init, start, stop. d. init, start, paint. ANS: d. init, start, paint. Overriding Method paint for Drawing 23.3 Q3: To draw on an applet, the programmer must access the ________ object in the applet's paint method. a. drawstring b. drawLine c. Graphics
..
d. Pixel
ANS: c. Graphics
Section 23.3.1 Executing WelcomeApplet in the appletviewer 23.3.1 Q1: When an applet container encounters an HTML file that specifies an applet to execute, the applet container automatically loads ________ of the applet from the same directory as that of the HTML file. a. the .java file b. the .class file c. the main line d. the .htm file ANS: b. the .class file 23.3.1 Q2: Which of the following will not produce an error when trying to load and run a program with the appletviewer? a. Placing additional characters, such as commas, between the components in the <applet> tag. b. Omitting the ending </applet> tag. c. Creating an applet that is less than 640 pixels by 480 pixels. d. Running the appletviewer with a file name that does not end with .html or .htm . ANS: c. Creating an applet that is less than 640 pixels by 480 pixels.
Section 23.3.2 Executing an Applet in a Web Browser None.
Section 23.4 Applet Life-Cycle Methods 23.4 Q1: Which method is called once by the applet container when an applet is loaded for execution. a. start b. init c. paint d. load ANS: b. init
23.4 Q2: Which method is called by the applet container when the applet is being removed from memory. a. stop b. remove c. destroy d. end ANS: c. destroy
Section 23.5 Initializing an Instance Variable with Method init 23.5 Q1: Which method should be used to draw a line of text on an applet? a. Graphics method drawText. b. Text method drawLine. c. Graphics method drawLine. d. Graphics method drawString. ANS: d. Graphics method drawString. 23.5 Q2: To draw a single black line from (0, 15) to (20, 25), call the method _________ in the paint method. a. g.drawLine( 0, 15, 20, 25 ); b. g.drawString( "black", 0, 15 );
..
c. g.drawLine( 0, 15, 20, 10 ); d. g.drawLine( 15, 0, 25, 20 ); ANS: a. g.drawLine( 0, 15, 20, 25 );
Section 23.6 Sandbox Security Model 23.6 Q1: The Java platform uses the _________ to prevent code that is downloaded to your local computer from accessing local system resources, such as files. a. blackbox security model. b. sandbox security model. c. whitebox security model. d. download security model. ANS: b. sandbox security model.
Section 23.7 Java Web Start and the Java Network Launch Protocol (JNLP) 23.7 Q1: Which of the following is a feature of Java Web Start? a. Desktop integration. b. Automatic updating. c. Draggable applets. d. All of the above. ANS: d. All of the above. 23.7 Q2: A(n) ________ describes the contents of a JAR file and specifies which class is the main-class of an applet for use with Java Web Start. a. HTML document. b. JNLP document. c. .java file. d. .class file. ANS: b. JNLP document.
..
Chapter 24: Multimedia: Applets and Applications 24.1 Introduction 24.1 Q1: Which of the following statements is false? a. The “sizzle” of Java is multimedia. b. Most programming languages do not have built-in multimedia capabilities. c. True three-dimensional multimedia imaging is widely available today. d. Most new computers are sold “multimedia ready” today. Ans: c. True three-dimensional multimedia imaging is widely available today. 24.1 Q2: Which of the following would not be considered multimedia? a. Video. b. Databases. c. Sound. d. Images. Ans: b. Databases.
24.2 Loading, Displaying and Scaling Images 24.2 Q1: Class Image is a(n) a. IconImage. b. concrete. c. transparent. d. abstract. Ans: d. abstract.
class.
24.2 Q2: Method of class Applet returns the location of the HTML file on the Internet as an object of class . a. getDocumentBase, URL. b. getDocumentBase, URI. c. getDocumentLocation, URL. d. getDocumentLocation, URI. Ans: a. getDocumentBase, URL. 24.2 Q3: Image objects are displayed using which Graphics method? a. drawImage. b. paintImage. c. getImage. d. setImage. Ans: a. drawImage. ..
24.3 Animating a Series of Images 24.3 Q1: Stopping animation when the user switches web pages helps to make the applet: a. robust. b. safe. c. browser friendly. d. efficient. Ans: c. browser friendly. 24.3 Q2: The a. Size. b. Dimension. c. PreferredSize. d. MinimumSize. Ans: b. Dimension.
class represents the width and height of a GUI component.
24.4 Image Maps 24.4 Q1: An image map is an image that has accomplish a task. a. cold areas. b. warm areas. c. hot areas. d. bubbles. Ans: c. hot areas.
that the user can click to
24.5 Loading and Playing Audio Clips 24.5 Q1: Which statement about class AudioClip is false? a. Method play plays the audio once. b. Method loop continuously loops the audio clip in the background. c. Method stop terminates an audio clip that is playing. d. Method makeAudioClip returns a reference to an AudioClip. Ans: d. Method makeAudioClip returns a reference to an AudioClip. 24.5 Q2: Which statement is false? a. Applet’s play method can play a sound in an applet. b. AudioClip interface method play can play a sound in an applet. c. AudioClip interface method play loads a sound and plays it once. d. A sound is garbage collected immediately after it is played by AudioClip method play. Ans: d. A sound is garbage collected immediately after it is played by AudioClip method play. ..
24.5 Q3: Which method returns the location of the applet’s .class file? a. getDocumentBase. b. getCodeBase. c. getClassLocation. d. getLocation. Ans: b. getCodeBase.
24.6 Playing Video and Other Media with Java Media Framework 24.6 Q1: Which of the following file types is not used for video? a. Macromedia Flash 2 (.swf). b. QuickTime (.mov). c. Graphics Interchange (.gif). d. MPEG Layer 3 (.mp3). Ans: c. Graphics Interchange (.gif).
Creating a Simple Media Player 24.6 Q2: The JMF offers interface a. VideoClip, javax.media. b. VideoClip, javax.video. c. Player, javax.media. d. Player, javax.video. Ans: c. Player, javax.media.
in package
to play video.
24.6 Q3: Method of interface Player begins the playing of a media file. a. play. b. start. c. begin. d. There is no such method—when the Player object is created, the media file begins playing. Ans: b. start.
..
Java How to Program, 8/e Multiple Choice Test Bank
1 of 4
Chapter 25: GUI, Part 2 Section 25.2 JSlider 25.2 Q1: A JSlider cannot display which of the following: a. Major tick marks. b. Minor tick marks labels. c. Minor tick marks. d. Snap-to ticks. ANS: d. Snap-to ticks. 25.2 Q2: Arrow keys can manipulate a JSlider object. Which of the following statements does not correctly describe how the arrow keys are used? a. The left-arrow and right arrow keys decrease or increase (respectively) the thumb of the JSlider by 1. b. The down-arrow and up-arrow keys decrease or increase (respectively) the thumb of the JSlider by 1. c. The PgDn and PgUp keys decrease or increase (respectively) by block increments of one-tenth of the range of values. d. The Home key and End key move the thumb to the maximum or minimum (respectively) value of the JSlider. ANS: d. The Home key and End key move the thumb to the maximum or minimum (respectively) value of the JSlider. 25.2 Q3: JSliders generate what type of event? a. ActionEvents. b. ChangeEvents. c. WindowEvents. d. MouseEvents. ANS: b. ChangeEvents.
Section 25.3 Windows: Additional Notes 25.3 Q1: A JFrame supports three operations when the user closes the window. Which of the choices below is not one of the three: a. DISPOSE_ON_CLOSE. b. DO_NOTHING_ON_CLOSE. c. LOWER_ON_CLOSE. d. HIDE_ON_CLOSE. ANS: c. LOWER_ON_CLOSE. 25.3 Q2: Which of the following is not one of the seven methods for handling window events? a. windowClosing. b. windowClosed. c. windowOpening. d. windowOpened. ANS: c. windowOpening. 25.3 Q3: Which of the following is false? a. JFrame is a lightweight component. b. JFrame is a subclass of Frame (which is a subclass of Window). c. JFrames have a title bar and a border. d. A JFrame window will look like all other windows displayed on that platform. ANS: a. JFrame is a lightweight component. 25.3 Q4: What happens if setSize is not called on a window? a. The window is displayed at its preferred size. b. It is a syntax error. c. The window is not displayed. d. Only the title bar appears. ANS: d. Only the title bar appears. ..
Java How to Program, 8/e Multiple Choice Test Bank
2 of 4
Section 25.4 Using Menus with Frames 25.4 Q1: Which of the choices below do not complete the sentence correctly? A _________ is a ___________. a. JMenuBar / JComponent. b. JMenuItem / AbstractButton. c. JMenu / JMenuItem. d. JRadioButtonMenuItem / JMenu. ANS: d. JRadioButtonMenuItem / JMenu. 25.4 Q2: Menus are attached to windows by calling method a. addMenuBar. b. setJMenuBar. c. setMenu. d. addJMenuBar. ANS: b. setJMenuBar. 25.4 Q3: Mnemonics can be used with all subclasses of which class? a. AbstractButton. b. JMenu. c. JMenuItem d. JComponent. ANS: a. AbstractButton.
25.4 Q4: The first argument to method showMessageDialog specifies a. the title. b. the message. c. the icon. d. the parent window. ANS: d. the parent window.
Section 25.5 JPopupMenu 25.5 Q1: Which statement below is false? a. Each JPopupMenu should be associated with its own component. b. Local variables must be declared static to be used in an anonymous inner class declaration. c. The JPopupMenu show method specifies the origin component, and the coordinates at which the JPopupMenu should display on the component. d. None of the above. ANS: b. Local variables must be declared static to be used in an anonymous inner class declaration. 25.5 Q2: Which method returns true if the popup trigger event occurred? a. isTrigger. b. isPopup. c. isPopupTrigger. d. isTriggerEvent. ANS: c. isPopupTrigger.
Section 25.6 Pluggable Look-and-Feel 25.6 Q1: Which of the following is not a Java AWT portability issue? a. GUI components that have different looks on different platforms may use different amounts of space. b. GUI components may have different default functionality. c. Different platforms may have different representations of integers. d. All of the above. ANS: c. Different platforms may have different representations of integers. 25.6 Q2: Which of the following is not a class UIManager method? a. LookAndFeelInfo(). ..
Java How to Program, 8/e Multiple Choice Test Bank
3 of 4
b. getInstalledLookAndFeels(). c. setLookAndFeel(). d. getLookAndFeel(). ANS: a. LookAndFeelInfo(). 25.6 Q3: Which of the following is not a look-and-feel? a. Windows. b. Motif. c. Metal. d. None of the above. ANS: d. None of the above.
Section 25.7 JDesktopPane and JInternalFrame 25.7 Q1: Which constructor below creates a JInternalFrame that is resizable, closable, maximizable, and minimizable? a. JInternalFrame frame = new JInternalFrame("Internal Frame", true, true, true, true); b. JInternalFrame frame = new JInternalFrame("Internal Frame", true, true, false, true); c. JInternalFrame frame = new JInternalFrame("Internal Frame", true, true, true, false); d. JInternalFrame frame = new JInternalFrame("Internal Frame", false, false, true, true); ANS: a. JInternalFrame frame = new JInternalFrame("Internal Frame", true, true, true, true); 25.7 Q2: In a multiple-document interface (MDI), a JDesktopPane is the parent window and what class is the child window? a. JChild. b. JInternalFrame. c. JChildWindow. d. JFrame. ANS: b. JInternalFrame.
Section 25.8 JTabbedPane 25.8 Q1: A JTabbedPane a. arranges GUI components into layers such that only one layer is visible at a time. b. allows users to access a layer of GUI components via a tab. c. extends JComponent. d. All of the above. ANS: d. All of the above. 25.8 Q2: By default, the tabs on a JTabbedPane appear at the: a. top. b. bottom. c. left. d. right. ANS: a. top.
Section 25.9 Layout Managers: BoxLayout and GridBagLayout BoxLayout layout manager
25.9 Q1: To evenly distribute fixed size components in a row using BoxLayout, use the method: a. createVerticalStrut(). b. createHorizontalStrut(). c. createVerticalGlue(). d. createHorizontalGlue(). ANS: d. createHorizontalGlue().
..
Java How to Program, 8/e Multiple Choice Test Bank
4 of 4
25.9 Q2: To create a fixed space between all components using BoxLayout, use the method: a. createVerticalStrut(). b. createHorizontalStrut(). c. createGlue(). d. createRigidArea(). ANS: d. createRigidArea(). GridBagLayout Layout Manager
25.9 Q3: Which of the following GridBagConstraints specifies the number of columns a component will occupy? a. gridwidth. b. gridheight. c. weightx. d. weighty. ANS: a. gridwidth. 25.9 Q4: What is the default value for the GridBagConstraint fill? a. NONE. b. BOTH. c. CENTER. d. HORIZONTAL. ANS: a. NONE. GridBagConstraints constants RELATIVE and REMAINDER
25.9 Q5: What GridBagConstraints constants can be used in place of gridx and gridy? a. RELATIVE and REMAINDER. b. CENTER and BOTH. c. NORTH and SOUTH. d. FILL and NONE. ANS: a. RELATIVE and REMAINDER. 25.9 Q6: The GridBagContraints constant RELATIVE means that a. The component is the last component. b. The component is the next to last component. c. The component should be placed relative to the previous component. d. Both b and c. ANS: d. Both b and c.
..
Java How to Program, 9/e Multiple Choice Test Bank
1 of 4
Chapter 26, Multithreading 26.1 Introduction No questions.
26.2 Thread States: Life Cycle of a Thread 26.2 Q1: A new thread begins its life cycle by transitioning to the __________ state. a. runnable. b. waiting. c. terminated. d. new. ANS: d. new. 26.2 Q2: With timeslicing, each thread is given a limited amount of time, called a __________, to execute on a processor. a. Quantum. b. Processor burst. c. Time allocation. d. Scheduling interval. ANS: a. Quantum.
26.3 Creating and Executing Threads with Executor Framework 26.3 Q1: The preferred means of creating multithreaded Java applications is by implementing the ________ interface. An object of a class that implements this interface represents a task to perform. a. Thread. b. Runner. c. Runnable. d. None of the above. ANS: c. Runnable. 26.3 Q2: The main method executes in the ________ thread of execution. a. starting b. main c. local d. None of the above. ANS: b. main. 26.3 Q3: An ExecutorService object is created by calling a static method of which class? a. Executor. b. Executors. c. ExecutorService. d. Thread. ANS: b. Executors. 26.3 Q4: Which of the following is not true of ExecutorService? a. It is a subinterface of Executor. b. It is an object that can be run in a separate thread. c. It declares method shutdown. d. It manages a group of threads. ANS: b. It is an object that can be run in a separate thread.
26.4 Thread Synchronization 26.4 Q1: When a __________ method or block is running on an object, the object is locked so no other such method can run on that object at the same time. a. synchronized. b. shared. ..
Java How to Program, 9/e Multiple Choice Test Bank
2 of 4
c. thread. d. writeable. ANS: a. synchronized. 26.4 Q2: When using Java's built-in monitors, every object has a(n) ________ or a(n) ________ that the monitor ensures is held by a maximum of only one thread at any time. a. monitor lock, intrinsic lock. b. built-in lock, free lock. c. mutual exlcusion lock, synchronization lock. d. None of the above. ANS: a. monitor lock, intrinsic lock.
26.4.1 Unsynchronized Data Sharing 26.5.1 Q1: Interface ExecutorService provides the ________ method, which returns control to its caller either when all tasks executing in the ExecutorService complete or when the specified timeout elapses. a. waitForTermination. b. wait. c. awaitTermination. d. None of the above. ANS: c. awaitTermination.
26.4.2 Synchronized Data Sharing—Making Operations Atomic 26.5.2 Q1: You can simulate atomicity by ensuring that ________. a. at least one thread carries out its operations on an object at a time. b. two threads carry out their operations on an object in parallel. c. only one thread carries out its operations on an object at a time. d. None of the above. Ans: c. only one thread carries out its operations on an object at a time.
26.5 Producer/Consumer Relationship without Synchronization 26.5 Q1: In a producer/consumer relationship, the ________ portion of an application generates data and stores it in a shared object, and the ________ portion of an application reads data from the shared object. a. consumer, producer. b. producer, consumer. c. outputter, inputter. d. None of the above. Ans: b. producer, consumer.
26.6 Producer/Consumer Relationship: ArrayBlockingQueue 26.6 Q1: The BlockingQueue interface declares which two methods for blocked adding and blocked removing of elements from a circular buffer? a. put and take. b. add and remove. c. push and pop. d. place and get. ANS: a. put and take. 26.6 Q2: The ArrayBlockingQueue method ________ returns the number of elements currently in the ArrayBlockingQueue? a. size. b. length. c. getSize. d. getLength. ANS: a. size. 26.6 Q3: In a producer/consumer relationship with a single cell of shared memory, which of the following is true? a. The consumer must run first. b. The producer must run first. ..
Java How to Program, 9/e Multiple Choice Test Bank
3 of 4
c. The producer must run first or the consumer will have to wait. d. The consumer must run first or the producer will have to wait. ANS: c. The producer must run first or the consumer will have to wait.
26.7 Producer/Consumer Relationship with Synchronization 26.7 Q1: When a thread obtains the monitor lock on an object, then determines that it cannot continue with its task on that object until some condition is satisfied, the thread can call Object method ________; this releases the monitor lock on the object, and transitions the thread waits to the waiting state. a. waitForOtherThreads. b. stop. c. waitForCondition. d. wait. ANS: d. wait. 26.7 Q2: When a thread executing a synchronized statement (or method) completes or satisfies the condition on which another thread may be waiting, it can call Object method ________ or ________ to allow a waiting thread or all waiting threads to transition to the runnable state again. a. notifyThread, notifyAllThreads. b. wakeUpThread, wakeUpAllThreads. c. notify, notifyAll. d. None of the above. ANS: c. notify, notifyAll.
26.8 Producer/Consumer Relationship: Bounded Buffers 26.8 Q1: Which one of the following statements is true with regard to a producer/consumer relationship with one producer and one consumer? a. A producer can never produce faster than the consumer is consuming. b. A consumer can never consume faster than the producer is producing. c. A producer can produce more items than a consumer consumes. d. A consumer can consume more items than a producer produces. ANS: c. A producer can produce more items than a consumer consumes. 26.8 Q2: Which of the following is true for a correct producer/consumer relationship with one producer, one consumer, and a 5-cell buffer? a. The producer can produce when all cells are full. b. The consumer can consume when all cells are full. c. The consumer can consume when all cells are empty. d. None of the above. ANS: b. The consumer can consume when all cells are full.
26.9 Producer/Consumer Relationship: The Lock and Condition Interfaces 26.9 Q1: This class is used to help implement mutual exclusion. a. MutEx. b. Condition. c. Lock. d. Signal. ANS: c. Lock. 26.9 Q2: If a thread calls __________, then every thread waiting for the object becomes eligible to acquire the lock. a. signalEach. b. signalAll. c. signal. d. signalMethods. ANS: b. signalAll. 26.9 Q3: In a producer/consumer relationship, when a consumer finds the buffer empty or finds that the previous data has already been read, the consumer should call __________. a.lock. b.signal. ..
Java How to Program, 9/e Multiple Choice Test Bank
4 of 4
c.sleep. d.await. ANS: d. await.
26.10 Concurrent Collections Overview No Questions
26.11 Multithreading with GUI 26.11 Q1: The ________ thread should be used to perform all tasks that manipulate GUI components, because they are not thread safe. a. event-handling. b. event-dispatch. c. GUI-handling. d. None of the above. ANS: b. event-dispatch. 26.11 Q2: SwingWorker method ________ executes a long computation in a worker thread. a. execute. b. performCalculation. c. doInBackground. d. None of the above. ANS: c. doInBackground.
26.12 Other Classes and Interfaces in java.util.concurrent 26.12 Q1: The submit method, when passed a Callable, returns an object of this type. a. Future. b. Callable. c. Runnable. d. Executor. ANS: a. Future. 26.12 Q2: The Callable interface declares this method. a. get. b. call. c. run. d. execute. ANS: b. call.
..
Java How to Program, 9/e Multiple Choice Test Bank
1 of 3
Chapter 27: Networking Section 27.1 Introduction 27.1 Q1: __________ sockets and the __________ protocol are more desirable for the vast majority of Java programmers. a. Stream, UDP. b. Stream, TCP. c. Datagram, UDP. d. Datagram, TCP. ANS: b. Stream, TCP. 27.1 Q2: Which statement is false? a. With datagram sockets a process establishes a connection to another process. b. The TCP protocol is used for transmission with stream sockets. c. The UDP protocol is used for transmission with datagram sockets. d. With the UDP protocol packets can be lost, duplicated or even arrive out of sequence. ANS: a. With datagram sockets a process establishes a connection to another process.
Section 27.2 Manipulating URLs 27.2 Q1: Using a URL as an argument to the __________ method of interface AppletContext causes the browser in which an applet is executing to display the URL. a. showURL. b. showFile. c. showHTML. d. showDocument. ANS: d. showDocument. 27.2 Q2: A(n) _________ is thrown when a String that is not in proper URL format is passed to a URL constructor. a. URLError. b. MalformedURLException. c. URLException. d. IllFormedURLException. ANS: b. MalformedURLException.
Section 27.3 Reading a File on a Web Server 27.3 Q1: Which statement is false? Normally, an applet __________. a. is allowed to read files only on the server from which the applet was downloaded. b. can read files on any server that can be reached over the network. c. cannot read files on the system on which it executes. d. has different file access rights than an application running on the same machine. ANS: b. can read files on any server that can be reached over the network. 27.3 Q2: A JEditorPane generates HyperlinkEvents only if it is __________. a. invisible. b. visible. c. uneditable. d. editable. ANS: c. uneditable.
Section 27.4 Establishing a Simple Server Using Stream Sockets 27.4 Q1: Once the ServerSocket is created, the server can listen indefinitely (or block) for an attempt by a client to connect. This is accomplished with a call to the ServerSocket method __________. a. connect. b. block. c. accept . d. listen. ANS: c. accept. ..
Java How to Program, 9/e Multiple Choice Test Bank
2 of 3
Section 27.5 Establishing a Simple Client Using Stream Sockets 27.5 Q1: If an ObjectInputStream is used to read information from the server, an __________ is generated when the client attempts to read a value from a stream on which end-of-stream is detected. a. EOF. b. EOS. c. EOFException. d. EOSException. ANS: c. EOFException. 27.5 Q2: A(n) __________ is thrown when a server address indicated by a client cannot be resolved. a. ConnectException. b. ServerException. c. MalformedURLException. d. UnknownHostException. ANS: d. UnknownHostException.
Section 27.6 Client/Server Interaction with Stream Socket Connections 27.6 Q1: Output __________ are typically used to increase the efficiency of an application by sending larger amounts of data fewer times. a. objects. b. broadcasters. c. buffers. d. None of the above. ANS: c. buffers. 27.6 Q2: The Internet address 127.0.0.1 is also known as __________. a. localhost. b. remotehost. c. localserver. d. remoteserver. ANS: a. localhost. 27.6 Q3: The port number at which the server waits for connections is often called the __________ point. a. handhold. b. handshake. c. handoff. d. handle. ANS: b. handshake.
Section 27.7 Connectionless Client/Server Interaction with Datagrams 27.7 Q1: Which statement is false? a. Streams-based transmission is connection-oriented. b. Connection-oriented transmission is like the telephone system. c. Datagram-based transmission is connection oriented. d. Connectionless transmission is like the way the mail is carried by the postal service. ANS: c. Datagram-based transmission is connection oriented. 27.7 Q2: Specifying a port that is already in use or specifying an invalid port number when creating a DatagramSocket results in a __________. a. SocketException. b. PortInUseException. c. PortException. d. ConnectException. ANS: a. SocketException.
..
Java How to Program, 9/e Multiple Choice Test Bank
3 of 3
Section 27.8 Client/Server Tic-Tac-Toe Using a Multithreaded Server 27.8 Q1: To be able to send and receive messages in parallel over a network connection, a program must use __________ of execution. a. one thread. b. two threads. c. three threads. d. four threads. ANS: b. two threads.
..
Chapter 28 Accessing Databases with JDBC Section 28.1 Introduction 28.1 Q1: Java programs communicate with databases using what API? a. DBMS. b. JDBC. c. RDBMS. d. Database. ANS: b. JDBC. 28.1 Q2: Which of the following is a key benefit of using JDBC? a. It is a simple-to-use database management system. b. Allows developers to change the underlying database without modifying the Java code. c. It is a multi-platform database management system. d. It provides a GUI for database management systems. ANS: b. Allows developers to change the underlying database without modifying the Java code. Section 28.2 Relational Databases 28.2 Q1: A ________ is a column (or set of columns) which have a unique value that cannot be duplicated in other rows? a. Primary key. b. Query. c. SQL statement. d. Lookup value. ANS: a. Primary key. 28.2 Q2: To obtain data from a table, you ________ the database? a. select. b. query. c. get. d. None of the above. ANS: b. Query. 28.2 Q3: What does a primary key do? a. Identifies each row of a table. b. Selects a number of rows from a database. c. Stores a bunch of related data. d. None of the above. ANS: a. Identifies each row of a table. Section 28.3 Relational Database Overview: The books Database 28.3 Q1: What is the name of a key in one table that is required to matche a primary key in another table? a. Foreign key. b. Matching key. c. Joined key. d. Linking key. ANS: a. Foreign key. 28.3 Q2: Which of the following states the Rule of Entity Integrity? a. Every row must have a value for the primary key and each value must be unique. b. Every foreign key must appear as another table’s primary key. c. Every row must have a value for the primary key and values may be repeated. d. None of the above. ANS: a. Every row must have a value for the primary key and each value must be unique.
..
28.3 Q3: What is the relationship between a primary key and its corresponding foreign keys? a. One-to-one. b. Many-to-one. c. Many-to-many. d. One-to-many. ANS: d. One-to-many. Section 28.4 SQL 28.4 Q1: Which SQL keyword is used to merge rows from multiple tables? a. JOIN. b. INNER JOIN. c. GROUP. d. MERGE. ANS: b. INNER JOIN. 28.4 Q2: Which SQL keyword is required in every query? a. FROM. b. WHERE. c. ORDER BY. d. LIKE. ANS: a. FROM. Section 28.4.1 Basic SELECT Query 28.4.1 Q1: Which symbol indicates that all columns should be retrieved? a. ? b. * c. + d. / ANS: b. * 28.4.1 Q2: To retrieve specific columns from a table, use _________ to separate the column names. a. ? b. * c. , d. ANS: c. , Section 28.4.2 WHERE Clause 28.4.2 Q1: Selection criteria can be added to a SQL query using which keyword? a. FROM. b. WHERE. c. SELECT. d. LIKE. ANS: b. WHERE. 28.4.2 Q2: Pattern matching in a SQL query is performed with which clause? a. FROM. b. WHERE. c. SELECT. d. LIKE. ANS: d. LIKE.
Section 28.4.3 ORDER BY Clause 28.4.3 Q1: The result of a query can be sorted by using the optional _________ clause. a. ORDER BY. ..
b. ORDER. c. SORT BY. d. SORT. ANS: a. ORDER BY. 28.4.3 Q2: The default sort order in a sorted query is _________. a. ascending. b. descending. c. natural. d. None of the above. ANS: a. ascending. Section 28.4.4 Merging Data from Multiple Tables: INNER JOIN 28.4.4 Q1: When joining tables, the _________ clause specifies the columns from each table that are
compared to determine which rows are merged. a. ON. b. WHERE. c. LIKE. d. GROUP. ANS: a. ON.
28.4.4 Q2: If a query includes columns from multiple tables that have the same name, the statement must precede those column names with _________. a. their database names. b. their database names and a dot. c. their table names and a dot. d. their table names. ANS: c. their table names and a dot. Section 28.4.5 INSERT Statement 28.4.5 Q1: This keyword is used to add a row to a table. a. INSERT. b. ADD. c. UPDATE. d. CREATE. ANS: a. INSERT. 28.4.5 Q2: SQL uses the _________ as a delimiter for strings. a. double quotes (" and "). b. single quotes (' and '). c. underscore (-). d. percent (%). ANS: b. single quotes (' and '). Section 28.4.6 UPDATE Statement 28.4.6 Q1: In an UPDATE statement, the SET keyword is followed by _________. a. a comma-separated list of column value-name pairs in the format value = columnName. b. a comma-separated list of column name-value pairs in the format columnName = value. c. a semicolon-separated list of column value-name pairs in the format value = columnName. d. a semicolon-separated list of column name-value pairs in the format columnName = value. ANS: b. a comma-separated list of column name-value pairs in the format columnName = value. Section 28.4.7 DELETE Statement 28.4.7 Q1: Which statement is false? a. A DELETE statement removes rows from a table. b. A DELETE statement must specify the table from which to delete. ..
c. A DELETE statement starts with the keyword DELETE. d. A WHERE clause must be present in a DELETE statement. ANS: d. A WHERE clause must be present in a DELETE statement. Section 28.5 Instructions to install MySQL and MySQL Connector/J No Questions. Section 28.6 Instructions on Setting MySQL User Account No Questions. Section 28.7 Creating Database books in MySQL No Questions. Section 28.8 Manipulating Databases with JDBC No Questions. Section 28.8.1 Connecting to and Querying a Database 28.8.1 Q1: Classes and interfaces for the JDBC API can be found in which package? a. java.jdbc. b. javax.jdbc. c. java.sql. d. java.sql.jdbc. ANS: c. java.sql. 28.8.1 Q2: What exception is thrown if the class loader cannot locate the driver class? a. NoSuchClassException. b. ClassCastException. c. ClassNotFoundException. d. IllegalClassException. ANS: c. ClassNotFoundException.
Section 28.8.2 Querying the books Database 28.8.2 Q1: Which constants are used to indicate that a ResultSet is scrollable, insensitive to changes and read only? a. TYPE_SCROLLABLE_INSENSITIVE, CONCUR_READ_ONLY. b. TYPE_SCROLLABLEINSENSITIVE, CONCUR_READONLY. c. TYPE_SCROLL_INSENSITIVE, CONCUR_READ_ONLY. d. TYPE_SCROLL_INSENSITIVE, CONCUR_READONLY. ANS: d. TYPE_SCROLL_INSENSITIVE, CONCUR_READONLY. 28.8.2 Q2: Initially, a ResultSet cursor is positioned _________. a. before the first row. b. at the first row. c. at the last row. d. after the last row. ANS: a. before the first row. Section 28.9 RowSet Interface 28.9.1 Q1: The _________ interface configures the database connection and prepares query statements automatically. a. ResultSet. b. RowSet. c. Both of the above. d. Neither of the above. ANS: b. RowSet. ..
28.9.1 Q2: Which statement is false? a. Interface JdbcRowSet is in the javax.rowset package. b. A CachedRowSet object is scrollable and updatable by default. c. A JdbcRowSet object is scrollable and updatable by default. d. JdbcRowSet is a connected RowSet. ANS: a. Interface JdbcRowSet is in the javax.rowset package. Section 28.10 Java DB/Apache Derby No Questions. Section 28.11 PreparedStatements 28.11 Q1: In a PreparedStatement, parameters are counted from position ________. a. 0. b. 1. c. 2. d. 3. ANS: b. 1. 28.11 Q2: JDBC 4 supports _______, so you do not need to manually load the database driver before accessing a database. a. automatic driver downloading. b. automatic driver creation. c. automatic driver discovery. d. None of the above. ANS: c. automatic driver discovery. 28.11 Q3: PreparedStatement method ________ returns a ResultSet. a. executeUpdate. b. executeQuery. c. execute. d. None of the above. ANS: b. executeQuery. Section 28.12 Stored Procedures 28.12 Q1: What are individual SQL statements saved in a database called? a. Stored statements. b. Stored queries. c. Stored commands. d. Stored procedures. ANS: d. Stored procedures.
28.12 Q2: SQL statements that are stored in a database can be invoked using an object that implements interface ________. a. Callable. b. StoredStatement. c. CallableStatement. d. Connection. ANS: c. CallableStatement. Section 28.13 Transaction Processing
..
28.13 Q1: Transaction processing enables a program to ________ or ________ a transaction based on whether the transaction was successful? a. save, delete. b. commit, rollback. c. save, rollback. d. commit, delete. ANS: d. commit, rollback. 28.13 Q2: Transaction processing enables a program to treat a database operation, or set of operations, as single operation. This is known as a(n) ________ or a(n) ________. a. atomic operation, unique operation. b. unique operation, transaction. c. atomic operation, transaction. d. None of the above. ANS: d. atomic operation, transaction.
..
29 Java Server Faces Web Applications 29.1 Introduction No questions. 29.2 HyperText Transfer Protocol (HTTP) Transactions 29.2 Q1: For security reasons, the path in a URL normally represents a(n) ________ on the server. a. Actual directory. b. Virtual directory. c. File. d. None of the above. Ans: b. URLs (Uniform Resource Locators). 29.2 Q2: A ________ maintains a database of hostnames and their corresponding IP addresses. a. file. b. database. c. DNS server. d. None of the above. Ans: c. DNS server. 29.3 Multitier Application Architecture 29.3 Q1: The three typical tiers in a web application are ________, ________ and ________. a. user interface tier, business logic tier, information tier. b. browser tier, server tier, information tier. c. client tier, middle tier, top tier. d. None of the above. Ans: a. user interface tier, business logic tier, information tier.
29.4 Your First JSF Web App 29.4 Q1: Which of the following is true? a. When you invoke a JSF app from a web browser for the first time, the browser requests the app’s default JSF page. b. When a web server receives a request for a JSF app, it passes the request to the JSF web-application framework for processing. c. The JSF framework includes the Faces servlet—a software component running on the server that processes each requested JSF page so that the server can eventually return a response to the client. d. All of the above. Ans: d. All of the above.
29.4.1 The Default index.xhtml Document: Introducing Facelets ..
29.4.1 Q1: Which of the following is true? a. Facelets are a combination of XHTML markup and JSF markup. b. XHTML combines a page's content with its presentation. c. You cannot dynamically insert values into a Facelets page. d. None of the above. Ans: a. Facelets are a combination of XHTML markup and JSF markup. 29.4.2 Examining the WebTimeBean Class 29.4.2 Q1: ________ are instances of classes that follow certain conventions for class design. a. Properties. b. JavaBeans objects. c. JSF elements. d. None of the above. Ans: b. JavaBeans objects. 29.4.2 Q2: A JavaBean exposes its data to a JSF document as ________. a. Properties. b. JavaBeans objects. c. JSF elements. d. None of the above. Ans: a. Properties. 29.4.3 Building the WebTime JSF Web App in NetBeans No questions. 29.5 Model-View-Controller Architecture of JSF Apps 29.5 Q1: ________ architecture separates application’s from the graphical presentation and the processing logic. a. Data-Presentation-Logic. b. Data-View-Controller. c. Model-View-Controller. d. None of the above. Ans: c. Model-View-Controller. 29.6 JSF Components 29.6 Q1: A(n) ________ arranges elements in an XTHML table containing rows with a specified number of columns. a. h:panelGrid. b. h:table. c. h:grid. d. None of the above. Ans: a. h:panelGrid. 29.6 Q2: Which of the following is true? a. An app's images and CSS files can be placed in any folder of the app. ..
b. An app's images and CSS files are placed in the app's resources folder within the Web Pages node. c. An app's images and CSS files are placed in the subfolders of the app's resources folder within the Web Pages node. d. None of the above. Ans: c. An app's images and CSS files are placed in the subfolders of the app's resources folder within the Web Pages node.. 29.7 Validation Using Validator Components and Custom Validators 29.7 Q1: A ________ determines whether a field contains an acceptable number of characters. a. f:validateDoubleRange. b. f:validateLength. c. f:validateLongRange. d. None of the above. Ans: b. f:validateLength. 29.7 Q2: A ________ determines whether a field contains an integer value in an acceptable range. a. f:validateDoubleRange. b. f:validateLength. c. f:validateLongRange. d. None of the above. Ans: b. f:validateLongRange. 29.8 Session Tracking 29.7 Q1: Tracking individual clients as they visit a website is known as ________. a. session tracking. b. client tracking. c. personalization. d. None of the above. Ans: a. session tracking. 29.8.1 Cookies 29.8.1 Q1: A cookie is ________. a. something you eat. b. a piece of data that maintains information about a client during and possibly between browser sessions. c. a piece of data that maintains information about all the servers that a client visits. d. None of the above. Ans: b. a piece of data that maintains information about a client during and possibly between browser sessions. 29.8.2 Session Tracking with @SessionScoped Beans 29.7.2 Q1: Which of the following is true? a. An @RequestScoped bean can be access by all of an app's pages during a session. ..
b. Sessions never expire. c. An @SessionScoped is created when a session begins and exists throughout the entire session. d. None of the above. Ans: c. An @SessionScoped is created when a session begins and exists throughout the entire session.
..
30 Ajax-Enabled JSF Web Applications 30.1 Introduction No questions. 30.2 Accessing Databases in Web Applications No questions. 30.2.1 Setting Up the Database 30.2.1 Q1: Which of the following is true? a. You should maintain a separate database connection for each client request. b. You should maintain a connection pool that allows the server to manage a limited number of database connections and share them among requests. c. You should never connect to databases from web apps. d. None of the above. Ans: b. You should maintain a connection pool that allows the server to manage a limited number of database connections and share them among requests. 30.2.2 @ManagedBean Class AddressBean 30.2.2 Q1: The ________ annotation allows you to inject a DataSource into a managed bean. a. @Resource. b. @DataSource. c. @Database. d. None of the above. Ans: a. @Resource. 30.2.3 index.xhtml Facelets Page 30.2.3 Q1: The ________ element displays a collection's data in tabular format. a. h:table. b. h:collection. c. h:dataTable. d. None of the above. Ans: c. h:dataTable. 30.2.4 addentry.xhtml Facelets Page No questions. 30.3 Ajax 30.3 Q1: Ajax separates the user interaction portion of an application from its server interaction, enabling both to proceed ________. a. synchronously. b. asynchronously in parallel. c. without any interaction whatsoever. d. None of the above. ..
Ans: b. asynchronously in parallel. 30.3 Q2: The ________ enables the asynchronous exchanges with the web server that make Ajax applications so responsive. a. HttpRequestObject. b. XMLHttpRequest. c. XMLHttpRequestObject. d. None of the above. Ans: c. XMLHttpRequestObject. 30.4 Adding Ajax Functionality to the Validation App 30.4 Q1: The f:ajax element's ________ attribute specifies a space-separated list of element ids—the values of these elements are submitted as part of the Ajax request. a. execute. b. render. c. send. d. display. Ans: a. execute. 30.4 Q2: The f:ajax element's ________ attribute specifies a space-separated list of element ids for the elements that should be updated via partial page updates. a. execute. b. render. c. send. d. display. Ans: b. render.
..
31 Web Services 31.1 Introduction 31.1 Q1: A ________ is a software component stored on one computer that can be accessed via method calls by an application (or other software component) on another computer over a network. a. web method. b. web service. c. web object. d. None of the above. Ans: b. web service. 31.1 Q2: ________ is an XML-based protocol that allows web services and clients to communicate, even if the client and the web service are written in different languages. a. SOAP. b. REST. c. TCP. d. UDP. Ans: a. SOAP.
31.2 Web Service Basics 31.2 Q1: The computer on which a web service resides is referred to as a ________. a. server. b. client. c. web service host. d. service repository. Ans: c. web service host. 31.2 Q2: Making a web service available to receive client requests is known as ________ a web service. a. accessing. b. serving. c. consuming. d. publishing. Ans: d. publishing. 31.2 Q3: Using a web service from a client application is known as ________ a web service. a. accessing. b. serving. c. consuming. d. publishing. ..
Ans: c. consuming.
31.3 Simple Object Access Protocol (SOAP) 31.3 Q1: The protocol that transmits request-and-response messages is known as the web service’s ________ or ________. a. format, protocol. b. wire format, wire protocol. c. web format, web protocol. d. None of the above. Ans: b. wire format, wire protocol. 31.3 Q2: Each request and response is packaged in a ________ (also known as a ________)—an XML “wrapper” containing the information that a web service requires to process the message. a. SOAP message, SOAP envelope. b. message, envelope. c. SOAP message, SOAP package. d. None of the above. Ans: a. SOAP message, SOAP envelope.
31.4 Representational State Transfer (REST) 31.4 Q1: REST returns data in the ________ format. a. XML. b. plain text. c. HTML. d. all of the above. Ans: d. all of the above. 31.4 Q2: Each method in a RESTful web service is identified by a unique ________. a. URL. b. data format. c. HTTP method (GET, POST, etc.). d. cache. Ans: a. URL.
31.5 JavaScript Object Notation (JSON) 31.5 Q1: JSON does not have a built-in way to represent ________. a. strings. b. arrays. c. dates. d. objects. Ans: c. dates. ..
31.6 Creating, Publishing, Testing and Describing a Web Service No questions.
31.6.1 Creating a Web Application Project and Adding a Web Service Class in Netbeans 31.6.1 Q1: To create a web service in NetBeans, you first create a project of type________. a. Web Service Application. b. Web Application. c. Service Application. d. Web Service. Ans: b. Web Application.
31.6.2 Defining the WelcomeSOAP Web Service in NetBeans 31.6.2 Q1: Each new web service class created with the JAX-WS APIs is a ________— you do not need to extend a class or implement an interface to create a Web service. a. Class. b. Object. c. POJO. d. None of the above. Ans: c. POJO. 31.6.2 Q2: The ________ annotation indicates that a class represents a web service. a. @WebService. b. @WebMethod. c. @WebParam. d. None of the above. Ans: a. @WebService. 31.6.2 Q3: The ________ annotation indicates the names of a method's parameters that will be exposed to a client calling one of the web service's methods. a. @WebService. b. @WebMethod. c. @WebParam. d. None of the above. Ans: c. @WebParam. 31.6.2 Q4: The ________ annotation indicates that a method can be called remotely. a. @WebService. ..
b. @WebMethod. c. @WebParam. d. None of the above. Ans: b. @WebMethod.
31.6.3 Publishing the WelcomeSOAP Web Service from NetBeans No questions.
31.6.4 Testing the WelcomeSOAP Web Service with GlassFish Application Server’s Tester Web Page No questions.
31.6.5 Describing a Web Service with the Web Service Description Language (WSDL) 31.6.5 Q1: JAX-WS uses ________ to describe web services in a platform-independent manner. a. XML. b. SOAP. c. WSDL. d. HTML. Ans: c. WSDL.
31.6.6 Creating a Client to Consume the WelcomeSOAP Web Service 31.6.6 Q1: A Java client application can consume a web service by adding a ________ to the application, which defines the proxy class that allows the client to access the web service. a. client reference b. web client reference. c. web service client. d. web service reference. Ans: d. web service reference.
31.6.7 Consuming the WelcomeSOAP Web Service No questions.
..
31.7 Publishing and Consuming REST-Based XML Web Services No questions.
31.7.1 Creating a REST-Based XML Web Service 31.7.1 Q1: The ________ annotation indicates the URI for accessing the web service. a. @Location. b. @URI. c. @Path. d. @URL. Ans: c. @Path. 31.7.1 Q2: To bind URL parameters to method parameters, use the ________ annotation. a. @PathParam. b. @marshal. c. @Produces. d. @BindParam. Ans: a. @PathParam. 31.7.1 Q3: To convert a POJO to XML, use the ________ method of the javax.xml.bind.JAXB class. a. serialize. b. convert. c. convertToXML. d. marshal. Ans: d. marshal.
31.7.2 Consuming a REST-Based XML Web Service 31.7.2 Q1: The unmarshal method of the JAXB class takes ________. a. a String indicating the URL or path of the XML document and a Class<T> indicating the class to convert to. b. an InputStream indicating the URL or path of the XML document and an object of the appropriate class to store the data. c. a Reader indicating the URL or path of the XML document; JAXB determines the type of the object from the XML data. d. a Scanner containing the XML document and a Class<T> indicating the class to convert to. Ans: a. a String indicating the URL or path of the XML document and a Class<T> indicating the class to convert to.
..
31.8 Publishing and Consuming REST-Based JSON Web Services No questions.
31.8.1 Creating a REST-Based JSON Web Service 31.8.1 Q1: The top level of a JSON text cannot be a(n) ________. a. number. b. object. c. string. d. both a and c. Ans: d. both a and c.
31.8.2 Consuming a REST-Based JSON Web Service 31.8.2 Q1: To retrieve data from a URL, create a URL object and then call its ________ method. a. getData. b. openStream. c. getReader. d. openReader. Ans: b. openStream.
31.9 Session Tracking in a SOAP-Based Web Service No questions.
31.9.1 Creating a Blackjack Web Service 31.9.1 Q1: The ________ annotation enables session tracking in a web service. a. @SessionScoped. b. @HttpSessionScope. c. @HttpSession. d. None of the above. Ans: b. @ HttpSessionScope.
31.9.2 Consuming the Blackjack Web Service 31.9.2 Q1: A ________ enables the client to manipulate the request information that will be sent to the server when invoking a web service method. a. WebServiceProvider. b. Provider. ..
c. Binder. d. BindingProvider. Ans: d. BindingProvider.
31.10 Consuming a Database-Driven SOAP-Based Web Service 31.10 Q1: Which of the following is true? a. Only desktop applications can consume web services. b. Only web applications can consume web services. c. Desktop and web applications can both consume web services. d. A web service client must be written in the same programming language Ans: c. Desktop and web applications can both consume web services.
31.10.1 Creating the Reservation Database No questions.
31.10.2 Creating a Web Application to Interact with the Reservation Service No questions.
31.11 Equation Generator: Returning User-Defined Types 31.11 Q1: For an object to be serialized and unserialized, what must be true about the class definitions on the server and client? a. They must have identical definitions, with the same class name and package. b. The class names and definitions must match, but the packages may differ. c. The class definitions must match, but the class name and package may differ. d. The classes must have the same set of public properties, but the classes may have additional methods that differ and class name and package do not matter. Ans: d. The classes must have the same set of public properties, but the classes may have additional methods that differ and class name and package do not matter.
31.11.1 Creating the REST-Based XML EquationGenerator Web Service No questions.
..
31.11.2 Consuming the REST-Based XML EquationGenerator Web Service No questions.
31.11.3 Creating the REST-Based JSON EquationGenerator Web Service No questions.
31.11.4 Consuming the REST-Based JSON EquationGenerator Web Service No questions.
..