Java Foundations Introduction to Program Design and Data Structures, 5th edition John Lewis Test Ban

Page 1

Java Foundations Introduction to Program Design and Data Structures, 5e By John Lewis

Email: richard@qwconsultancy.com


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 1

Chapter 1: Introduction Multiple Choice Questions: 1) _____________ consists of specific words and symbols to express a problem solution. a) A programming language b) Software c) Hardware d) A computer e) An application Answer: a Explanation: A programming language consists of words and symbols to express a problem solution. Software consists of programs and the data these programs use. Hardware is the tangible parts of a computer, such as keyboards and hard disks. A computer is made up of hardware and software, and an application is a program that runs on a computer. 2) Java is _____________________. a) a procedural language b) a functional language c) an object-oriented language d) a fourth-generation language e) a spoken-language Answer: c Explanation: Java is best described as an object-oriented language. Procedural languages, functional languages and fourth-generation languages are different types of languages that don't necessarily include object-oriented features. A spoken language is a language such as English or Spanish, and is too ambiguous for a computer to use. 3) Problem domain describes a) the set of problems that are encountered when testing a program b) the alternate ways to design the solution c) the challenges in implementing the solution d) the real-world issues that are key to a solution e) all of the above Answer: d Explanation: The problem domain is the set of real-world issues that are key to a solution.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 1 4) In order for a program to run on a computer, it must be expressed in ______________________. a) an assembly language b) a machine language c) a high-level language d) an object-oriented language e) a fourth generation language Answer: b Explanation: A computer can only understand its machine language. Assembly languages, high-level languages, objectoriented languages and fourth generation languages are are languages that are easy for humans to understand, but they must first be translated into a machine language before they are run on a computer. 5) A syntax error is a _____________________. a) a logical error b) a compile-time error c) a run-time error d) a bug e) an exception Answer: b Explanation: A program that contains a syntax error is invalid, and therefore cannot be compiled. It is a compile-time error because it is caught by the compiler. A logical error is an error that causes a running program to behave in an unexpected manner during run-time. A bug is an example of a logical error. A run-time error is an error that happens while the program is running. In Java, run-time errors are called exceptions. 6) Which of the following is not one of the four basic software development activities? a) establishing the requirements b) creating a design c) preliminary practice coding d) testing e) implementing the design Answer: c Explanation: Preliminary practice coding is not one of the four basic software development activities. Establishing the requirements for a program, creating a design for a program, implementing the design and testing the program all occur during software development. 7) Software requirements specify ____________________. a) what a program should accomplish b) which programming language the developer should use c) how objects should be encapsulated d) how a solution should be implemented e) a programming schedule Answer: a Explanation: Software requirements specify what a program should accomplish. They do not specify how a program or a programmer should get a program to work as it is supposed to, and therefore none of the other choices are correct.

2.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 1 8) The _____________ of an object define it define its potential behaviors. a) attributes b) white spaces c) variables d) methods e) name Answer: d Explanation: The methods of an object represent the objects potential behaviors. The attributes are the values that the object stores internally, and include the objects instance variables. The name of an object has nothing to do with its behaviors. White space is related to the program code and has nothing to do with objects. 9) Which of the following will is considered a logical error? a) forgetting a semicolon at the end of a programming statement b) typing a curly bracket when you should have typed a parenthesis c) multiplying two numbers when you meant to add them d) dividing by zero e) misspelling an identifier Answer: c Explanation: Multiplying two numbers when you mean to add them is an example of a logical error, because the program will still compile and run, but the output will be incorrect. Forgetting a semicolon, using a bracket instead of a parenthesis and misspelling an identifier will all lead to the program failing to compile, and are therefore compile-time errors. Dividing by zero is an example of a run-time error since it will cause the program to crash at run-time. 10) Which of the following lines is a properly formatted comment? a) // This is a comment b) /* This is a comment */ c) /* this is a comment */ d) both a and b e) a, b and c Answer: e Explanation: All three are examples of valid comments in Java. The first is an in-line comment, and the second two are examples of multi-line comments, although the second is only on one line. 11) The Java compiler translates Java source code into _____________ . a) Java bytecode b) C++ c) assembly code d) machine code e) an object-oriented language Answer: a Explanation: The Java compiler translates source into Java bytecode, which is an architecture-neutral language. The bytecode can then be run on a Java virtual machine. It does not translate Java into C++, assembly code, or machine code. Java is already an object-oriented language, so there is no need to translate it into one. 3.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 1 12) Classes can be created from other classes by using _______________ . a) encapsulation b) polymorphism c) inheritance d) attributes e) machine code Answer: c Explanation: Inheritance allows a programmer to create new classes from existing classes. Polymorphism is related to dynamic method binding in the inheritance hierarchy. Encapsulation is the conceptual idea that states that an object should be self-governing. Attributes are the values that are stored within an object. Machine code is a language that a computer can understand directly without translation. 13) Which of the following is not a valid Java identifier? a) answer_7 b) highest$ c) anExtremelyLongIdentifierIfYouAskMe d) 2ndlevel e) thirdNumber Answer: d Explanation: An identifier in Java can consist of any number of letters, numbers, the dollar sign character or underscores. It cannot, however, start with a digit. Therefore, 2ndlevel is not a valid identifier. 14) Which task(s) is/are done in the implementation activity in the software development process? a) specify what the program must accomplish b) determine how a program will accomplish its requirements c) write the source code that will solve the problem d) ensure that the program solves the targeted problem e) all of the above Answer: c Explanation: Implementation is the process of writing the source code that will solve a problem. Answer a) refers to the software requirements. Answer b) refers to the software design. Answer d) refers to testing activities. 15) Which of the following describes the act of ensuring that a program solves the intended problem in all cases? a) establishing the requirements b) testing c) preliminary practice coding d) implementing the design e) creating a design Answer: b Explanation: Testing a program is the act of ensuring that a program solves the intended problem in all cases. Establishing the requirements is done at the beginning of the software life cycle, and refers to specifying what a program should accomplish. Creating the design refers to designing the software and implementing the design refers to the actual coding portion of software development.

4.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 1

True/False Questions: 1) An editor is typically included as part of an IDE. Answer: True Explanation: An IDE is an integrated development environment. It typically includes all of the tools needed to write programs in a particular language. This includes a compiler, an editor, and a debugger among other things. 2) Comments affect the run-time execution of a program. Answer: False Explanation: Comments are useful for people who are reading the code and do not affect the run-time execution of a program. 3) A reserved word can be used to name a method. Answer: False Explanation: A reserved word cannot be used as an identifier in Java. 4) "Purchase a computer" is one of the problem-solving steps. Answer: False Explanation: The problem-solving steps include understanding the problem, designing a solution, considering alternate solutions and refining the solution, implementing the solution, and testing. 5) In Java, total, ToTal and TOTAL are all different identifiers. Answer: True Explanation: Java is case-sensitive, so these three identifiers are distinct and different. 6) Testing is the act of ensuring that a program will solve the targeted problem. Answer: True Explanation: Testing is the act of ensuring that a program will solve the targeted problem, given all of the constraints under which it must perform. 7) The attribute of an object defines its potential behaviors Answer: False Explanation: The attributes of an object are values that are stored internally in the object. The methods of an object define its potential behaviors. 8) An interpreter is a program that translates code that is written in one language into equivalent code in another language. Answer: False Explanation: A compiler is a program that translates code that is written in one language into equivalent code in another language. An interpreter is a program that interprets code in another language line-by-line. 9) Syntax rules dictate the form of a program. Semantics dictate the meaning of the program statements. Answer: True Explanation: These are correct definitions for syntax and semantics in the context of a programming language. 10) An object should never be encapsulated. Answer: False Explanation: In the object-oriented programming paradigm, it is important that an object be encapsulated, meaning that it manages all of its own information.

5 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 1

Short Answer Questions: 1) Explain why "Understand the problem" is the first activity in problem solving. Answer: Understanding the problem is critical to designing the solution. Without a good understanding of the problem, you may design a solution to the wrong problem.

2) Write a short Java program that outputs the following: * * * ************** * * * Answer:

Time flies like an arrow

public class Arrow { public static void main(String [] args) { System.out.println(" *"); System.out.println(" *"); System.out.println(" *"); System.out.println(" ************** Time flies like an arrow"); System.out.println(" *"); System.out.println(" *"); System.out.println(" *"); } }

3) Why is testing part of the problem-solving process? Answer: Testing allows us to find errors in our solution. The errors may be in the design, in the refinement of the design, or in the implementation. Testing helps to ensure that a solution is viable.

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 1 4) Identify the syntax errors in the following snippet of code: public clas Hello { public static void main(String [] args)

{

Sytem.out.println("Hello Wrld!") } } Answer: There are three syntax errors in this snippet of code: "class" is spelled incorrectly; "System" is spelled incorrectly; there is no semicolon after the print statement. Although "world" is spelled incorrectly, it is not a syntax error since it is part of a string literal. 5) Explain the difference between the syntax of a program and the semantics of a program. Answer: Syntax rules dictate the form of a program. Semantics dictate the meaning of the program statements. In other words, syntax specifies the actual code of the program, while semantics refers to the meaning that is attached to the code. 6) Why is ambiguity a problem for programming languages? Answer: Ambiguity is a problem for programming languages because it is extraordinarily difficult for a computer to tell what is meant by a phrase or a sentence from its context. Therefore translating an ambiguous language into machine code is very difficult. 7) Why is it important to consider alternate solutions to a problem? Answer: The initial design of a solution may not be the best way to solve a problem. By considering alternate solutions, the design can be improved if necessary. 8) Why is inheritance a form of software reuse? Answer: Inheritance supports creating classes based on the definition of an existing class. The new class re-uses the existing class’s attributes and methods. 9) Determine a good identifier for each of the following entities in a program that calculates the final grade: a) A grade on the first test of the semester b) The total number of tests c) The total number of homework assignments d) The relative weight of the tests Answer: a) firstTest b) totalNumTests c) totalNumAssn d) testWeight Note that there are other descriptive identifiers that can be used for each of these.

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 1 10) Explain the difference between a compile-time error and a run-time error. Give an example of each. Answer: A compile-time error will cause the compiler to exit with an error, and therefore the program will not be properly translated. A program with a run-time error will compile and be translated, but will crash or throw an exception while it is running. An example of a compile-time error is forgetting a semicolon. An example of a run-time error is dividing by zero. 11) What are the primary concepts that support object-oriented programming? Answer: The primary concepts that support object-oriented programming are objects, attributes, methods, classes, encapsulation, inheritance and polymorphism. 12) What are some advantages to writing programs in a high-level language instead of machine code? Answer: Programs written in a high-level language are more easily readable by humans and, therefore, they can be debugged and maintained easier than programs written in machine code. In addition, high-level languages support more natural problem-solving approaches such as object-oriented programming, whereas machine languages typically do not. 13) Name the four basic activities that are involved in a software development process. Answer: The four basic activities that are involved in a software development process are establishing the requirements, creating the design, implementing the design and testing. 14) Write a program that outputs Four Score and Seven Years Ago on six lines, with the words centered relative to each other. Answer: public class Lincoln { public static void main(String [] args) System.out.println(" Four "); System.out.println("Score"); System.out.println(" and "); System.out.println("Seven"); System.out.println("Years"); System.out.println(" Ago "); } }

{

15) Give three examples of Java reserved words. Answer: Three commonly used reserved words in Java are public, static, and void. See figure 1.1 in your textbook for a list of all reserved words in Java.

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Chapter 2: Data and Expressions Multiple Choice Questions: 1) Which of the following are examples of invalid string literals? a) "Hello World!" b) "4 score and 7 years ago, our forefathers brought forth..." c) "z" d) "" e) none of the above Answer: e Explanation: A string literal can contain any valid characters, including numeric digits, punctuation and other special characters. They can also contain no characters at all. 2) A(n) ________________ is a piece of data that we send to a method. a) parameter b) object c) escape sequence d) service e) expression Answer: a Explanation: A parameter is a piece of data sent to a method. An object may not be sent to a method directly (although you can send a reference to an object as a parameter). An escape sequence is used to represent special characters in a string literal. A service is the action that a method provides to a program. An expression is a combination of operators and operands that produces a result. 3) Which of the following is an example of an invalid assignment or declaration statement? a) int age = 30; b) int money, dollars = 0, cents = 0; c) int years = 1; months = 12; days = 365; d) int length, meters, centimeters, millimeters; e) none of the above Answer: c Explanation: A declaration/assignment statement cannot have multiple declaration/assignments separated by semicolons since a semi-colon denotes the end of a statement in Java.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2 4) Java has two basic kinds of numeric values: _____________, which have no fractional part, and ___________________ which do. a) shorts, longs b) doubles, floating points c) characters, bytes d) integers, floating points e) integers, longs Answer: d Explanation: All numeric data types are either floating point data types, which have fractional parts (e.g. float, long) or integer data types which have no fractional parts (e.g. byte, short, int, long). 5) To assign a value stored in a double variable to an int variable, use a) a cast operator b) promotion c) a print statement d) a widening conversion e) nothing. Java will do this automatically Answer: a Explanation: This is a narrowing conversion. A cast operator must be used to perform a narrowing conversion. 6) Which of the following is not an arithmetic operation in Java? a) + b) c) * d) % e) These are all arithmetic operations in Java Answer: e Explanation: All of these operators can be used as part of an arithmetic expression in Java. They represent the addition, subtraction, multiplication and remainder operators respectively. 7) Which modifier must be used in the declaration of a variable to make it a constant? a) public b) final c) static d) void e) private Answer: b Explanation: The final modifier makes a variable a constant, meaning that its value cannot be reassigned.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2 8) Which of the following data types only allows one of two possible values to be assigned? a) char b) int c) boolean d) float e) long Answer: c Explanation: Variables of type boolean can only be assigned values of true or false. The other four types can be assigned many different values. 9) Which of the following is an example of an invalid expression in Java? a) b) c) d) e)

result = a + b; result = (14 + 9) * 5; result = ((19 + 4) - 5; result = firstNum % secondNum; result = firstNum / secondNum % thirdNum;

Answer: c Explanation: All of these expressions are valid except for c, which has mismatched parenthesis. This will generate a compiler error. 10) A _______________ is a list of characters in a particular order. Examples include ASCII and Unicode. a) character literal b) character set c) char data type d) control character e) none of the above Answer: b Explanation: A character set is a list of characters in a particular order. Java uses the Unicode character set. A character literal is an explicit character in a Java program and is denoted by surrounding it with single quotes. The char data type is a primitive data type in Java and a control character is a nonprinting or invisible character that does not have a symbol to represent it. 11) A user types the number -12.6 in response to a prompt in a program. Which Scanner class method should be used to read the user input as a numeric value? a) b) c) d) e)

nextInt() nextDouble() nextNegative() next() any of these methods will work

Answer: b Explanation: The user input contains a decimal point, so it cannot be read as an int. The next() method will read it in as a String, not as a numeric value. 3.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

12) Which of the following lines allows a programmer to use the Scanner class in a Java program? a) b) c) d) e)

import java.util.Scanner; using Scanner; include Scanner; include java.util.Scanner; any of the above will allow the programmer to use the Scanner class

Answer: a Explanation: The Scanner class must be imported using the import command before it may be used in a program. 13) Consider the following snippet of code: System.out.println("30 plus 25 is " + 30 + 25); What is printed by this line? a) b) c) d) e)

30 plus 25 is 55 30 plus 25 is 30 30 plus 25 is 25 30 plus 25 is 3025 this snippet of code will result in a compiler error

Answer: d Explanation: In this case, the + symbol represents the concatenation operator, not addition. Therefore, the println method will output the concatenation of 30 plus 25 is, 30, and 25. If we wanted to print out the sum of 30 and 25, we must put the sum in parentheses. 14) Consider the following snippet of code: int firstNum = 25; int seconNum = 3; double result = 25/3; System.out.println(result); What is output by this code? a) b) c) d) e)

8.0 8.333333333 8 8.3 This snippet of code will result in a compiler error

Answer: a Explanation: The right hand side of the assignment statement in the third line results in an integer because the two operands are integers. Specifically, it yields 8. The left hand side of the expression is of type double,so assignment conversion occurs. Therefore, result holds 8.0. This is what will be printed by the println statement.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2 15) Information is most likely to be lost in what kind of data conversion? a) A widening conversion b) A narrowing conversion c) promotion d) assignment conversion e) no information will be lost in any of the conversions listed above Answer: b Explanation: A narrowing conversion is most likely to result in information loss since you are changing a piece of data from a data type that can hold more information into a data type that can hold less information. The other three types of conversions are all widening conversions, and therefore do not lose any information.

5 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

True/False Questions: 1) The print and the println methods are identical and can be used interchangeably. Answer: False Explanation: The println method prints the information sent to it, then moves to the beginning of the next line. The print method does not advance to the next line when completed. 2) A String literal may span multiple lines in the program code. Answer: False Explanation: A string literal may not span multiple lines. If a programmer wishes to have part of a string literal on one line and part on another line, she must separate the single literal into two literals, and use the concatenation operator (+). 3) Java is a strongly-typed language. Answer: True Explanation: Java is strongly-typed, which means we cannot assign values to a variable that are inconsistent with its declared type without generating a compile time error. 4) Variables declared with the final modifier cannot have new values assigned to them. Answer: True Explanation: The final modifier makes a variable a constant. 5) The byte type can be assigned a larger range of numbers than the int type. Answer: False Explanation: The int type can hold numbers in the range -2,147,483 to 2,147,483,647 while the byte type can only hold numbers in the range -128 to 127. 6) Java uses the ASCII character set to represent character data. Answer: False Explanation: Java uses the Unicode character set to represent characters, since it supports more unique characters and can therefore represent the world's many alphabets better. 7) After the execution of the code below: int counter = 9; int result = counter++; variable result contains the value 9. Answer: True Explanation: The expression counter++ uses the postfix form of the increment operator. Its value, 9, is assigned to result, then the value in counter is incremented to 10. 8) The type of result produced by a mathematical expression depends on the types of the operands. Answer: True Explanation: The types of the operands dictate the data type to which an expression evaluates. An important example of this is arithmetic division, which will always result in an integer when the expression's operands are integers. 9) Promotion is a widening data conversion that is explicitly requested by the programmer. Answer: False Explanation: Promotion is an explicit conversion that happens when operators need to modify their operands to perform the operation. For example, when an integer is divided by a floating point number, the integer will be promoted to a floating point number so that the division operator is acting on two floating point types. 6.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

10) The Scanner class must be imported using the import statement before it can be used in a program. Answer: True Explanation: The Scanner class is part of the java.util package which is not imported automatically.

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Short Answer Questions: 1) Write an application that prints out the following using a single call to the print method. Hello! How are you? Answer: public class QuestionOne { public static void main(String [] args) { System.out.print("Hello!\nHow\nare you?"); } } 2) Write a single println statement that prints out the following line. "There is Thingumbob shouting!" the Bellman said, Answer: System.out.println("\"There is Thingumbob shouting!\" the Bellman said,"); 3) Write a short program that declares a single integer variable called age and assigns it a value equal to your age. Also have it print out your age using the age variable. The output of your program should look similar to the following: I am 30 years old. Answer: public class MyAge { public static void main(String [] args) { int age = 30; System.out.println("I am " + age + " years old."); } } 4) Write a single line of Java code that computes the average of three integer variables – num1, num2, and num3 – and stores the result in a variable of type double called result. Answer: Note that in order to compute an accurate average, we must avoid integer division. This can be achieved by making one of our operands a floating point value. In this solution, we divide by 3.0 to yield floating point division on the right hand side of the expression. double result = (num1 + num2 + num3)/3.0;

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2 5) Suppose your numeric grade is calculated using the following formula: Test 1: 15% Test 2: 15% Final Exam: 30% Homework: 10% Programming Projects: 30% Determine a good variable name to represent each of these values. Write a single expression to compute your grade assuming the variables have been declared and each one stores its value as an integer in the range 0 to 100. Answer: double grade = test1*.15 + test2*.15 + exam*.3 + homework*.1 + projects*.3; 6) Write a short application that converts inches to centimeters. It should read the number of inches from the user as a floating point number and output the number of inches and the number of centimeters at the end of the program. Note that there are 2.54 centimeters in an inch. Answer: import java.util.Scanner; public class InchesToCentimetersConversion { public static void main(String [] args) { double inches; double centimeters; Scanner input = new Scanner(System.in); System.out.print("Please enter the number of inches: "); inches = input.nextDouble(); centimeters = inches*2.54; System.out.println(inches + " inches is equivalent to " + centimeters + " centimeters."); }//end main }//end class

9 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2 7) Consider the following snippet of code. int iResult; float fResult; int rResult; int iNum1 = 25; int iNum2 = 8; iResult = iNum1/iNum2; rResult = iNum1%iNum2; fResult = (float) iNum1/iNum2; What values are stored in iResult, rResult, and fResult? Explain your answers. Answer: The value that is stored in iResult is 3. This is the result of dividing 25 and 8 using integer division. The value that is stored in rResult is 1. This is the remainder of dividing 25 and 8 using integer division. The value that is stored in fResult is 3.125. This is the result of dividing 25 and 8 using floating point division. In the expression, iNum1 is explicitly cast as a floating point value which causes iNum2 to be promoted to a floating point value. The division is then floating point division. 8) Write a short program that allows the user to enter the year that they were born (as an integer) and outputs the age that they will be at the end of this year. Declare the current year as a constant. Answer: import java.util.Scanner; public class AgeThisYear { public static void main(String [] args) { final int CURRENT_YEAR = 2017; // adjust as appropriate int age, birthYear; Scanner scan = new Scanner(); System.out.print("Enter the year of your birth: "); birthYear = scan.nextInt(); age = CURRENT_YEAR – birthYear; System.out.println("You will be " + age + " at the end of" + " this year."); }//end main }//end class

10 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2 9) What are some reasons that you might want to declare a variable as final? Answer: A variable that is declared as final is one that cannot be reassigned throughout the program. You might want to declare a variable as final if its value will not change during program execution. This will make it so you cannot accidentally change the value by reassigning it which can cause errors. It also will allow you to change the variable in a single place in the program if and when the value does change. 10) Write a short application that computes the perimeter of a rectangle. It should allow the user to input the length and width of the rectangle as a double. Answer: import java.util.Scanner; public class Perimeter { public static void main(String [] args) double length, width, perimeter;

{

Scanner scan = new Scanner(); System.out.print("Enter the length of the rectangle: "); length = scan.nextDouble(); System.out.print("Enter the width of the rectangle: "); width = scan.nextDouble(); perimeter = length*2 + width*2; System.out.println("The perimeter of the rectangle is " + perimeter + " inches."); }//end main }//end class 11) Consider the following snippet of code: int firstNum = 5; int secondNum = firstNum++; int thirdNum = 6*(++firstNum); What values are stored in firstNum, secondNum and thirdNum after these lines are executed? Explain your answer. Answer: After the first two lines are executed, secondNum will contain 5 and firstNum will contain 6. This is because the increment operator is after the variable, which means that the assignment will happen before firstNum is incremented. After the third line is executed, firstNum is 7 and thirdNum is 42 (which is 6*7). This is because the increment operator is before firstNum, which means that firstNum is incremented to 7, and then the expression is evaluated.

11 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2 12) For the following expression, indicate the order that in which the operators will be evaluated. a + b * c / (d - e) Answer: The subtraction (d – e) will be evaluated first since it is in parentheses. Next, the multiplication b*c will be evaluated and then the division operation will be evaluated. Finally, the addition will be performed. 13) Explain why it might not be safe for a programmer to use a narrowing conversion. Answer: A narrowing conversion might not be safe because it can result in information loss. This is because in a narrowing conversion a programmer is changing a piece of data from a data type that can hold more information into a data type that can hold less information. 14) How are primitive data types and object data types related? Answer: Object types are more complex data types, and they are generally made up of primitive data types. 15) Explain the difference between the print and the println methods. Answer: The println method performs a carriage return after printing the specified characters. This means the next output will begin on the next line. The print method does not do this, and therefore the next output will begin right after the previous output.

12 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 3

Chapter 3: Using Classes and Objects Multiple Choice Questions: 1) A special method that is invoked to set up an object during instantiation is called a ___________________. a) new method b) dot operator c) creator d) constructor e) destructor Answer: d Explanation: The constructor is called to set up an object during instantiation. The dot operator is used to access methods of an object. There is no "new" method – new is an operator. Java also does not have "creators" or "destructors." 2) Which of the following is an invalid way to instantiate a String object? a) b) c) d) e)

String title = new String("Java Software Solutions"); String name = "John Lewis"; String empty = ""; String alsoEmpty = new String(""); all of the above are valid

Answer: e Explanation: Choices a and d represent the standard approach to instantiating a String object. Choice d creates the emptry string. Choices b and c use a shortcut notation that is only available for creating a String object. 3) Assume that we have a Random object referenced by a variable called generator. Which of the following lines will generate a random number in the range 5-20 and store it in the int variable randNum? a) b) c) d) e)

randNum = generator.nextInt(15) + 5; randNum = generator.nextInt(15) + 6; randNum = generator.nextInt(16) + 5; randNum = generator.nextInt(16) + 6; none of the above

Answer: c Explanation: When called with 16 as a parameter, the nextInt() method will return a number in the range 0 to 15. Adding 5 to this random number will generate a number in the range 5 to 20.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 3 4) Which of the following classes include the getCurrencyInstance() method? a) b) c) d) e)

String NumberFormat DecimalFormat Math none of the above

Answer: b Explanation: The NumberFormat class includes the getCurrencyInstance() method. 5) Which of the following expressions correctly computes the value of the mathematical expression 5 + 26? a) b) c) d) e)

result = 5 + 2^6; result = 5 + 2*exponent(6); result = 5 + 2*Math.exponent(6); result = 5 + Math.pow(2, 6); none of the above

Answer: d Explanation: Choice a is wrong because Java does not have an exponential operator for primitive types. Choices b and C are wrong because there are no methods named exponent in the java.lang package or the Math class. Choice c correctly uses the Math.pow() method to compute the expression. 6) Consider the following snippet of code: Random generator = new Random(); int randNum = generator.nextInt(20) + 1; Which of the following will be true after these lines are executed? a) b) c) d) e)

randNum will hold a number between 1 and 20 inclusive. randNum will hold a number between 0 and 20 inclusive. randNum will hold a number between 1 and 21 inclusive. these lines will not be executed because a compiler error will result. none of the above

Answer: a Explanation: When called with a parameter of 20, the nextInt() method will return an integer between 0 and 19 inclusive. Adding one to this will result in a number between 1 and 20 inclusive.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 3 7) Which of the following represents the proper way to create a NumberFormat object that formats numbers as percentages? a) b) c) d) e)

NumberFormat fmt = new NumberFormat(%); NumberFormat fmt = new NumberFormat("%"); NumberFormat fmt = NumberFormat.getPercentInstance(); NumberFormat fmt = new PercentNumberFormat(); none of the above

Answer: c Explanation: The NumberFormat class uses factory methods to construct objects. The new operator is called implicitly in this case. The factory method that is used is called getPercentInstance(). Therefore choice c is correct. Choice a and Choice b are incorrect since they call the new operator explicitly. Choice d is incorrect because there is no PercentNumberFormat class that can be called with the new constructor. 8) Which of the following is a correct declaration of enumerated type for the suits of a deck of cards? a) b) c) d) e)

enumerated type Suit = { hearts, spades, diamonds, clubs }; enum Suit {hearts, spades, diamonds, clubs }; enum Suit {hearts, spades, diamonds, clubs } enumerated type Suit = {hearts, spades, diamonds, clubs }; enum Suit = { hearts, spades, diamonds, clubs }

Answer: c Explanation: Choice c represents the correct syntax for declaring an enumerated type called Suit that can take one of the values hearts, spades, diamonds or clubs. 9) Fruit is an enumerated type with values apple, banana, grape, and orange, in that order. Which of the following statements assigns the value orange to the Fruit variable snack? a) b) c) d) e)

snack = orange; Fruit.snack = orange; snack = Fruit.orange; snack =Fruit.last(); snack = Fruit(4);

Answer: c Explanation: Values are assigned to enumerated type variables by using the typename, the dot operator, and the type value. 10) newNum is an Integer object that holds an int value. Which expression below returns the value in newNum as a double value? a) b) c) d) e)

newNum.doubleValue() newNum.double(); newNum.toDouble(); Double.newNum(); There is no way to return the value as a double.

Answer: a Explanation: The doubleValue() method of the Integer class returns the value of an object as a double. 3.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 3

11) ____________________ is the automatic conversion between a primitive value and a corresponding wrapper object. a) Generating b) Aliasing c) Number formatting d) Static invocation e) Autoboxing Answer: e Explanation: Autoboxing allows a programmer to automatically convert between a primitive value and a corresponding wrapper object. The other 4 answers are incorrect. 12) Which of the following best describes what happens when an object no longer has any references pointing to it? a) The object is overwritten the next time the new operator is called. b) The object is overwritten the next time the new operator is called using the same class. c) The object is immediately deleted from memory. d) The object is marked as garbage and its associated memory is freed when the garbage collector runs. e) The object stays in memory for the remainder of the programs execution. Answer: d Explanation: Java has automatic garbage collection. When an object no longer has any references pointing to it, it is marked as garbage. When the garbage collector runs, the memory is freed so that new objects can be created in its space. 13) Suppose we have a String object referenced by a variable called listing. Suppose we want a new String object that consists of the first 5 characters in listing. Which of the following lines of code will achieve this? a) b) c) d) e)

String prefix = listing.front(5); String prefix = listing.front(6); String prefix = listing.substring(1,5); String prefix = listing.substring(0,5); String prefix = listing.firstChars(5);

Answer: d Explanation: Choices a, b, and e are wrong because the String class does not have methods called front or firstChars. Choice c is incorrect because the first character in the string is indexed by 1. Choice c is correct, since it will create a new string from the first 5 characters of listing. 14) When two references point to the same object, ________________________________ . a) a run-time error will occur. b) a compiler error will occur. c) the references are called aliases of each other. d) the object will be marked for garbage collection. e) the references are called null references. Answer: c Explanation: It is perfectly acceptable to have two references pointing to the same object, so no errors will be generated. Therefore choices a and b are incorrect. Choice d is incorrect since objects are marked for garbage collection only when no references point to them. Choice e is incorrect since references are called null when they do not point to anything.

4.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 3

15) The String class _______________________________ . a) is part of the java.lang package. b) is part of the java.util package. c) is a wrapper class. d) none of the above. e) all of the above. Answer: a Explanation: The String class is part of the java.lang package. Therefore, choice a is the correct answer. It is not a wrapper class, and it is not part of the java.util package, therefore the other choices are wrong.

5 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 3

True/False Questions: 1) Multiple reference variables can refer to the same object. Answer: True Explanation: When multiple reference variables refer to the same object, they are called aliases of each other. 2) The new operator is used to access an object's methods. Answer: False Explanation: The new operator is used to instantiate objects. The dot operator is used to access an objects methods. 3) A variable that is declared as a primitive type stores the actual value of the associated data. A variable that is declared as an object type stores a pointer to the associated object. Answer: True Explanation: Primitive data types are stored by value, object types are stored by reference. 4) The value of a primitive datatype variable may be assigned to an object of the corresponding wrapper class, and vice-versa. Answer: True Explanation: Autoboxing and unboxing allow the conversion between primitive datatypes and wrapper objects of the corresponding classes. Such assignments are generally not possible without classes that support autoboxing and unboxing. 5) String objects can be changed after instantiation. Answer: False Explanation: String objects are immutable, meaning that once a String object is created, its value cannot be lengthened or shortened, nor can any of its characters change. 6) All of the classes contained in the java.util package are automatically included in every Java program. Answer: False Explanation: In order to use classes in the java.util package, the programmer must include them using an import statement. The classes in the java.lang package are automatically included in every Java program, and therefore do not require an import statement to use. 7) When called with integer parameter n, the nextInt() method of the Random class will return a randomly generated integer between 0 and n. Answer: False Explanation: When called with integer parameter n, the nextInt() method of the Random class will return a randomly generated integer between 0 and n-1. 8) The Math class is part of the java.lang package. Answer: True Explanation: The Math class is part of the java.lang package. Therefore, a programmer does not need to include an explicit import statement to use its methods. 9) Enumerated types allow a programmer to treat primitive data as objects. Answer: False Explanation: Enumerated types are programmer-defined types that allow variables to be assigned values from a specified set. Wrapper classes allow a programmer to treat primitive data as objects. 10) The System.out.printf() method is an alternative way to output information in Java. Answer: True Explanation: The System.out.printf() method provides an alternative way of outputting data, but was mainly incorporated into Java to make it easier to port legacy programs written in C to the Java language. 6.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 3

Short Answer Questions: 1) Explain how variables representing objects and variables representing primitive types are different. Answer: A variable representing a primitive type actually holds the primitive value associated with the variable, while a variable representing an object holds a reference to the object associated with the variable. 2) Suppose we have a String object called myString. Write a single line of Java code that will output myString in such a way that all of its characters are uppercase. Answer: System.out.println(myString.toUpperCase()); 3) Explain what it means for a String object to be immutable. Are there any workarounds for this? Answer: String objects are immutable, meaning that once a String object is created, its value cannot be lengthened or shortened, nor can any of its characters change. However, there are several methods in the String class that return new modified String objects. By reassigning the original reference to the result of calling one of these methods, we can effectively change the value of a String object. 4) Write a short program that allows the user to input a positive integer and then outputs a randomly generated integer between 1 and the input number. Answer: import java.util.Scanner; import java.util.Random; public class RandomInteger { public static void main(String [] args) int inputNum, randNum;

{

Scanner input = new Scanner(System.in); Random generator = new Random(); System.out.print("Please enter a positive integer: "); inputNum = input.nextInt(); randNum = generator.nextInt(inputNum) + 1; System.out.println("Your random number is " + randNum + "."); }//end main }//end class

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 3 5) Write a statement that computes the square root of a variable called discriminant and stores the value in a variable called result. Answer: result = Math.sqrt(discriminant); 6) After an object is instantiated and associated with a reference variable, how are the object's methods accessed? Give an example. Answer: The name of the reference variable and the dot operator are used to access the object's methods. Example: Integer num = new Integer(12); // Invoke the println() method of the System.out object // and the toHexString() method of the num object System.out.println(num.toHexString()); 7) generator is an object of the Random class. Write a single statement that generates a random number in the range 73 to 100 and assigns it to int variable randNum. Answer: randNum = generator.nextInt(28) + 73; 8) What is the range of integers that will be generated by the following expression? generator.nextInt(15) + 5 Answer: This expression will generate a random number in the range 5 to 19 (inclusive). 9) Write an expression that will compute the tangent of an angle stored in a variable named angle, and put the resulting value in a variable named tangent. Answer: tangent = Math.tan(angle); 10) Write a declaration for an enumerated type that represents the months of the year. Answer: enum Month { January, February, March, April, May, June, July, August, September, October, November, December } 11) Write a single statement that creates a DecimalFormat object that formats numbers to 2 decimal places. Answer: DecimalFormat fmt = new DecimalFormat("0.##");

8.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 3 12) Write a short program that allows the user to enter the base and height of a triangle and outputs the hypotenuse, formatted to three decimal places. Answer: import java.util.Scanner; import java.text.DecimalFormat; public class Hypotenuse { public static void main(String [] args) double base, height, hypotenuse;

{

Scanner input = new Scanner(System.in); DecimalFormat fmt = new DecimalFormat("0.###"); System.out.print("Please enter the base: "); base = input.nextDouble(); System.out.print("Please enter the height: "); height = input.nextDouble(); hypotenuse = Math.sqrt(Math.pow(base,2) + Math.pow(height,2)); System.out.println("The hypotenuse is " + fmt.format(hypotenuse) + "."); }//end main }//end class 13) A program will use a Scanner object from java.util.Scanner and a Random object from java.util.Random. Write a single import statement that will support the program. Answer: import java.util.*; 14) Write a single line that creates a wrapper object named numWrapper for an int variable named num. Answer: Integer numWrapper = new Integer(num); 15) Write an expression that computes 12 raised to the power 4.3 and store the result in a double called result. Answer: result = Math.pow(12, 4.3);

9 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 4

Chapter 4: Conditionals and Loops Multiple Choice Questions: 1) Which of the following statements best describes the flow of control in the main method of a Java program that has no conditionals or loops? a) Program statements are all executed at the same time. b) Program statements are executed according to their priority, which is specified by the programmer. c) Program statements are executed linearly, with earlier statements being executed first. d) Program statements are executed linearly, with later statements being executed first. e) Some program statements are executed at the same time, and others are executed in a linear manner. Answer: c Explanation: Program statements in a Java program are executed linearly when there are no conditionals or loops. This means that statements that appear earlier in the code are executed before statements that appear later in the code. 2) Which of the following best describes this code snippet? if (count != 400) System.out.println("Hello World!"); a) If the variable count is exactly equal to 400, "Hello World" will be printed. b) If the variable count is not equal to 400, "Hello World" will be printed. c) If the variable count is close to, but not greater than, 400, "Hello World" will be printed. d) If the variable count is exactly equal to 399 or 401, "Hello World" will be printed. e) This code will not compile. Answer: b Explanation: The != operator means is not equal to. Therefore if the variable count is not equal to 400, the following line will be executed. The boolean operator to test is equal to is ==. There are no boolean operators that directly test the cases specified in choices c and d. 3) In Java, a block statement is a) b) c) d) e)

a set of statements that are all indented to the same column. a set of statements enclosed in { and }. statements that form a rectangular set of characters on the screen. a statement that prevents other statements from executing. a statement that ends the execution of the program.

Answer: b Explanation: Java uses block statements to execute a set of statements as if it was a single statement. Block statements are commonly used in the body of loop statements and in the execution of if and if-else statements. Java does not pay attention to whitespace, indentation, or other formatting, so choices a) and c) are false.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 4 4) Let a and b be valid boolean expressions. Which of the following best describes the result of the expression a || b? a) It will evaluate to true if a evaluates to true and b evaluates to true. It will evaluate to false otherwise. b) It will evaluate to false if a evaluates to false and b evaluates to false. It will evaluate to true otherwise. c) It will evaluate to true if a evaluates to false and b evaluates to false. It will evaluate to true otherwise. d) It will evaluate to true if a evaluates to false or b evaluates to false. It will evaluate to true otherwise. e) None of the above statements correctly describes the evaluation of the expression. Answer: b Explanation: The || operator represents the logical or. Therefore the expression will evaluate to true whenever a is true or b is true, or if they are both true. Thus, it will evaluate to false only when both a is false and b is false, and it will evaluate to true otherwise. 5) Which of the following expressions best represents the condition "if the grade is between 75 and 100"? a) b) c) d) e)

if (75 < grade && grade < 100) if (grade != 75 && grade != 100) if (75 < grade < 100) if (75 > grade || grade < 100) if (75 < grade || grade < 100)

Answer: a Explanation: Choice a best represents the condition specified. Choice b best represents "if the grade is not 75 and the grade is not 100." Choice c is not valid Java code. Choice d represents "if the grade is less than 75 or the grade is greater than 100." Choice e represents "if the grade is greater than 75 or the grade is less than 100," and it will always evaluate to true. 6) A set of statements must be executed an unknown number of times, and possibly not executed at all. Which loop statement should not be used to control the execution of this set of statements? a) b) c) d) e)

while for do repeat Any of these loop statements can be used.

Answer: c Explanation: Because the condition that controls the execution of a do loop comes after the body, the body of a do loop always executes at least once. It is not a choice to use if the statements may not need to be executed at all. There is no repeat loop in Java.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 4 7) Suppose we wanted to process a text file called "input.txt" using the Scanner object. Which of the following lines of code correctly creates the necessary Scanner object? a) b) c) d) e)

Scanner inputFile = new Scanner("input.txt"); Scanner inputFile = new Scanner(new InputFile("input.txt"); Scanner inputFile = new Scanner(new File(input.txt); Scanner inputFile = new Scanner(new InputFile(input.txt); Scanner inputFile = new Scanner(new File("input.txt");

Answer: e Explanation: The Scanner constructor needs to take a reference to a File object as a parameter, so choice a, b and d are incorrect. The constructor for a File object takes in a String, so choice c is incorrect. Therefore, choice e is correct. 8) The code below is supposed to add the numbers from 1 up to and including 10. It does not calculate the correct sum. The problem is caused by a(n) ________ error. int sum = 0; for (int count = 1; count < 10; count++) sum += count; a) b) c) d) e)

syntax compilation requirement off-by-one testing

Answer: d Explanation: An off-by-one error occurs when a loop body is executed either one too many times or one too few times. The problem is solved if the boolean condition is replaced by count <= 10. 9) What happens if a case in a switch statement does not end with a break statement? a) The program will not compile. b) The switch statement will never execute. c) It will cause an infinite loop. d) The switch statement will execute the next case statement as well. e) The case will never be executed. Answer: d Explanation: If the case statement does not end in a break statement, the next case will also be executed. Therefore choice d is correct.

3 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 4 10) A switch statement does not have a case that matches the value of the expression, and it does not have a default case. What happens? a) The first case will be executed because there is no default case. b) The last case will be executed because there is no default case. c) The case whose value is closest to the expression will be executed. d) None of the cases will be executed. e) An execution error will occur if there is no matching case and no default case. Answer: d Explanation: If none of the cases are matched, then none of the cases will be executed. 11) Suppose we want to write an if statement to test whether two String objects, referenced by stringOne and stringTwo, are the same. Which of the following is the correct way to achieve this? a) b) c) d) e)

if(stringOne == stringTwo) if(stringOne.compareTo(stringTwo)) if(stringOne.equals(stringTwo)) if(stringOne != stringTwo) if(stringOne === stringTwo)

Answer: c Explanation: In Java, a programmer should not use conditional operators to compare objects for equality. Instead, the equals() method should be used. Therefore choice c is correct, and choices a and d are incorrect. The compareTo() method returns an int and not a boolean, so choice b will not compile. There is no operator in Java that is represented by ===, so choice e is incorrect. 12) A(n) _________________ is an object that has methods that allow you to process a collection of items one at a time. a) iterator b) loop c) conditional d) palindrome e) nested loop Answer: a Explanation: An iterator is an object that has methods that allow you to process a collection of items one at a time. None of the other choices are objects in Java. 13) A logical expression can be described by a ________________ that lists all possible combinations of values for the variables involved in an expression. a) palindrome b) nested loop c) equality operator d) switch statement e) truth table Answer: e Explanation: A truth table lists out all possible combinations of values for the variables involved in an input expression and also lists the evaluation of a logical expression. 4.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 4

14) The expression that is evaluated at the start of a switch statement must not be which primitive data type below? a) b) c) d) e)

byte short int char double

Answer: e Explanation: The possible primitive data types for the expression of a switch statement are byte, short, int, and char. 15) Which of the following for loop headers will cause the body of the loop to be executed 100 times? a) b) c) d) e)

for(int i = 0; i <= 100; i++) for(int i = 1; i < 100; i++) for(int i = 1; i <= 101; i++) for(int i = 0; i < 100; i++) none of these for loops will execute the loop body 100 times

Answer: d Explanation: For choice a, the variable i has the values 0, 1, 2, …, 99, and 100, which are 101 values. For choice b, the values of i are 1, 2, 3, …, 97, and 98, which are 98 values. For choice c, the values of i are 1, 2, 3, …, 100, and 101, which are 101 values.

5 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 4

True/False Questions: 1) Every if statement requires an associated else statement, but not every else statement requires an associated if statement. Answer: False Explanation: Every else statement requires an associated if statement, but not every if statement requires an associated else statement. 2) In a nested if statement an else clause is matched to the closest unmatched if. Answer: True Explanation: Any ambiguity among if-else statements is resolved using this rule in Java. 3) In Java, a boolean expression is limited to having exactly 2 logical operators. Answer: False Explanation: A boolean expression can have any number of logical operators, so it is possible to construct sophisticated conditions using a single boolean expression. 4) A do statement should be used to avoid creating an infinite loop. Answer: False Explanation: It is possible to create an infinite loop with any of the loop statements. Proper coding and attention to the condition that controls loop execution are essential to avoiding infinite loops. 5) A while statement always executes its loop body at least once. Answer: False Explanation: A do statement always executes its loop body at least once. A while statement will not execute its loop body if its condition evaluates to false on the first pass. 6) The initialization portion of a for loop header can be used to declare a variable that is used during loop execution. Answer: True Explanation: If a variable is only needed during the execution of the body of a for loop, it can be declared and initialized in the for loop header. 7) The relational operators should not be used to test the equality of objects. Answer: True Explanation: To test the equality of objects, the equals()method should be used. The compareTo() method may also be used to test for equality when it returns 0. 8) It is possible to implement a switch statement using if statements. Answer: True Explanation: A programmer can implement any switch statement using a series of nested if statements. The code for a switch statement may be clearer and more readable, however. 9) An infinite loop is a compile-time error. Answer: False Explanation: An infinite loop is usually caused by a logical error, and will not be caught by the compiler. 10) The Scanner object can be used to read text files. Answer: True Explanation: The Scanner object can be used to read text files by passing a File object to its constructor.

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 4

Short Answer Questions: 1) Using the following declarations and initializations: int num1 = 5, num2 = 12, num3 = 13; write a boolean expression that is true when the sum of num1 and num2 is more than num3, or when the value of num1 is an odd number. Answer: ( (num1 + num2 > num3) || (num1 % 2 == 1) ) 2) Write a snippet of code that determines which of two integer variables, intOne and intTwo, contains a larger number, and print out the larger one. If they are equal, the output should say that. Answer: if (intOne > intTwo) System.out.println(intOne + " is larger than " + intTwo); else if(intOne < intTwo) System.out.println(intTwo + " is larger than " + intOne); else System.out.println(intOne + " and " + intTwo + " are equal!"); 3) name is a String object that contains user input. Write a segment of code that determines if name contains "George". If it does, print the message "Hey, that's my name too! " Answer: if (name.equals("George")) System.out.println("Hey, that's my name too!"); 4) What is output by the following code fragment? int num = 0; int max = 10; while(num < max) { System.out.print(num + " "); num += 2; } Answer: This code will output the following: 0 2 4 6 8

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 4 5) Rewrite the following code fragment using a for loop instead of a while loop. int i = 0; while(i < 50) { System.out.println(i); i+=2; } Answer: for(int i = 0; i < 50; i+=2) System.out.println(i); 6) Write a short application that takes in a String from the user and prints it out backwards. Answer: import java.util.Scanner; public class StringReverse { public static void main(String [] args) String inputString;

{

Scanner input = new Scanner(System.in); System.out.print("Please enter a string: "); inputString = input.nextLine(); for(int i = inputString.length – 1; i >= 0; i--) System.out.print(inputString.charAt(i)); }//end main }//end class 7) The following code compiled, but while running it the program appears to hang (e.g. nothing happens). This is a sign that there may be an infinite loop. What part of this code fragment may be causing an infinite loop? while(i < 50); { System.out.println(i); i+=2; } Answer: There is a misplaced semi-colon after the while statement. This causes the loop to have an empty body, meaning that the i variable is never updated. This leads to an infinite loop.

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 4 8) grade is a char variable that holds a letter grade 'A', 'B', 'C', 'D', or 'F'. Write a switch statement that prints one of the messages in the table below based on the value in grade. Grade A B C D F any other value

Message Excellent! Very Good Good You can do better You must do better Error – invalid grade detected

Answer: switch (grade){ case 'A': System.out.println("Excellent!"); break; case 'B': System.out.println("Very Good"); break; case 'C': System.out.println("Good"); break; case 'D': System.out.println("You can do better"); break; case 'F': System.out.println("You must do better"); break; default: System.out.println("Error – invalid grade detected"); } // end switch 9) How many times will the body of a while loop be executed if the boolean expression is false the first time that the while statement is encountered? Answer: The body will not be executed at all. The expression of a while loop is evaluated before the body is executed, so a false expression means that the body will not be executed.

9 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 4 10) Write a short code fragment that uses a while loop to verify that the user enters a positive integer as input. You may assume that a Scanner object named input has already been created. Answer: System.out.print("Please enter a positive value: "); int value = input.nextInt(); while(value <= 0) { System.out.println("Error (the number was not positive)"); System.out.print("Please enter a positive value: "); value = input.nextInt(); } 11) Write a do loop that verifies that the user enters an odd value. You may assume that a Scanner object named input has already been created. Answer: int value; do { System.out.print("Please enter an odd value: "); value = input.nextInt(); if(value%2 != 1) System.out.println("Error (the number was not odd)"); } while(value%2 != 1); 12) Write a switch statement that switches on an integer variable named val. If val is 2 or 15, then output "Hello World." For all other values, output "Goodbye World." Answer: switch(val) { case 2: System.out.println("Hello World!"); break; case 15: System.out.println("Hello World!"); break; default: System.out.println("Goodbye World!"); }

10 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 4 13) Write a code fragment that allows a user to continue inputting numbers until she enters a sentinel value of 0. Then print the sum of all the numbers she entered. You may assume that a Scanner object named input has already been created. Answer: int sum = 0; int inputInt; do { System.out.print("Please enter an integer (0 to quit): "); inputInt = input.nextInt(); sum += inputInt; }while(inputInt != 0); System.out.println("The sum of the numbers is " + sum); 14) Write a code fragment that determines how many times the character 'A' appears in a String object called name. Answer: int countA = 0; for(int i = 0; i < name.length(); i++) if(name.charAt(a) == 'A') countA++; System.out.println("A appears " + countA + " times in " + name + "."); 15) line is a String object that holds an unknown number of int values separated by spaces. Write a segment of code that will compute and display the sum of the values in line. Answer: int sum = 0; int val; // the next value from line Scanner s = new Scanner(line); while (s.hasNext()) { val = s.nextInt(); sum += val; } System.out.println("The sum is " + sum);

11 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 5

Chapter 5: Writing Classes Multiple Choice Questions: 1) A ________________ diagram helps us visualize the contents of and relationships among the classes of a program. a) class and object b) UML c) object-oriented d) public e) private Answer: b Explanation: A UML diagram helps us visualize the contents and relationships among the classes of a program. The other choices do not refer to any type of diagram. 2) Regression testing refers to a) re-testing a program after fixing a problem to ensure that the fix worked and that it did not introduce another problem. b) executing the statements in the program in reverse order. c) executing the program on many different types of computers and comparing the results. d) running a program with many different sets of inputs. e) None of these describes regression testing Answer: a Explanation: Once an error is found and fixed, regression testing is the process of re-testing the program to both determine that the original problem is fixed and to detect if any new errors were introduced by the fix. Choice d) refers to the general notion of designing sets of inputs to exercise as many branches of a program as possible. 3) When applied to instance variables, the ________________ visibility modifier enforces encapsulation. a) static b) final c) public d) private e) none of the above Answer: d Explanation: The private visibility modifier guards against inappropriate data access, and therefore promotes encapsulation. Choices a) and b) are not visibility modifiers, and choice c) is a visibility modifier that allows public access to an object's data, which violates the principle of encapsulation.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 5 4) Which of the following types of methods do not have any return type (not even a void return type)? a) methods declared as static b) methods declared as public c) methods declared as private d) constructors e) all of the above have return types Answer: d Explanation: Constructors are the only methods that do not have any return type. They do not even have a void return type. All of the other methods must specify a return type or be declared as void. 5) Which of the following method headers is most likely a header for a mutator method? a) public int getAge() b) public double computeSalary() c) public Person() d) public void setAge(int newAge) e) none of these are headers for a mutator method Answer: d Explanation: Mutators are methods that change the value of an instance variable, and are often referred to as "setters." Therefore, choice d) is the correct answer. Choice a) is an example of a header for a accessor method, often referred to as a "getter." Choice c) is a constructor, and choice b) is a class method. 6) A _______________ variable is shared among all instances of a class. a) static b) final c) public d) private e) none of the above Answer: a Explanation: A static variable is shared among all instances of a class. A final variable is a constant, a public variable is one that is accessible from outside the object and a private variable is one that cannot be accessed outside of the object. 7) A(n) __________________ is an application that displays the inner workings of an executing program. a) stethoscope b) telescope c) debugger d) signal analyzer e) oscilloscope Answer: c Explanation: Debugging is the act of locating and correcting run-time and logic errors in your programs. A debugger is a software application that allows us to observe the inner workings of a program as it executes. Choice a) is an analytic tool used in medicine. Choice b) is a tool used in astronomy. Choices d) and e) are used in analyzing hardware components.

2.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 5 8) The ________________ reference always refers to the currently executing object. a) null b) static c) final d) actual e) this Answer: e Explanation: The this reference always refers to the currently executing object. A null reference is a reference that is not pointing to any object. The other three choices are not special references in Java. 9) A method that has multiple definitions is an __________________ method. a) overloaded b) overridden c) overlooked d) overclocked e) none of the above Answer: a Explanation: A method that has multiple definitions is an overloaded method. The versions of an overloaded method are distinguished by the number, type and order of their parameters. Overridden methods are methods that have been redefined later in an inheritance hierarchy. They will be studied in more detail later. Choice c and d are not types of methods in Java. 10) A(n) ________________ is a step-by-step process for solving a problem. a) UML diagram b) aggregate object c) class d) algorithm e) none of the above Answer: d Explanation: An algorithm is a step-by-step solution for solving a problem. A UML diagram is a way of visually representing how classes and objects interact. An aggregate object is an object that is composed, in part, of other objects. A class can be thought of as a blueprint for a set of objects. 11) All methods (with the exception of constructors) must specify a return type. What is the return type for a method that does not return any values? a) int b) public c) double d) void e) none of the above Answer: d Explanation: Methods that do not need to return any data should have void specified as the return type. A method cannot have public specified as its return type, so choice b is incorrect. Choices a) and c) specify a return type, and therefore they must return data of that type.

3.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 5 12) Methods that can be called directly through the class name and do not need to have an object instantiated are called _________________. a) final b) public c) static d) private e) none of the above Answer: c Explanation: Methods that can be called directly through the class name must be declared as static. Choices b) and d) are visibility modifiers for a method. Methods declared as final cannot be overridden. 13) A(n) ___________________ object is one that is made up, at least in part, of other objects. a) static b) aggregate c) encapsulated d) private e) public Answer: b Explanation: An aggregate object is one that is made up of other objects. Choice a), d) and e) do not refer to types of objects. Encapsulated objects may be made up of primitive types or object types. 14) If a service is so complex that it cannot be reasonably be implemented using one method, it is often helpful to decompose it to make use of ________________ support methods. a) static b) aggregate c) private d) public e) final Answer: c Explanation: Private support methods are useful when a service is too complex to be defined in a single method. Therefore choice c) is correct. 15) The versions of an overloaded method are distinguished by ___________________________. a) the number, type and order of their parameters b) their identifiers c) their classes d) the number and type of their parameters e) the number of their parameters Answer: a Explanation: Overloaded methods are two methods in the same class that have the same identifier, but a different number, type or order of parameters. Therefore, choice a) is correct and the rest are incorrect.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 5

True/False Questions: 1) A variable can always be referenced anywhere in a program. Answer: False Explanation: Scope rules, based on a variable's declaration, determine where it can be referenced. 2) An object can be thought of as a blueprint for a set of classes. Answer: False Explanation: A class can be thought of as a blueprint for a set of objects; not the other way around. 3) A return statement is not required at the end of every method. Answer: True Explanation: Constructors and methods with a return type of void do not require return statements. 4) Black-box testing uses the internal structure and implementation of the code to be tested in designing the tests. Answer: False Explanation: Black-box testing treats the code being tested as a black box that cannot be opened or examined. Tests are developed based on possible inputs and expected outputs. Black-box testing does not use knowledge of the internal design or the structure of the code. 5) A break point is a statement in a program that causes the program to crash. Answer: False Explanation: A breakpoint is a statement in a program that is marked for use by a debugger. When a program is running under the control of a debugger, execution will pause when a breakpoint is encountered. When paused, the contents of variables can be examined. Program execution can then be resumed in one of several ways: run until the program completes, run until the next breakpoint, run a single statement, etc. 6) A main method can only access static or local variables. Answer: True Explanation: A main method cannot access non-static and non-local variables because it is a static method. In particular, it cannot access any variables declared at the class level. 7) In a class that has variables called height and width, methods called getHeight() and getWidth() are examples of accessor methods. Answer: True Explanation: Accessor methods return the value of instance variables. They are often named using the word 'get' followed by the name of the instance variable. 8) Every class has a constructor, whether defined by the programmer or not. Answer: True Explanation: Every class automatically has a default constructor that doesn't take any parameters. The default constructor is used when objects are created if no other constructor is defined. 9) Variables that are declared as static are shared among all instances of a class. Answer: True Explanation: Static variables are sometimes called class variables because they are shared among all instances of a class. 10) Aggregation is sometimes described as a has-a relationship. Answer: True Explanation: Aggregate objects are objects that contain other objects as instance variables. Therefore the relationship between an object that is an aggregate of other objects is often described as a has-a relationship.

5.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 5

Short Answer Questions: 1) What is the difference between an object and a class? Answer: A class can be thought of as the blueprint for an object. In other words, the object is the embodiment of a class. 2) Explain the difference between actual parameters and formal parameters. Answer: Formal parameters are used in the definition of a method, while actual parameters are the values that are used in the method call. 3) What is encapsulation? How can it be enforced in Java? Answer: Encapsulation is the principle that objects should be self-governing. In other words, an object's internal data should be protected from outside access. Encapsulation can be enforced in Java by making instance variables private. 4) What is instance data? Answer: Instance data refers to the data that will be stored in each object of a class. New memory space is allocated for instance data every time that an object is created. Each object of a class has its own unique memory allocation, so that its instance data is unique from that of any other objects of the same class. 5) Write a method called randomInRange that takes in two numbers representing a range. Print an error message and return zero if the second parameter is less than the first. Otherwise, the method should return a randomly generated integer in that range (inclusive). You may assume that the class has a static Random object called generator already declared and instantiated. Answer: public int randomInRange(int a, int b) { if(b < a) { System.out.println("Error, invalid range!"); return 0; } return generator.nextInt(b – a + 1) + a; }

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 5 6) Write a method called isPalindrome that accepts a String as a parameter and returns true if the String is a palindrome, and false otherwise. You may assume that the entered String consists entirely of lowercase letters (meaning it contains no numbers, spaces, punctuation, etc). Hint: write code that creates a new string that is the original string reversed, and then check to see if the two strings are equal. Answer: public boolean isPalindrome(String s) { String reverseS = new String(""); for(int i = s.length()-1; i >= 0; i--) reverseS += s.charAt(i); return reverseS.equals(s); } 7) What is the difference between a service method and a support method in a class definition? Answer: A service method is used to access or modify the data values of an object. They generally have public visibility. Support methods are designed to be used by service methods to support the tasks that the service methods perform. Support methods generally have private visibility. 8) Can a static method access instance data in a class? Answer: No. Static methods are defined at the class level. Instance data is allocated at the object level. Static methods do not have access to object level data. 9) Student is a class that has the following instance variables: name (a String), yearInSchool (an int), and gpa (a double). Write a constructor for the Student class that takes parameters for these instance variables as initial values of the variables. Use the this reference in the constructor. Answer: public Student(String name, int yearInSchool, double gpa) { this.name = name; this.yearInSchool = yearInSchool; this.gpa = gpa; } 10) Java uses pass by value for passing parameters on a method call. What does this mean if the parameter is a primitive data type? What does this mean if the parameter is a reference to an object? Answer: Pass by value means that the value associated with the actual parameter is copied into the memory location of the formal parameter when the method is called. The formal and actual parameters occupy distinct locations in memory. If the parameter is a primitive data type, any modifications made to the formal parameter during the execution of the method will most likely not be reflected in the actual parameter. If the parameter is a reference to an object, then it holds the location of an object. While the formal and actual parameters will be distinct, they will both hold the address of the object and will be aliases. If the method modifies the object, then those modifications will be apparent when referencing the object using the actual parameter after the method terminates.

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 5 11) Give an example of how a static variable can be used in a class. Answer: Suppose that a program needs to keep track of how many objects of a particular class have been created. Declaring and managing a counter at the program level could be a complex task. It might be simpler to let the class itself maintain the counter. A static int variable could be declared at the class level to be used as a counter. All of the constructors of the class could increment the static variable. A static method would also be needed to return the value of the counter. 12) Method overloading requires that the methods have different signatures. What parts of a method are used in the signature? Answer: The method name, the number of parameters, the types of the parameters, and the orders of the parameters are all part of the method signature. 13) Explain why method overloading is useful. Answer: Method overloading is useful because it allows multiple methods to have the same name as long as they have different parameter types. This allows for more flexibility in choosing identifiers for methods, since the alternative would require the programmer to have different method identifiers for every method that took in a different type of parameter. 14) How are unit testing, integration testing, and system testing related? How are they different? Answer: They are related in that they are all forms of software testing. They differ in respect to the size (the amount of code) that they test. Unit testing tests the individual modules or components as units. These units may be individual classes or methods. Integration testing combines several related units and tests them as a collective entity. System testing tests the overall software system as a whole, which is comprised of several sets of software that have passed integration testing. 15) How can a print() or println() statement be used in debugging? Answer: Print statements can be used to show the contents of variables at specific points in the code execution. This can be useful if a program produces incorrect results and the programmer or tester is trying to detect where an incorrect value first appeared in the code.

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 6

Chapter 6: Graphical User Interfaces Multiple Choice Questions: 1) The default layout manager used by the JPanel class is the _______________________ layout. a) flow b) border c) box d) grid e) gridBag Answer: a Explanation: The flow layout is the default layout manager used by JPanel objects. 2) A(n) ___________________ is an object that defines a screen element used to display information or allow the user to interact with a program in a certain way. a) GUI b) component c) event d) listener e) AWT Answer: b Explanation: A component is an object that defines a screen element used to display information or allow the user to interact with a program in a certain way. A GUI is a graphical user interface. An event is an object that represents some occurrence in which we may be interested. A listener is an object that waits for an event to occur and responds in some way when it does. AWT stands for the Abstract Windowing Toolkit, which is a package that contains classes related to Java GUIs. 3) A(n) ____________________ is an object that waits for an event to occur and responds in some way when it does. a) GUI b) component c) listener d) frame e) panel Answer: c Explanation: A listener is an object that waits for an event to occur and responds in some way when it does. A component is an object that defines a screen element used to display information or allow the user to interact with a program in a certain way. A GUI is a graphical user interface. A frame is a container that is used to display GUI-based Java applications. A panel is also a container, but unlike a frame it cannot be displayed on its own.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 6 4) A GUI is being designed that will detect and respond to a mouse event. How many methods must appear in the listener object for the event? a) 1 b) 2 c) 3 d) 4 e) 5 Answer: e Explanation: A listener for a mouse event implements the MouseListener interface. The MouseListener interface contains specifications for five methods to respond to different types of mouse events that can be detected. Each of these methods must appear in the listener and have a body. If a method is not needed, its body can be an empty set of { }. 5) A container is governed by a(n) __________________, which determines exactly how the components added to the panel will be displayed. a) event b) content pane c) JFrame object d) JPanel object e) layout manager Answer: e Explanation: The layout manager determines exactly how the components added to the panel will be displayed. A content pane's frame is where all visible elements of a Java interface are displayed. The JFrame and JPanel objects are part of the AWT package. An event is an object that represents some occurrence in which we may be interested. 6) Which of the following components allows the user to enter typed input from the keyboard. a) check boxes b) radio buttons c) sliders d) combo boxes e) none of the above Answer: e Explanation: None of the listed components allow typed input. A text field allows typed input from the user. 7) Which of the following components allows the user to select one of several options from a "drop down" menu? a) check boxes b) radio buttons c) sliders d) combo boxes e) none of the above Answer: d Explanation: Combo boxes allow the user to select one of several options from a "drop down" menu.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 6 8) Which of the following layout managers organize the components from left to right, starting new rows as necessary? a) Border Layout b) Box Layout c) Card Layout d) Flow Layout e) Grid Layout Answer: d Explanation: The flow layout organizes components from left to right, starting new rows as necessary. A border layout organizes components into five areas: north, south, east, west, and center. The box layout organizes components into a single row or column. The card layout organizes components into one area such that only one is visible at any time. A grid layout organizes components into a grid of rows and columns. 9) Which of the following event descriptions best describes the mouse entered event? a) The mouse button is pressed down b) The mouse button is pressed down and released without moving the mouse in between c) The mouse pointer is moved onto a component d) The mouse button is released e) The mouse is moved while the mouse button is pressed down Answer: c Explanation: The mouse entered event is triggered when the mouse pointer is moved onto a component. Choice a best describes a mouse pressed event. Choice b best describes a mouse clicked event. Choice d best describes a mouse released event. Choice e best describes a mouse dragged event. 10) A(n) _______________________ is a graphical window that pops up on top of any currently active window so that the user can interact with it. a) component b) dialog box c) event d) listener e) none of the above Answer: b Explanation: The sentence describes a dialog box. Events and listeners are not windows. Components are graphical elements that appear in windows, but they are not windows. 11) Which of the following is a fundamental idea of good GUI design? a) Know the user b) Prevent user errors c) Optimize user abilities. d) Be consistent. e) all of the above Answer: e Explanation: All of the choices are fundamental ideas of good GUI design.

3 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 6 12) Which of the following best describes a timer component? a) it starts when a GUI component is first initialized, and ends when it is destroyed b) it generates action events at regular intervals c) every object has a timer, and it is implicitly activated in the constructor of the object d) it determines the amount of time it takes to execute a method e) a timer cannot be considered a GUI component Answer: b Explanation: Choice b is the best description of a timer component. None of the other choices are true statements. 13) Which of the following border styles can make a component appear raised or lowered from the rest of the components? a) line border b) etched border c) bevel border d) titled border e) matte border Answer: c Explanation: A bevel border can be used to add depth to a component and give it a 3-D appearance. 14) Which of the following represents a dialog box that allows the user to select a file from a disk or other storage medium? a) color chooser b) disk chooser c) tool tip chooser d) file chooser e) none of the above Answer: d Explanation: A file chooser is a dialog box that allows the user to select a file. A color chooser allows the user to select a color. There are no dialog boxes in the AWT that represent a tool tip chooser or a disk chooser. 15) Which of the following classes play a role in altering a visual aspect of a component? a) ColorChooser b) ToolTip c) BorderFactory d) ColorCreator e) none of the above Answer: c Explanation: The BorderFactory class can be used to create borders, and when used with the setBorder() method, the borders of components can be changed. The other options are not classes that are included with the AWT.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 6

True/False Questions: 1) A panel is displayed as a separate window, but a frame can only be displayed as part of another container. Answer: False Explanation: A frame is displayed as a separate window, but a panel can only be displayed as part of another container. 2) Layout managers determine how components are visually presented. Answer: True Explanation: Every container is managed by a layout manager, which determines how components are visually presented. 3) Check boxes operate as a group, providing a set of mutually exclusive options. Answer: False Explanation: Radio buttons operate as a group, providing a set of mutually exclusive options. Check boxes are buttons that can be toggled on or off using the mouse, indicating that a particular boolean condition is set or unset. 4) A dialog box allows the user to select one of several options from a "drop down" menu. Answer: False Explanation: A combo box allows the user to select one of several options from a "drop down" menu. A dialog box is a pop-up window that allows for user interaction. 5) The grid layout organizes components into a grid of rows and columns, and also allows components to span more than one cell. Answer: False Explanation: Both the grid and the GridBag layouts organized components into a grid of rows and columns. Only a GridBag layout allows components to span more than one cell. 6) The keyHit event is called when a key is pressed. Answer: False Explanation: The keyPressed event is called when a key is pressed. 7) A tool tip can be assigned to any Swing component. Answer: True Explanation: All Swing components can be assigned a tool tip, which is a short line of text that will appear when the cursor is rested momentarily on top of the component.. 8) A color chooser is a dialog box. Answer: True Explanation: A color chooser is a dialog box that allows the user to select a color from a palette or using RGB values. 9) When designing a GUI, the ability of the user is not an important consideration. A GUI should be designed with the lowest common denominator in mind. Answer: False Explanation: It is important to design GUIs that are flexible and that support both skilled and unskilled users. 10) A mnemonic is a short line of text that will appear when the cursor is rested momentarily on top of the component. Answer: False Explanation: A mnemonic is a character that allows the user to push a button or make a menu choice using the keyboard in addition to the mouse. A tool-top is a short line of text that will appear when the cursor is rested momentarily on top of the component.

5.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 6

Short Answer Questions: 1) Explain the difference between check boxes and radio buttons. Answer: A check box sets a boolean condition to true or false. Therefore if there are multiple items listed with check boxes by each, any or all of them can be checked at the same time. A radio button represents a set of mutually exclusive options. This means that at any given time, only one option can be selected. 2) Explain the difference between a combo box and a dialog box. Answer: A combo box is a component that allows the user to select one of several options from a "drop down" menu. A dialog box is a graphical window that pops up on top of any currently active windows so that the user can interact with it. 3) Give an example of a common use of a dialog box. Answer: A confirm dialog box presents the user with a simple yes-or-no question. A file chooser is a dialog box that presents the user with a file navigator that can be used to select a file. A color chooser is a dialog box that allows the user to select an RGB color. 4) What method in what interface is used in a GUI application to detect that a user typed the letter 'Y'? Answer: The keyPressed() method in the KeyListener interface can be used to determine which key was typed. 5) Write a keyPressed method that behaves as follows. If the user presses the up arrow, the method should output "You pressed up" using the System.out.println method. If the user presses the down arrow, the method should output "You pressed down" using the System.out.println method. Answer: public void keyPressed(KeyEvent event) { switch(event.getKeyCode()) { case KeyEvent.VK_UP: System.out.println("You pressed up."); break; case KeyEvent.VK_DOWN: System.out.println("You pressed down."); break; }//end switch }//end method 6) When, if ever, should a component be disabled? Answer: A component should be disabled whenever it is inappropriate for the user to interact with it. This minimizes error handling and special cases.

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 6 7) Write a segment of code that will use a dialog box to ask a user to enter their age. Their age will then be stored in an int variable named userAge. Assume that the necessary import statements to support the dialog box are already in place. Answer: int userAge; String ageStr; // used for user's response ageStr = JOptionPane.showInputDialog("How old are you"?); userAge = Integer.parseInt(ageStr); 8) Write a short class that represents a panel with a single radio button that has the option "Yes" and the option "No." By default, the Yes button should be checked. Answer: import javax.swing.*; import java.awt.*; public class RadioPanel extends JPanel private JRadioButton yes, no;

{

public RadioPanel() { yes = new JRadioButton("Yes", true); no = new JradioButton("No");

} }

add(yes); add(no); // end constructor

// end class RadioPanel

9) Suppose we have created a class called MyGUI, which represents a GUI. Write a program that creates a JFrame object, adds a MyGUI object to the frame and makes it visible. Answer: import javax.swing.*; public class MyGUIDisplayer { public static void main(String [] args) { JFrame frame = new Jframe("My GUI"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new MyGUI()); frame.pack(); frame.setVisible(true); }

} // end main // end class MyGUIDisplayer 7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 6

10) Write a short class that represents a panel with a single slider that has values from 0 to 250, with large tick marks in increments of 50 and small tick marks in increments of 10. Answer: import javax.swing.*; import java.awt.*; public class SlidePanel extends JPanel private JSlider slide;

{

public SlidePanel() { slide = new Jslider(JSlider.HORIZONTAL, 0, 255, 0); slide.setMajorTickSpacing(50); slide.setMinorTickSpacing(10); slide.setPaintTicks(true); slide.setPaintLabels(true);

}

add(slide); } // end constructor // end class SlidePanel

11) Describe the areas of a border layout. Answer: Border layout is divided into five areas: North, South, East, West and Center. The North and South areas are at the top and bottom of the container, respectively, and span the entire width of the container. Sandwiched between them, from left to right, are the West, Center, and East areas. Any unused area takes up no space, and the others fill in as needed. 12) One of the fundamental ideas of good GUI design is to "know the user". How does "know the user" influence a GUI design? Answer: The software has to meet the user's needs. This means not only that it has to do what it is designed to do, but it also must be software that the user understands how to use. It needs to have an interface that the user is comfortable with in order to be usable and useful to the user. A person who designs a GUI without an awareness of the user's preferences or skills is less likely to please the user than someone who takes these into consideration. 13) What is the difference between a mnemonic and a tool tip? Answer: A mnemonic is a character that allows the user to push a button or make a menu choice using the keyboard in addition to the mouse. A tool-top is a short line of text that will appear when the cursor is rested momentarily on top of the component. The difference is that the mnemonic allows for more flexibility on the users end (it allows for multiple methods of achieving the same task), which a tool-tip is simply a helpful reminder of the role of a particular component and offers no flexibility on the users end.

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 6 14) Describe the difference between a heavyweight container and a lightweight container. Give an example of each. Answer: A heavyweight container is a container that is managed by the underlying operating system on which the program is run, whereas a lightweight container is managed by the Java program itself. A frame is an example of a heavyweight container and a panel is a lightweight container. 15) When using a box layout, how is the orientation – horizontal or vertical box – specified? Answer: The orientation is specified as a parameter to the BoxLayout constructor. BoxLayout.Y-AXIS indicates a vertical box layout. BoxLayout.X-AXIS indicates a horizontal box layout.

9 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 7

Chapter 7: Arrays Multiple Choice Questions: 1) In Java, array indexes always begin at ________________ . a) -1 b) 0 c) 1 d) 2 e) you can declare an array to have any indexes you choose Answer: b Explanation: In Java, the array indexes are from 0 to one less than the length of the array. 2) Which of the following statements best describes this line of code? numbers[5] = 12; a) The value 12 is put into the numbers array at the location with index 5. b) The value 5 is put into the numbers array at the location with index 12. c) numbers is declared to be an array of 5 elements, each of which contains the number 12. d) numbers is declared to be an array of 12 elements, each of which contains the number 5. e) none of the above is correct Answer: a Explanation: The code represents the assignment of the value 12 to the location in the numbers array with index 5. 3) Which of the statements is true about the following code snippet? int[] array = new int[25]; array[25] = 2; a) The integer value 2 will be assigned to the last index in the array. b) The integer value 25 will be assigned to the second index in the array. c) The integer value 25 will be assigned to the third value in the array. d) This code will result in a compile-time error. e) This code will result in a run-time error. Answer: e Explanation: This code will throw an ArrayIndexOutOfBoundsException, since the last index in this array will be 24. This causes a run-time error.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 7 4) What does this array contain? String [] studentNames = new String[25]; a) names b) students c) studentNames d) Strings e) references to Strings Answer: e Explanation: The elements of the array are Strings, which are objects. As such, the array contains references to objects, not the objects themselves. The Strings may be the names of students, but the array elements are not names, students, or studentNames. 5) Which of the following array declarations are invalid? a) int[] grades = new int[5]; b) int grades[] = new int[5]; c) int[] grades = { 91, 83, 42, 100, 77 }; d) all of the above are valid e) none of the above are valid Answer: d Explanation: All three of these are valid array declarations. Choice b uses an alternate syntax. Choice c uses an initializer list to initialize the array. 6) Which of the following is a true statement? a) Arrays are passed as parameters to methods like primitive types. b) Arrays are passed as parameters to methods like object types. c) Arrays cannot be passed as parameters to methods. d) All of the above are true. e) None of the above are true. Answer: b Explanation: Arrays are passed to methods by reference. This means that if the content of the array is changed in a method, the change will be reflected in the calling method. 7) Suppose we have an array of String objects identified by the variable names. Which of the following for loops will not correctly process each element in the array. a) for(int i = 0; i < names.length; i++) b) for(String name : names) c) for(int i = 0; i < names.length(); i++) d) none of these will correctly process each element e) all of these will correctly process each element Answer: c Explanation: Choice c will not process each element correctly due to a syntax error. The length constant is not a method and, therefore, does not have parentheses after it. Choice b is an example of using a foreach loop to process an array, and choice a is a correct for loop. 2.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 7

8) Which of the following statements will assign the first command-line argument sent into a Java program to a variable called argument? a) argument = System.getFirstArgument(); b) argument = System.getArgument[1]; c) argument = System.getArgument[0]; d) argument = args[0]; e) argument = args[1]; Answer: d Explanation: Choice d is the correct answer. The System object does not have any methods called getFirstArgument or getArgument, and the args array's index starts at 0. Therefore the other choices are incorrect. 9) Which of the following method declarations correctly defines a method with a variable length parameter list? a) public int average(int[] list) b) public int average(int ... list) c) public int average(...) d) public int average(int a, int b, int c, ...) e) public int average(integers) Answer: b Explanation: The only choices with valid syntax are choice a and choice b. Choice a represents a method declaration with a single parameter, which is a reference to an array. Choice b correctly represents a valid declaration for a method with a variable length parameter list. 10) Which of the following is a valid declaration for a two-dimensional array? a) int[][] matrix; b) int[2] matrix; c) int[]** matrix; d) int[] matrix; e) none of these are correct Answer: a Explanation: Choice a is the only valid declaration for a two-dimensional array. Choices b and c contain invalid Java syntax, and choice d is a valid declaration for a single dimensional array. 11) Which of the following lines of code accesses the second element of the first array in a two-dimensional array of integers, numbers, and stores the result in a variable called num? a) num = numbers[1][2]; b) num = numbers[0][1]; c) num = numbers.getElement(1, 2); d) num = numbers.getElement(0, 1); e) none of the above are correct Answer: b Explanation: Choice b accesses the second element of the first array. Choice a accesses the third element of the second array. Choices c and d do not represent valid Java syntax. 3.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 7

12) Which of the following are true about two-dimensional arrays? a) Two-dimensional integer arrays cannot be initialized via an initializer list. b) Two-dimensional arrays can only store up to 10 elements per array (or per row). c) Two-dimensional arrays are not accessible using for loops. d) Two-dimensional arrays cannot hold objects. e) None of the above is true. Answer: e Explanation: None of the statements about two-dimensional arrays are true. 13) How do you determine the number of command-line arguments a program has? a) The numArgs constant contains the number of command-line arguments. b) The first member of the args array is the count of the number of command-line arguments. c) The number of command-line arguments is the length of the args array. d) The number of command-line arguments is one less than the length of the args array. e) The number of command-line arguments is fixed and is 5. Answer: c Explanation: args is the array that contains the command-line arguments as Strings. args.length is the number of command-line arguments. 14) What is the limit of the number of variable parameters that can be passed to a method that has a variable-length parameter list? a) 5 b) 10 c) 16 d) less than 100 e) none of the above Answer: e Explanation: A variable-length parameter list is converted to an array when the method is called. Since the length of an array is not limited to the numbers 5, 10, 16 or some number less than 100, none of the choices a) through d) can be correct. 15) Multi-dimensional arrays that contain arrays of different lengths in any one dimension are called _________________. a) ragged arrays b) static arrays c) two-dimensional arrays d) constant arrays e) overloaded arrays

lengths.

Answer: a Explanation: Ragged arrays are multi-dimensional arrays that contain arrays at the same dimension with differing

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 7

True/False Questions: 1) In Java, array indexes begin at 0 and end at one less than the length of the array. Answer: True Explanation: For an array of length n, the indexes begin at 0 and end at n – 1 in Java. 2) If an array is declared to hold objects, none of the objects can have instance variables that are arrays. Answer: False Explanation: If an array holds objects, each element of the array is a reference to an object. There are no restrictions on the instance variables or the methods of the objects that are the referenced by the elements of the array. 3) An array declared as an int[] can contain elements of different primitive types. Answer: False Explanation: An array that has been declared with a specific type may only contain elements of that type. In this case the array can only contain integers. 4) The elements of a two-dimensional array are called rows and columns. Answer: False Explanation: We consider the elements of a two-dimensional array as being arranged in a table that has rows and columns. The rows are represented by the first subscript of the array, while the column within a row is indicated by the second subscript. The element in a particular row and column of a two-dimensional array is still called an element. 5) It is possible to store 11 elements in an array that is declared in the following way. int[] array = new int[10]; Answer: False Explanation: An array declared as above can only store 10 elements. 6) If a program attempts to access an element outside of the range of the array indexes, a run-time error will occur. Answer: True Explanation: If a program attempts to access an element outside of the range of the array indexes, an ArrayOutOfBoundsException will be thrown at run-time. 7) An array cannot hold object types. Answer: False Explanation: An array can be declared to hold references to objects. 8) It is possible to send in data to a Java program via the command-line. Answer: True Explanation: Command-line arguments can be sent in to a Java program. They are sent into the program via the args[] array. 9) It is possible for a method to have a variable length parameter list, meaning that the method can take in any number of parameters of a specified data type. Answer: True Explanation: Java supports variable length parameter lists for methods. 10) In Java it is not possible to have arrays of more than two dimensions. Answer: False Explanation: It is possible to have arrays of any dimension in Java.

5.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 7

Short Answer Questions: 1) Explain how arrays are passed to methods as parameters. Answer: Arrays are passed to methods by reference. This means that a reference to the original array is sent into the method. Therefore any changes that are made to the array in the method will be reflected in the original array in the calling method. 2) Write the declaration for an array of doubles called averages that is initialized with an initializer list. Answer: double[] averages = { 25.2, 36.18, 42.1, 30.5 }; 3) Write the declaration for a two-dimensional array of integers that can be thought of as a table with three rows and three columns. Assign the value 3 to the cell that is in the second row and the third column. Answer: int[][] table = new int[3][3]; table[1][2] = 3; 4) Write a loop that cycles through an array of String objects called names and prints them out, one per line. Answer: using a for loop: for(int i = 0; i < names.length; i++) System.out.println(names[i]); Answer:: using a foreach loop: for(String n : names) System.out.println(n); 5) How do you determine how the elements of an array can be used in a program? Answer: Refer to the array declaration to determine how the elements can be used. For example, if the array is declared with the type int [], then each element of the array is an individual int, and can be used in any way that is appropriate for an int. If the array is declared with a type that refers to a class, then the array elements are all references to objects of that class and can be used as such. 6) Student is a class that defines data fields and methods for an individual student. Write the declaration of an array named roster that can be used to reference 24 Student objects. Answer: Student [] roster = new Student[24];

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 7 7) Write a method called doubleSize that accepts an integer array as a parameter and returns a reference to a new integer array that is twice as long and contains all of the elements of the first array in the same positions. Answer: public int[] doubleSize(int[] originalArray) { int[] newArray = int[originalArray.length*2]; for(int i = 0; i < originalArray.length; i++) newArray[i] = originalArray[i]; return newArray; } 8) Circle is a class that has data and methods related to circles. How many Circle objects are created by the following declaration? Circle [] shapes = new Circle[12]; Answer: No Circle objects are created by the declaration. The array declaration creates references to 12 Circles, but the Circle objects must be separately instantiated and assigned to the array members. 9) What is the purpose of command-line arguments to a Java program? How can they be used? Answer: Command-line arguments are passed to the main method when execution commences. They can be used to provide input to a program in a non-interactive way. They are passed as an array of Strings. Individual arguments can be accessed using array subscript notation. 10) Write a method that takes in an arbitrary number of String objects, and then prints out all of them that have over 10 characters. Answer: public void printLongStrings(String ... words) for(String w : words) if(w.length() > 10) System.out.println(w); }

{

11) Write a method that takes in at least one integer and returns the largest of all integer parameters sent in. Answer: public void largest(int first, int ... numbers) int currentLargest = first; for(int num : numbers) if(num > currentLargest) currentLargest = num; return currentLargest; } 7.

{


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 7

12) Write a method that accepts an array of integers as a parameter and returns a reference to an array that contains the even numbers in the array original array. The returned array should have a size equal to the number of even numbers in the original array. Answer: public int[] getEvenArray(int[] numbers) int size = 0;

{

for(int i = 0; i < numbers.length; i++) if(numbers[i]%2 == 0) size++; int[] evenArray = new int[size]; int evenArrayIndex = 0; for(int i = 0; i < numbers.length; i++) { if(numbers[i]%2 == 0) { evenArray[evenArrayIndex] = numbers[i]; evenArrayIndex++; }//end if }//end for } 13) Write a short program that accepts an arbitrary number of command line arguments, and prints out those containing the character 'z'. Answer: public class PrintZArgs { public static void main(String[] args) { for(String s : args) { boolean printed = false; for(int i = 0; (i < s.length) && (!printed); i++) if(s.charAt(i) == 'z') { printed = true; System.out.println(s); } // end if // end inner for loop }//end foreach }//end main }//end class 14) Write a line of code that initializes a two-dimensional array of integers using an initializer list. Answer: int[][] numbers = { {2,3},{4,5} };

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 7 15) The following declaration allocates space for how many double variables? double [][][] temperatures = new double [10][20[]30]; Answer: This is the declaration of a 3-dimensional array. It can be viewed as a 10-element array (the first subscript) where each array element is a 2-dimensional array. The 2-dimensional arrays have 20 rows and 30 columns, so they have 20 x 30 = 600 elements. There are 10 2-dimensional arrays, so the total number of doubles allocated by this declaration is 10 x 600 = 6000 doubles.

9 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 8

Chapter 8: Inheritance Multiple Choice Questions: 1) The process of inheritance should establish a(n) ___________________ relationship. a) is-a b) has-a c) static d) not-a e) none of the above Answer: a Explanation: Inheritance should establish an is-a relationship. Therefore, any objects that are of a type lower in the inheritance hierarchy are also of a type higher in the inheritance hierarchy. 2) The original class that is used to derive a new class using inheritance is called ____________________ . a) a superclass b) a parent class c) a base class d) all of the above e) neither a, b, nor c Answer: d Explanation: The original class can be called a superclass, a parent class, or a base class. 3) __________ occurs when a child class defines a method with the same signature as a method in the parent class. a) Overloading b) Overriding c) Overwhelming d) Substituting e) A child class cannot define a method with the same signature as a parent class method. Answer: b Explanation: Overriding occurs when two methods, one in the parent class and one in the child class, have the same signature. The signature is the method name and the parameter list. 4) In order for derived classed to have access to encapsulated data members and methods of superclasses, the data members and methods should be declared using the ____________________ modifier. a) private b) public c) protected d) final e) static Answer: c Explanation: Data members and methods declared using the protected modifier can be accessed by subclasses in an inheritance hierarchy but are still encapsulated from classes and methods outside of the hierarchy. 1.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 8

5) A child class can access private members of a parent class by a) using super in front of the member name b) using the member name directly c) using this in front of the member name d) using the public accessor and mutator methods defined in the parent class e) A child class cannot access private members of a parent class. Answer: e Explanation: Private members of a parent class cannot be accessed from an object of a child class directly or through the use of super. They can be accessed by using the public accessor and mutator methods that the parent class provides. 6) When a variable declared in a subclass has the same name as a variable declared in a superclass, it is called a _______________ variable. a) final b) shadow c) static d) dead e) this is not allowed in Java Answer: b Explanation: A shadow variable is a variable in a subclass with the same name as a variable in the superclass. 7) A(n)______________________ class represents a generic concept in a class hierarchy. a) super b) abstract c) interface d) shadow e) generic Answer: b Explanation: An abstract class represents a generic entity that is not completely defined. An abstract class cannot be instantiated. It contains one or more abstract methods, which are methods that should be overridden by subclasses. 8) A class declared as final _________________________________ . a) cannot be changed. b) cannot have subclasses. c) cannot have superclasses. d) has several abstract methods. e) cannot be used in a program. Answer: b Explanation: The final modifier restricts inheritance. In particular, a class declared as final cannot have subclasses.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 8 9) Which of the following key words indicates a method that cannot be overridden in a derived class? a) super b) final c) extends d) inherits e) expands Answer: b Explanation: The key word final, when used in a method header, indicates that the method cannot be overridden in a derived class. 10) To invoke a parent’s constructor in a subclass, we use the ______________ method. a) abstract b) construct c) parent d) super e) extends Answer: d Explanation: The super method is used to invoke a parent’s constructor from a subclass. 11) Which of the following statements is not a general inheritance practice that you should keep in mind in the design of a program? a) Derived classes should have an “is-a” relationship with the parent classes. b) Use the final key word when defining parent classes. c) Avoid shadowing inherited variables when possible. d) Define abstract classes to specify a common class interface for concrete derived classes. e) All of these are general inheritance practices that should be considered when designing a program. Answer: b Explanation: Using the final key word in a class header indicates that the class cannot be extended or inherited from. It cannot be used in a class header if the class is intended to be the parent of one or more classes. 12) All Java classes are subclasses of the ___________________ class. a) String b) java.lang c) Java d) Class e) Object Answer: e Explanation: All classes are subclasses of Java's Object class, whether explicitly specified or not.

3 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 8 13) When designing a class hierarchy, it is important that common features be ________________________ . a) higher in the class hierarchy. b) lower in the class hierarchy. c) near the middle of the class hierarchy. d) in abstract classes. e) in the Object class. Answer: a Explanation: Common features should be included closer to the top of the class hierarchy. Doing this makes them available to more classes lower in the hierarchy. 14) Which of the following methods are included in every class created in Java by inheritance? a) next b) toString c) compareTo d) charAt e) none of the above Answer: b Explanation: The toString method is defined in the Object class and is therefore included in every Java class via inheritance. 15) Of the classes below, the one that is most likely to be declared abstract is _________________. a) Bat b) Squirrel c) Animal d) Iguana e) Parrot Answer: c Explanation: The Animal class is most likely to be abstract since it is the most generic.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 8

True/False Questions: 1) A parent class object must be created before objects of a child class can be created. Answer: False Explanation: Objects can be created from concrete classes at any point of an inheritance hierarchy in any order. 2) Private members of a parent class are inherited by child classes. Answer: True Explanation: Child classes inherit all of the members of a parent class, whether they are public, private, or protected. Private members cannot be accessed directly (by name) in the child class, but they are part of the derived class. 3) Java supports multiple inheritance. Answer: False Explanation: Java does not support true multiple inheritance, but it is possible to get some of the features of multiple inheritance using interfaces. 4) In Java, a subclass can only extend one parent class. Answer: True Explanation: Allowing a subclass to extend multiple parent classes leads to multiple inheritance, which is not supported in Java. 5) A child class is allowed to define a method with the same name and parameter list as a method in the parent class. Answer: True Explanation: A subclass is allowed to override methods that are in the parent class. 6) A child class is allowed to declare a variable with the same name as one that is contained in the parent class. Answer: True Explanation: This is known as variable shadowing and can lead to confusion. It is, however, permitted in Java. 7) An abstract class must contain abstract methods. Answer: False Explanation: A class declared as abstract may or may not contain abstract methods. 8) It makes sense to declare most abstract classes as final. Answer: False Explanation: Since an abstract class cannot be instantiated, it makes no sense to declare it as final. It is usually expected that an abstract class will be extended. 9) It is possible to derive a class from an abstract class without overriding all of the parents abstract methods. Answer: True Explanation: The child class must also be declared as abstract in this case. 10) Inheritance should not be considered in the software design process. Answer: False Explanation: Inheritance should be carefully considered in the software design process. Software systems designed carefully using inheritance can be more flexible than software designed without considering inheritance.

5 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 8

Short Answer Questions: 1) Explain why inheritance is useful. Answer: Inheritance is useful because it allows for code-reuse. This means that if we have multiple software entities that have common features, the code for the common features can be written once in a superclass. The classes that include these features can then be written via inheritance, and this common code does not have to be rewritten. 2) Compare and contrast the private visibility modifier to the protected visibility modifier. Why is the protected visibility modifier a better choice in an inheritance hierarchy? Answer: The private modifier and the protected modifier both enforce the encapsulation of instance variables and methods in a class. This means that unrelated classes are not able to directly access the variables and the methods. The protected modifier, however, does allow for the instance variables and the methods to be accessed by subclasses of the original class. This makes the protected modifier a better choice for use in an inheritance hierarchy, because it is often useful for subclasses to have access to a superclass's instance variables and methods. 3) Suppose we create a subclass from a class that has a method called someMethod. If we override someMethod in the subclass, is it possible to access the superclass's version of someMethod? If so, how? Answer: Yes, it is possible to access the original version of the method. To do so, we qualify the call to the method with the super reference. In other words, to access the original version of the method we call super.someMethod(). 4) Can a class be a parent of more than one subclass? Can a class be a child of more than one parent? Explain. Answer: A class can be the parent of more than one subclass in an inheritance hierarchy. Classes that have the same parent class are often called siblings. In Java, a class cannot be the child of more than one parent since Java does not support multiple inheritance. 5) Explain the relevance of the Object class to the Java programming language. Answer: Every class in Java is a subclass of the Object class. This occurs whether a class definition explicitly extends the Object class or not. Therefore, every class in Java has a common set of methods that are defined in the Object class. These include the toString method and the equals method. 6) What is an abstract class, and why might it be useful in an inheritance hierarchy? Answer: An abstract class is a class represents a partially defined concept in an inheritance hierarchy. Abstract methods cannot be instantiated, but they can be extended. They are often useful because several classes may include common functionality but may lack a fully defined parent concept. Abstract classes allow a programmer to implement the partially defined parent concept as an abstract class which will include the common functionality of the child classes. An example of an abstract concept in an inheritance hierarchy might be a Vehicle. Subclasses like Car, Boat and Airplane are more fully defined, but they share common states and behaviors. 7) Explain how a subclass can can access its parent classes private instance variables and methods. Answer: A subclass can access private instance variables and methods of its parent class, but only indirectly. There must be public methods that access the private data and methods directly. These public methods can then be called by the subclass, which gives indirect access to the private variables and methods of the parent class.

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 8 8) A programmer tries to create a subclass of String called MyString. When the programmer compiles her new class, the compiler produces the following message: MyString.java:1: cannot inherit from final java.lang.String public class MyString extends String { ^ 1 error Explain the cause of this error. Answer: The String class has been declared with the final modifier, which restricts any other classes from extending it. 9) Draw a hierarchy of Animals. The hierarchy should include the following entities: Animal, Reptile, Mammal, Bear, Human, Iguana, and Dolphin. Note that an Iguana is a Reptile, a Bear is a Mammal, a Human is a Mammal, and a Dolphin is a Mammal. Answer: / Reptile / Iguana

Animal \ Mammal / | \ Bear Human Dolphin

10) Consider a software system that will implement the following classes: Student, Professor, StaffMember, ContractWorker. List some common attributes of these classes. What would be a good abstract class from which these classes may be extended via inheritance? Answer: Some common attributes would be socialSecurityNumber, age, and address. A good abstract class from which these classes could be extended is Person. 11) Explain what it means for a child class to override a method in a parent class. Why might this be useful? Answer: A child class overrides a method that is inherited from a parent class by redefining it in the subclass. This is useful because a subclass may have a slightly different behavior than the superclass, but the behavior still has the same name. Overriding methods allows for this flexibility. 12) Why is it considered a good practice to override the toString and equals methods? Answer: These methods are defined in the Object class and are inherited by all classes. By overriding these methods, a programmer can define behavior that more closely matches the purpose of the class, rather than using the default behavior as defined in the Object class. 13) Describe the behavior of the toString method and the equals method of the Object class. Answer: The toString method returns a String representation of an object. The equals method returns true if the object is an alias of the object sent in as a parameter.

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 8 14) What does it mean for a class to be declared as final? What does it mean for a method to be declared as final? Answer: A method declared as final cannot be overridden by any subclass. A class declared as final can not be extended via inheritance. 15) What is a shadow variable? Answer: A shadow variable is a variable that is declared in a subclass that has the same name as a variable declared in the class's parent class.

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 9

Chapter 9: Polymorphism Multiple Choice Questions: 1) A polymorphic reference is one that can refer to _______________ type(s) of object(s). a) exactly one b) zero c) multiple d) abstract e) static Answer: c Explanation: A polymorphic reference can point to multiple types of objects at different points in time. 2) The commitment to execute certain code to carry out a method invocation is referred to as _________________. a) execution b) binding c) polymorphism d) inheritance e) none of the above Answer: b Explanation: Binding refers to the commitment to execute certain code to carry out a method invocation. 3) In Java, polymorphic method binding occurs ____________________ . a) at run time b) at compile time c) never d) when a programmer writes the code e) during the testing phase of software development Answer: a Explanation: polymorphic method binding occurs at run-time. 4) Late binding is _______________ than _______________ . a) more efficient, compile-time binding b) less efficient, compile-time binding c) more efficient, run-time binding d) less efficient, run-time binding e) Answer: b Explanation: Late binding is less efficient than compile-time binding due to the overhead associated with determining the code that should be executed at run time.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 9 5) Suppose that Horse is a subclass of Animal, and neither class is abstract. Which of the following is an invalid declaration and initialization? a) Horse h = new Horse(); b) Horse h = new Animal(); c) Animal a = new Animal(); d) Animal a = new Horse(); e) all of the above are valid Answer: b Explanation: Since Horse is a subclass of Animal, choice b would require an explicit cast in order to be valid. 6) In Java, a(n) ___________________ is a collection of constants and abstract methods. a) polymorphic reference b) abstract class c) implementation d) interface e) iterator Answer: d Explanation: An interface is a collection of constants and abstract methods. 7) In Java, polymorphic references can be created through the use of __________________ and ________________. a) inheritance, interfaces b) inheritance, abstract classes c) interfaces, abstract classes d) interfaces, iterators e) none of the above Answer: a Explanation: In Java, polymorphic references can be created through the use of inheritance and interfaces. 8) Let Dog be a subclass of Animal, and suppose Animal has a method called speak() that is overridden in the Dog class. Consider the following code. Animal spot = new Dog(); spot.speak(); Which of the following is true? a) This code will result in a compile-time error. b) This code will result in a run-time error. c) The speak method defined in the Animal class will be called. d) The speak method defined in the Dog class will be called. e) The speak method will not be called at all. Answer: d Explanation: The speak method defined in the Dog class will be called in this case. At run-time, the Java virtual machine determines that spot is pointing to an object of type Dog and binds the method to the methods defined in the Dog class. 2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 9

9) The Comparable interface contains which of the following methods? a) isGreaterThan b) isLessThan c) equals d) compareTo e) all of the above Answer: d Explanation: The Comparable interface contains exactly one method -- compareTo. 10) Let Object a be larger than Object b. What will the following method call return? a.compareTo(b) a) it will return 0 b) it will return a number greater than 0 c) it will return a number less than 0 d) it will return true e) it will return false Answer: b Explanation: The compareTo method returns an integer. If Object a is bigger than Object b, it will return a number greater than 0. If Object a is less than Object b, it will return a number less than 0. If they are equal it return 0. 11) Which of the following methods are included with any object that implements the Iterator interface? a) next b) hasNext c) toString d) all of the above e) a and b Answer: d Explanation: The Iterator interface specifies that all objects that implement it must have the hasNext and next methods. Since all objects in Java are a subclass of the Object class, it will also include the toString method. 12) You need to create a reference variable that can refer to objects from many different classes. You do not know the inheritance hierarchies of the classes. The safest class to use to declare the reference variable is a) Animal b) String c) Object d) Scanner e) File Answer: c Explanation: All classes are descendants of the Object class, so every object will have the Object class in its inheritance hierarchy. 3.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 9

13) Consider the following line of code. Comparable s = new String(); Which of the following statements is true about this line? a) It will result in a compile-time error. b) It will result in a run-time error. c) It will create a String object pointed to by a Comparable reference. d) Although it is perfectly valid Java, it should be avoided due to confusion. e) none of the above are true Answer: c Explanation: This is a valid Java statement and will result in no errors, since the String class implements the Comparable interface. 14) Suppose Animal is an interface that specifies a single method – speak. Now suppose the Dog class implements the Animal interface. In addition to the speak method, the Dog class also has a method called wagTail. Now consider the following code. Animal a = new Dog(); a.wagTail(); Which of the following is true about this code? a) It will result in a compile-time error. b) It will result in a run-time error. c) It will call the speak method defined in the Animal interface. d) It will call the wagTail method defined in the Dog class. e) none of the above are true. Answer: a Explanation: This code will result in a compile-time error since the Animal interface does not specify a wagTail method. This compile-time error can be avoided by explicitly casting a as a Dog when calling the wagTail method. 15) Which GUI concepts use polymorphism to establish their relationship? a) a listener and its associated component b) a radio button and its default selection c) a button and its label d) a slider and its tick marks e) none of the above Answer: a Explanation: Polymorphism is used to establish the relationship between a listener and its associated component.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 9

True/False Questions: 1) Consider a reference declared in the following manner. Animal a; This reference may only point to an object that created by instantiating the Animal class. Answer: False Explanation: This reference may point to an object of any type that is compatible with Animal. In particular, it may point to any object that is an instance of a class that is a subclass of Animal. 2) Let Animal be an interface. Then it is possible to create an object by instantiating the Animal interface. Answer: False Explanation: An interface cannot be instantiated. 3) The compareTo method of the Comparable interface returns a boolean value. Answer: False Explanation: The compareTo method returns an integer. 4) Compile-time binding is more efficient than dynamic binding Answer: True Explanation: Binding is the process of connecting method code to a method invocation/call. Compile-time binding occurs when the code is compiled. The connection is made once. Dynamic binding occurs when the program runs. For each call, the program must determine which code to use, and then execute the code. The need to determine the code to invoke for each call during program execution makes dynamic binding slightly less efficient than compile-time binding. 5) A parameter to a method can be polymorphic. Answer: True Explanation: A method can accept a polymorphic reference; this may give the method more flexibility than it would otherwise have. 6) An interface cannot declare any instance variables. Answer: True Explanation: An interface may declare constants, but it may not declare instance variables. 7) Establishing the relationship between a listener and the component it listens to is accomplished using polymorphism. Answer: True Explanation: The association between a component and its listener is performed by using the component’s addActionListener method. The parameter to addActionListener is a reference to an object of the ActionListener interface. The listener object must implement the ActionListener interface and provide a body for the performAction method, which the component invokes when an event occurs. 8) A reference variable can refer to an object of a child class, but not any further down the inheritance hierarchy. Answer: False Explanation: A reference variable can refer to an object of any class that is a descendent of the class of the reference variable.

5 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 9 9) Polymorphism via inheritance requires that all classes in the inheritance hierarchy are concrete. Answer: False Explanation: A reference variable can be declared at the level of an abstract class. Objects that it refers to must be instantiated from concrete classes. 10) An interface name may be used as a reference type. Answer: True Explanation: An interface name may be used a reference type in the same way that a class name may be used as a reference type. Like an abstract class, an interface cannot be instantiated, however.

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 9

Short Answer Questions: 1) What is polymorphism? Answer: A polymorphic reference is a single type of reference that can point to different types of objects at different times. Polymorphism refers to the fact that the method calls on polymorphic references are selected by the object type, not the reference type. This is often referred to as late binding. 2) How does inheritance relate to polymorphism in Java? Answer: Inheritance is one process by which polymorphic references are created. A reference to a type higher in an inheritance hierarchy can always refer to an object of a type lower in an inheritance hierarchy due to the is-a relationship. 3) Consider a class hierarchy that includes a class called Vehicle, with subclasses called Car and Airplane. The Vehicle class has a method called getMaxSpeed, which is overridden in the Car class. The getMaxSpeed of the Vehicle class returns 760 mph, while the getMaxSpeed method of the Car class is overridden to return 150 mph. What is the output of the following snippet of code? Explain your answer. Vehicle v = new Car(); System.out.println(v.getMaxSpeed() + “ mph”); Answer: The output of this code will be “150 mph”. Even though the reference is to the Vehicle class, the getMaxSpeed method is bound to the definition in the Car class, since the object is a car. This is due to the polymorphic nature of the reference. 4) Consider the following inheritance hierarchy that is used in a video game. Character / Friend / WiseMan

\ ShopKeeper

\ Villain / Dragon | FlyingDragon

\ Skeleton | EliteSkeleton

Which of the following declarations and initializations will not cause a compiler error? Character c = new FlyingDragon(); FlyingDragon f = new Character(); Dragon d = new Villain(); Villain v = new Skeleton(); Dragon d = new ShopKeeper(); Answer: The following are valid for this inheritance hierarchy because of the is-a relationship. Character c = new FlyingDragon(); Villain v = new Skeleton();

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 9 5) When a reference variable refers to an object that is in an inheritance hierarchy and a method of the object is invoked, how does Java determine which version of the method to use? Answer: Java determines the definition of the method that is closest to the object in the inheritance hierarchy between the reference variable and the object. 6) Are there any differences between extending a class and implementing an interface? Answer: Yes. First, extending a class uses the extends keyword, while implementing an interface uses the implements keyword. More importantly, a class can implement multiple interfaces, while it can only extend a single class. 7) Describe the compareTo method and the circumstances under which it returns different values. Answer: The compareTo method is specified by the Comparable interface. It places an ordering on objects. Consider the following call to compareTo: int result = obj1.compareTo(obj2); In this case result will be positive if obj1 is larger than obj2 in the sense of the ordering. It will be 0 if obj1 and obj2 are the same, and it will be negative if obj2 is larger than obj1. 8) Does polymorphism work if some of the classes in an inheritance hierarchy are abstract? Answer: Yes. A reference variable can be declared at any level in the inheritance hierarchy. If it is declared to be of an abstract class, it can still be used to refer to objects of concrete classes. 9) Can an interface hierarchy be used for polymorphism? Explain. Answer: Yes. A reference variable can use an interface as its type, and can then refer to objects of classes that implement the interface. In this way, polymorphism works the same as it does with an inheritance hierarchy. 10) Write an interface for a CD player. It should have the standard operations (i.e. play, stop, etc) that usual CD players have. Answer: public interface CDPlayer

{

public void play(); public void stop(); public void nextTrack(); public void previousTrack(); public void seekForward(); public void seekBackwards(); }

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 9 11) Give an example of a class that implements the Comparable interface, and explain how the implementation of the compareTo method determines its return value. Answer: The String class implements the Comparable interface. The comparison is based on the lexicographic ordering of String objects defined by the Unicode character set. 12) Is dynamic binding used when polymorphic references are made using interfaces? Answer: Yes. Java must use the type of the object to identify which method code to use for an invocation. This identification is done at execution-time, not at compile time, and is therefore considered dynamic binding. 13) Can a polymorphic reference invoke a method that is only declared at the object’s class level? If “yes”, explain how. Answer: In general, a polymorphic reference can only be used to invoke methods that are known to the class of the reference variable. In order to call a method that is declared at the object’s class level, the reference variable must be cast to be of the object’s type as part of the call. 14) Suppose you are implementing the comparable interface in a class representing a Person, where the ordering is based on the age of the person. Write a compareTo method for this class. You may assume that there is an instance variable called age and an accessor method called getAge. Answer: public int compareTo(Object o) { Person p = (Person) o; return this.getAge() - p.getAge(); } 15) Why can't an interface be instantiated? Answer: An interface cannot be instantiated because, similar to an abstract class, it only contains abstract methods.

9 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 10

Chapter 10: Exceptions Multiple Choice Questions: 1) A(n) _____________________ is an object that defines an unusual or erroneous situation that is typically recoverable. a) error b) exception c) interface d) try block e) catch block Answer: b Explanation: An exception is an object that represents an erroneous situation, and it is usually recoverable. 2) A(n) _____________________ is an object that defines an erroneous situation from which the program usually cannot recover. a) error b) exception c) interface d) try block e) catch block Answer: a Explanation: An error is similar to an exception in that it is an object that represents and erroneous situation, but it typically cannot be recovered from. 3) A(n) ____________________ can be used to find the exact line where an exception was thrown during program execution. a) interface b) call-stack trace c) try block d) catch block e) none of the above Answer: b Explanation: A call-stack indicates the exact line where an exception is thrown. 4) A(n) ____________________ is used to identify a block of statements that may cause an exception. a) call-stack trace b) error c) catch block d) try block e) none of the above Answer: d Explanation: A try block is used to identify a block of statements that can throw an exception.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 10 5)

A(n) ____________________ is used to specify how certain exceptions should be handled. a) finally block b) try block c) catch block d) error e) none of the above Answer: c Explanation: A catch block specifies the actions to be performed when a particular exception is thrown in a try block.

6) Every line of a(n) __________________ is executed no matter what exceptions are thrown. a) try block b) call stack trace c) catch block d) interface e) finally block Answer: e Explanation: Every line of a finally block is always executed, even if exceptions are thrown and caught. 7) If an exception is not caught, a program will __________________________ . a) not compile b) terminate abnormally c) print a message and continue executing d) all of the above e) neither a, b nor c Answer: b Explanation: A program will terminate abnormally if an exception is thrown and not handled by a catch block. 8) The Exception class and the Error class are subclasses of the ___________________ class. a) Throwable b) Catchable c) RuntimeProblem d) CompilerProblem e) none of the above Answer: a Explanation: The Throwable class is the parent class of the Error and Exception classes.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 10 9) ____________ is the process of catching an exception in the chain of method calls from the method where the exception occurred up to the main method. a) Error handling b) Exception handling c) Exception propagation d) Catch block nesting e) Finally block nesting Answer: c Explanation: The statement defines the process of exception propagation. 10) A(n) ________________ is an ordered sequence of bytes. a) exception b) error c) input-output flow d) stream e) none of the above Answer: d Explanation: A stream is an ordered sequence of bytes. 11) Which of the following represents the standard input stream? a) System.in b) System.out c) System.err d) System.instream e) System.outstream Answer: a Explanation: The standard input stream is represented by System.in. 12) Which of the following file streams should be explicitly closed to ensure that written data is properly retained? a) output b) input c) error d) writable e) readable Answer: a Explanation: Output file streams should be explicitly closed using the close method so that all data is properly retained.

3 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 10 13) Which of the following exception types must always be caught unless they are contained in methods that throw them in the method header? a) file stream b) IO c) checked d) unchecked e) none of the above Answer: c Explanation: Checked exceptions must always be caught or thrown, or else a compiler error will be generated. 14) Which of the following exceptions are unchecked? a) RuntimeException b) IllegalAccessException c) NoSuchMethodException d) ClassNotFoundException e) none of the above Answer: a Explanation: All subclasses of the RuntimeException class are unchecked. 15) Which of the following methods are part of the Exception class and can be used to give information about a thrown exception? a) getInfo b) printInfo c) printStackTrace d) getStackTrace e) none of the above Answer: c Explanation: The printStackTrace method can be used to give more information about a thrown exception.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 10

True/False Questions: 1) Files that are open for output from a program must be explicitly closed in the program. Answer: True Explanation: Output files must be closed before a program ends to ensure that all of the expected output is in the file. 2) Unchecked exceptions must be caught or propogated, or a program will not compile. Answer: False Explanation: Checked exceptions must be caught or propogated. Unchecked exceptions do not have to be caught. 3) A finally clause is always required in a try-catch block. Answer: False Explanation: A finally clause is optional. 4) Attempting to divide by zero will result in an Error being thrown, not an Exception. Answer: False Explanation: Attempting to divide by zero will result in an ArithmeticException being thrown. An Error is typically reserved for more serious, unrecoverable problems in a program. 5) Every line in a catch block is guaranteed to be executed in all situations. Answer: False Explanation: A catch block may not be executed at all. It is only executed when an exception is thrown. All lines in a finally block are guaranteed to be executed. 6) An exception will be propagated until it is caught and handled or until it is passed out of the main method. Answer: True Explanation: If an exception is not caught and handled, it will be propagated until it is passed out of the main method. 7) A throw statement is used to begin exception propagation. Answer: True Explanation: A throw statement begins the propagation of an exception. 8) The getMessage method of the Exception class prints out the stack trace, which helps the user to track down the source of the exception. Answer: False Explanation: The printStackTrace method prints out the stack trace. 9) When accessing an element of an array, if the index is outside of the range of the indexes of the array, an exception is thrown. Answer: True Explanation: This is a situation where an ArrayIndexOutOfBoundsException will be thrown. 10) In practice, it is important to catch all exceptions that might be thrown by a program. Answer: False Explanation: It is important for the programmer to consider the possible exceptions and to determine which exceptions are important to handle for a given application.

5 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 10

Short Answer Questions: 1) What is a try block? Answer: A try block is a block of statements that may throw an exception. 2) What is a catch clause? Answer: The catch clause is the part of the try statement that catches an exception that may be thrown in the try block. 3) How is a finally clause different from a try block and a catch clause? Answer: In a finally clause, every statement is guaranteed to be executed, whereas every statement in a try block or a catch clause may not be executed. 4) What is the difference between a checked exception and an unchecked exception? Answer: If a program includes a method call that may throw a checked exception, it is required to either explicitly catch it or throw it in order for the program to compile. An unchecked exception may be caught, but it does not require explicit handling for the program to compile. 5) How are input and output streams similar? How are they different? Answer: The similarity is that they are both streams, which are ordered sequences of bytes of data. They differ in their purpose: input streams are meant to be used by a program for input, that is, as a source of data. Output streams are meant to be used by a program for output, that is, to hold some part of the results that were computed in the program. 6) Consider the following code fragment. int [] a = new int[50]; a[50] = 100; Will this code fragment throw an exception? Explain. Answer: This code will throw an ArrayIndexOutOfBoundsException since the indexes of a run from 0 to 49, and this code fragment tries to access index 50.

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 10 7) Write a short snippet of code that converts the first element of the String[] args array to an integer. It should catch an exception and print out a message if the first element cannot be converted to an integer. Answer: int number; try

{ number = Integer.parseInt(number);

} catch(NumberFormatException nfe) { System.out.println("The first argument to the command line" + " is not an integer; try again."); System.exit(0); } 8) Give two examples of methods in the Exception class that can be used to output information about the Exception. Answer: The printStackTrace and the getMessage methods can be used to output information about a particular Exception object. 9) Is an exception an object? Explain. Answer: Yes, an exception is an object in Java. It is defined by a class, which is a subclass of the Object class. Therefore, it has all of the features of every other object type in Java. 10) What is exception prorogation, and how does it work in Java? Answer: If an exception is not caught by the method in which it is thrown, it will be thrown to the method which called that method. If it is not handled there, it will be thrown to the method that called that method, and so on. This is called exception propagation. An exception will be propagated until it is caught and handled or until it is passed out of the main method. This will cause the program to terminate and print a message about the exception. 11) Is the Exception class a subclass of the Error class? Explain. Answer: No, the Exception class is not a subclass of the Error class, because there is no is-a relationship between them. They are actually siblings in an inheritance hierarchy. They are both subclasses of the Throwable class. 12) How must IOExceptions be addressed in a program? Answer: IOExceptions must either be caught, or the methods in the propagation sequence must all contain throws IOException in their headers. 13) What are the standard I/O streams? Answer: In Java, the standard I/O streams are System.in, System.out, and System.err. 14) How does a method throw an exception? Answer: A method throws an exception by using the throw statement.

7.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 10 15) Write a code fragment that will throw an ArithmeticException. Your code fragment should not use the throw statement. Answer: int zero = 0; int num = 5; int result = num/zero; System.out.println(result);

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 11

Chapter 11: Analysis of Algorithms Multiple Choice Questions: 1) _____________________ is one of the most important computer resources a) The size of the computer monitor b) The number of disk drives that a computer has c) The CPU time needed by a running program d) A wireless keyboard e) A wireless mouse Answer: c Explanation: Choices a), b), d), and e) all refer to physical hardware components. CPU time is a measure of the efficiency of a program. Programs that use less CPU time are considered more efficient because more programs can be executed in a given amount of time. 2) A library employee takes 45 seconds to process a returned item. One morning there were 30 items in the book return bin. How long did it take the employee to process all of the returned items? a) 22 ½ minutes b) 30 minutes c) 45 minutes d) 135 minutes e) 1350 minutes Answer: a Explanation: One item takes 45 seconds to process. 30 items take 30 x 45 = 1350 seconds to process. 1350 seconds is 22 minutes and 30 seconds, or 22 ½ minutes. 3) A growth function that is O(n) is ____________________ a) constant b) logarithmic c) linear d) quadratic e) exponential Answer: c Explanation: O(n) is linear order. O(1) is constant order, O(𝑛2 ) is quadratic order, and O(2𝑛 ) is exponential order.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 11 4) When evaluating an algorithm, which of the following most likely contributes to the efficiency of the algorithm? a) The number of comparisons made to process each item b) The name of the input file c) The number of primitive variables in the program d) The number of arrays in the program e) All of these are likely to contribute to the efficiency of the algorithm Answer: a Explanation: Comparing values uses CPU time. An algorithm that performs fewer comparisons to process an item is likely to be more efficient. The other choices are less likely to have an impact on the efficiency of an algorithm. 5)

Big – Oh notation establishes a(n) ____________ on a growth function a) lower bound b) upper bound c) average (or mean) bound d) both a) and b) e) all of a), b), and c)

Answer: b Explanation: The symbol omega (Ω) refers to a lower-bound function. Theta (Θ) refers to a function that establishes both an upper and a lower bound. Big-Oh notation, O( ), refers to an upper bound on a growth function. 6) An algorithm has liner time complexity and can process an input of size n in a certain amount of time. If the algorithm runs on a computer that has a processor that is 5 times as fast, how large of an input can be processed in the same amount of time? a) n + 5 b) 5n c) n / 5 d) 𝑛5 e) 5𝑛 Answer: b Explanation: The algorithm is O(n). A process that is 5 times as fast can process 5 times as many items in the same amount of time. 7) Which of the following complexity measures is the most efficient? a) O(2𝑛 ) b) O(𝑛2 ) c) O(n log n) d) O(n) e) O(1) Answer: e Explanation: An algorithm whose complexity measure is O(1) runs in constant time. Its execution time is unaffected by the size of the input. No other measure in the list has this property, so no other measure will be more efficient.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 11 8) We need to examine _______________ when evaluating the order of an algorithm. a) loops b) nested loops c) method calls d) all of a), b), and c) e) none of these is correct Answer: d Explanation: Loops, nested loops, and method calls all may contribute to the asymptotic complexity of an algorithm. 9) Suppose that a loop executes n times. The loop contains a method call whose order is O(𝑛2 ), and some other statements that are O(1). From a complexity standpoint, the order of the loop is a) n b) 𝑛2 c) 𝑛3 d) (𝑛2 )𝑛 2 e) (𝑛)𝑛 Answer: c Explanation: Each execution of the loop body is O(𝑛2 ). The loop executes n times, so its order is 𝑛(𝑛2 ) = 𝑛3 . 10) A loop body is controlled by the following statement: for (int count = 2; count <= n; count +=2) If the statements in the body of the loop are all O(1), what is the order of the loop? a) O(1/2) b) O(1) c) O(n) d) O(𝑛2 ) e) O(2𝑛 ) Answer: c Explanation: The loop executes n / 2 times, which is considered to be O(n).

3 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 11

True/False Questions: 1) A program is more efficient if it uses more CPU time Answer: False Explanation: When comparing two programs, the program that uses less CPU time is the more efficient one. 2) One of the ways to express the size of a problem is in terms of the number of items to be processed. Answer: True Explanation: When defining the size of a problem, we must consider those aspects of the problem that contribute to the amount of time that it takes to complete the task. Size could be determined by the number of items to process, by the number of miles to travel, by the number of items to produce, etc. 3) If the growth function for an algorithm is expressed as a polynomial, then the asymptotic complexity of the algorithm is determined by the term with the smallest exponent of the variable. Answer: False Explanation: The asymptotic complexity is determined by the dominant term, which is generally the term with the largest exponent of the variable. This is the term whose value dominates the value of the polynomial for sufficiently large values of the variable. 4) The asymptotic complexity of an algorithm is also called the order of the algorithm. Answer: True Explanation: Asymptotic complexity and order are synonymous terms for the purposes of this chapter. 5) All of the terms in a growth function contribute to the order of the function Answer: False Explanation: The dominant term of a growth function determines the order. The non-dominant terms are ignored when determining the order. 6) A growth function shows the relationship between the size of a problem and the part of an algorithm that we are trying to optimize. Answer: True Explanation: This is the definition of a growth function. 7) When comparing two growth functions, a larger exponent on the problem size in the growth function indicates greater efficiency. Answer: False Explanation: A larger exponent indicates that an algorithm will require more time to execute, not less, when compared to an algorithm with a smaller exponent. 8) If the problem size is fairly small, then there is little difference between the efficiencies of different algorithms. Answer: True Explanation: For sufficiently small problem size, there is little difference between O(n), O(n log n), O(𝑛2 ), and O(2𝑛 ). 9) When determining the complexity of a segment of code, simple print statements are generally O(1). Answer: True Explanation: A print statement that displays a text message or the contents of a variable runs in constant time. The problem size has no impact on the amount of time that it takes to execute the statement.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 11 10) When evaluating the complexity of a loop, all statements in the loop body are considered to be O(1). Answer: False Explanation: If the loop contains a method call, then the complexity of the body of the method must be evaluated. If the loop contains another loop, then the complexity of the inner loop must be evaluated. Both nested loops and method calls will most likely not be O(1).

5 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 11

Short Answer Questions: 1) Why is the efficiency of an algorithm important? Answer: Efficient algorithms allow us to better use computer resources. An inefficient algorithm takes longer to execute, which means that fewer programs can run in a given amount of time. 2) There are two algorithms that perform a particular task. Algorithm 1 has a complexity function 𝑓(𝑛) = 2𝑛 + 248. Algorithm 2 has a complexity function 𝑔(𝑛) = 𝑛2 + 16. Which algorithm is more efficient when n = 5? Which is more efficient when n = 20? Answer: When n = 5, 𝑓(5) = 2(5) + 248 = 10 + 248 = 258. 𝑔(5) = 52 + 16 = 25 + 16 = 41. Algorithm 2 is more efficient when n = 5. When n = 20, 𝑓(20) = 2(20) + 248 = 40 + 248 = 288. 𝑔(20) = 202 + 16 = 400 + 16 = 416. Algorithm 1 is more efficient when n = 20. 3) What is a growth function? How does it relate to the efficiency of an algorithm? Answer: A growth function is a function that shows the relationship between the size of a problem and an aspect of an algorithm that we are trying to optimize. It is a measure of the complexity of the algorithm. A more complex algorithm is a less efficient algorithm. 4) Which is more efficient, an O(𝑛2 ) algorithm or an O(2𝑛 ) algorithm? 10

2

Answer: O(𝑛2 ) is more efficient for n > 4. When n = 5, 52 = 25, while 25 = 32. When n = 10, 102 = 100, while = 1024.

5) What term or terms of a growth function are considered when determining the order of an algorithm? Answer: The dominant term of the growth function determines the order of the algorithm. The dominant term is the term that contributes the most to the value of the function as n becomes large. 6) Why are faster computer processors not an adequate solution for inefficient algorithms? Answer: Faster computer processors can provide a small improvement in execution time, but as the size of the problem increases, an inefficient algorithm will still take more CPU time to execute than an efficient algorithm. 7) What parts of the code of an algorithm contribute to its complexity? Answer: Loops, nested loops, and calls to methods all contribute to the complexity of an algorithm.

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 11 8) What is the time complexity for the following segment of code? for (int factor1 = 1; factor1 <= n; factor1++) { for (factor2 = 1; factor2 < n; factor2++) System.out.print(factor1*factor2 + " "); System.out.println(); } Answer: The complexity of each loop is O(n). Since the inner loop executes n times for each single execution of the outer loop, the complexity is 𝑂(𝑛 × 𝑛) = 𝑂(𝑛2 ).

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 12

Chapter 12: Introduction to Collections - Stacks Multiple Choice Questions: 1) A stack is a ___________________ data structure. a) LIFO b) FIFO c) link based d) array based e) none of the above Answer: a Explanation: A stack is a LIFO (last in, first out) data structure. This means that the last element to be put on the stack will be the first element that is removed. 2) Which of the following is not an operation on a stack? a) push b) pop c) peek d) dequeue e) all of the above are operations on a stack Answer: d Explanation: The dequeue operation is a queue operation, not a stack operation. 3) Which of the following is not a valid postfix expression? a) 5 4 + b) 6 5 4 + c) 4 + 5 d) 8 2 + 2 / e) all of the above are valid postfix expressions Answer: c Explanation: Choice c is in infix notation, not postfix. 4) What is the result of evaluating the following postfix expression: 4 8 + 2 * a) 40 b) 24 c) 64 d) 20 e) none of the above are correct Answer: b Explanation: Converting this postfix expression to infix notation yields the following expression: (4+8) * 2. This is equal to 24.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 12 5) What exception is thrown if the pop method is called on an empty stack, implemented using the ArrayStack class? a) EmptyStackException b) NoSuchElementException c) ArrayOutOfBoundsException d) EmptyCollectionException e) none of the above Answer: d Explanation: If a pop method is called on an empty stack, the EmptyCollectionException is thrown. 6) Which of the following methods inserts an element into a stack data structure? a) enqueue b) dequeue c) push d) pop e) peek Answer: c Explanation: The push method inserts an element into a stack. 7) A stack is the ideal collection to use when _______________________ . a) implementing a radix sort b) evaluating a postfix expression c) modeling customers standing in line at the checkout of a grocery store d) finding the largest number in an array e) none of the above Answer: b Explanation: A postfix expression can be easily evaluated using a stack. 8) A(n) ______ is an object that gathers and organizes other objects. a) abstraction b) collection c) exception d) algorithm e) none of the above Answer: b Explanation: A collection is an object that gathers and organizes other objects.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 12 9) In Java, type compatibility is enforced by _____________. a) compile-time type checking b) convention c) an Enforcer object d) an exception e) Java does not enforce type compatibility Answer: a Explanation: Java provides compile-time type checking with some classes to detect statements that have invalid type compatibility. 10) Java uses ________ to allow us to define a class and not specify the type of the objects that the class employs until the class is instantiated. a) exceptions b) widgets c) inheritance d) interfaces e) generic types Answer: e Explanation: A generic type is represented in the class definition by a letter in angle brackets, e.g., <T>. When the class is instantiated, T is replaced by the name of the class that will be used by the object. 11) Which of the following stack operations is not likely to cause an exception to be thrown? a) adding an item to the stack when the stack is full b) adding an item that has the same value as one that is already in the stack c) removing an item when the stack is empty d) all of a), b), and c) e) All of these are likely to cause an exception to be thrown Answer: b Explanation: The items in a stack are distinct. There is no problem if two stack items have the same value. Whether an exception is thrown for choice a) depends on the implementation of the underlying data structure that supports the stack. Choice c) should always throw an exception. 12) A Stack interface is defined and has an isEmpty() abstract method. What should this method return? a) an int representing the number of items in the stack b) a double representing the average of the values of the items in the stack c) a String representing the contents of the items in the stack. d) a boolean value representing whether the stack is empty or not. e) the item that is at the top of the stack Answer: d Explanation: isEmpty() returns true if the stack is empty and false if it is not empty. Choice c) may be implemented as a toString() method. Choice a) is better referred to as a size() method. Choice e) is a peek() method.

3 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 12 13) Which of the following situations could be implemented using a Stack? a) cars waiting to pay and exit a parking garage b) people who have appointments in the reception area of a doctor’s office c) students passing through the serving line in a cafeteria d) a person who wants to un-do several changes that were made to the document that she is editing. e) none of the above Answer: d Explanation:. The un-do operation can be modeled using a stack. Each edit action pushes something onto a stack that represents what was done – add words, replace words, change formatting, etc. The un-do operation will reverse the effects of these changes in the reverse order in which they were made, which can be viewed as a series of pop operations. Choices a) and c) are better implemented using a queue. 14) In an array implementation of a stack, we can include code that will automatically allocate more memory if every element of the array is occupied. Which stack operation should invoke this code? a) push b) pop c) peek d) poke e) none of the above Answer: a Explanation: The push operation will fail if the array is at capacity. The implementation of push should check to see if the stack is full and invoke the code that allocates more memory before it stores the new element in the stack. The pop operation removes and returns an element from the stack, so it will not be affected if the stack is full. The peek operation does not modify the stack contents and will be unaffected if the stack is full. 15) The peek operation of a stack is a) O(1) b) O(n) c) O(𝑛2 ) d) O(n log n) e) none of the above Answer: a Explanation: Peek checks to see if the stack is empty, and if not, returns a reference to the element at the top of the array. Its execution time is not affected by the size of the problem or the number of elements in the stack. It is constant order.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 12

True/False Questions: 1) A postfix expression can be easily evaluated using a stack. Answer: True Explanation: A postfix expression can be easily expressed using a stack. See the example in the text. 2) A stack is a LIFO structure. Answer: True Explanation: A stack is a LIFO structure, meaning that the last element that is inserted is the first element that is removed. LIFO stands for last-in-first-out. 3) The peek operation on a stack returns a reference to the element at the bottom of the stack. Answer: False Explanation: The peek operation returns a reference to the element at the top of the stack. 4) An abstract datatype is a data type that is not known to the programmer Answer: False Explanation: An abstract data type is a data type whose values and operations are not inherently part of the programming language. It is abstract in that its implementation details should be hidden from the user. A user interacts with the abstract data type through its interface, without knowing the details of how the abstract data type is implemented. 5) Creating a data structure that holds Objects makes a lot of sense, since all objects inherit from the Object class. Answer: False Explanation: While inheritance and polymorphism can be used to implement such a stack, basing the stack on the Object class does not enforce inheritance hierarchies or compile-time type checking. Such an implementation also limits you to use the small set of methods that are defined in the Object class to access the objects in the stack. 6) The postfix expression 5 3 * 2 5 + - 4 * 2 / evaluates to 16 Answer: True. Explanation: The infix expression that corresponds to this expression is (5 * 3 – (2 + 5)) * 4 / 2. Using the order of operations, the expression evaluates to 16. 7) An exception should be thrown if an attempt is made to pop an item from an empty stack. Answer: True Explanation: Attempting to pop an item when the stack is empty is a problem with the way that a program is designed, not a problem with the implementation of the stack. The implementation of the stack should throw an exception and the program should detect and respond to the exception. 8) The peek operation can retrieve a value from anywhere in the stack. Answer: False Explanation: The peek operation can only return the value that is at the top of the stack. It does not have access to any other values on the stack. 9) An array-based implementation of a stack can be designed so that all stack operations are O(1). Answer: True Explanation: If the bottom of the stack is at index 0, then pop and peek are both O(1), since they only have to access the top element of the stack. Push is O(1), even with occasional calls to code to allocate more memory for the stack. 10) The isEmpty() method determines if the store of extra memory for use by the stack is empty. Answer: False Explanation: isEmpty() is used to determine if the stack is empty. It returns true or false.

5.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 12

Short Answer Questions: 1) In an array-based implementation of a stack, which end of the contents of the array represents the bottom of the stack and why? Answer: A stack is implemented as an array with the bottom of the stack represented by index 0 of the array. This is for efficiency – if index 0 were the top, whenever an element is removed the entire contents of the array would have to be shifted down, which would require too much time. 2) Suppose the following sequence of elements are pushed onto a stack named myStack in the following order: 50, 26, 32, 18, 26, 51. What is the output of the following code? for (int count = 1; count <=3; count++) System.out.println(myStack.pop() ); Answer: The pop operations of the stack will result in displaying 51, 26 and 18, in that order, each on a separate line. 3) Write out the order of elements that are contained in a stack after the following operations are performed. myStack.push(new Integer(8)); myStack.push(new Integer(6)); Integer num1 = myStack.pop(); myStack.push(new Integer(3)); myStack.push(new Integer(4)); myStack.push(new Integer(15)); myStack.push(new Integer(12)); myStack.push(new Integer(9)); myStack.pop(); myStack.pop(); myStack.pop(); myStack.push(new Integer(19)); Answer: The resulting stack (from bottom to top) is: 8, 3, 4, 19. 4) Write a push method for a stack implemented with an array. You may assume that the stack is referenced by an array named stack, and that there is an integer variable named count that keeps track of the number of elements in the stack. You may not assume that you have access to an expandCapacity method, nor should your code throw an exception if the stack is full. Your method should include code to expand the capacity of the array if it is full. Answer: public void push(T element) { if(count == stack.length) { T[] newStack = new T[stack.length*2]; for(int i = 0; i < stack.length; i++) newStack[i] = stack[i]; stack = newStack; } stack[count++] = element; }

6.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 12

5) List the five basic operations on a stack. You may assume that there is an integer variable named Answer: The five basic operations on a stack are push, pop, peek, isEmpty, and size. 6) Write an isEmpty method for a stack implemented with an array. You may assume that there is an integer variable named count that keeps track of the number of elements in the stack. Answer: public boolean isEmpty() { return (count == 0); } 7) A collection is an object. A collection is also an abstraction. Explain how these two sentences can both be true. Answer: A collection is an object that is used to gather and organize other objects. Since it is an object, it has instance data and member methods. The instance data and member methods together define what the collection is and how the collection works. As an object, a collection is an abstraction, in that users interact with it through its interface, its public methods, without having to know anything about its instance data or how the methods work. By using the collection’s interface, users do not have to know the internals of how the collection is implemented. 8) Java has existing collections that implements the stack data type. Why is it important to know how to implement our own stack data types? Answer: The existing stack data types may not support design decisions that are necessary for your application. By knowing how to write your own stack data type, you can customize it to meet your particular needs. It is also important to understand how the existing data types work, as this gives you in-depth understanding of some of the design issues that were faced and decisions that were made, both of which you may experience if you have to create your own stack data type. 9) Suppose NumberValue is class that uses a generic type: public class NumberValue<T> { ... } Write the declaration of a NumberValue object named num that will use Integer for its type. Answer: NumberValue<Integer> num = new NumberValue<Integer>(); 10) What should happen if a user attempts to pop an element from an empty stack? Answer: Popping an element from an empty stack is most likely a logic error in the user code. The responsibility of the stack data type is to let the user know that something isn’t right. The implementation of the stack data type should throw an exception from within the pop operation if the stack is empty. The user’s program should detect and process the exception.

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 12 11) What should a stack data type do if a push operation cannot succeed because there is no more room in the data structure to hold another item? Answer: One possibility is to throw an exception and let the user catch and respond to it. Another possibility is to add a return code to the push operation that will signal the user whether the push succeeded or not. A third possibility is to detect that the storage is full and to allocate more storage. All of these approaches have their advantages and disadvantages. 12) What benefit is gained by placing the bottom of the stack at array index 0 when designing an array-based stack data type? Answer: Placing the bottom at index 0 means that existing stack items do not have to move for push or pop operations. The implementation of push and pop can be O(1). If the top of the stack was at index 0 and all existing elements had to be moved to implement a push or a pop operation, then push and pop would become O(n), which is less efficient. 13) The pop operation should throw an exception if the stack is empty. What should the peek operation do if the stack is empty? Answer: The peek operation should probably also throw an exception. The user code is expecting that both pop and peek will return the object at the top of the stack. If neither operation can succeed due to their being no object at the top of the stack, then both operations should throw an exception. 14) How should the constructor for an array-based stack data type be designed to support user choice for stack size? Answer: There should be two constructors, one that takes no parameters and one that takes a parameter that indicates the initial array size. The one that takes no parameter should declare an array with a default size, while the constructor that takes a parameter should use the parameter to declare an array with the desired size. 15) How are Javadoc comments useful in documenting code? Answer: Javadoc comments follow a specific format and have predefined contents. They can be read by the javadoc tool, which is used to generate class documentation in HTML format. Consistent use of javadoc-style comments in code can make the code easier for a novice reader to understand.

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 13

Chapter 13: Linked Structures - Stacks Multiple Choice Questions: 1) In an ideal implementation of a stack, all operations are ______________________ . a) O(1) b) O(n) c) O(n log n) d) O(n2) e) it depends on the operation Answer: a Explanation: In a good implementation of a stack, all operations require a constant amount of time. 2) A(n) _____________________ is a data structure that uses object reference variables to create links between objects. a) link structure b) exception structure c) interface d) stack e) array-based data structure for a stack Answer: a Explanation:. A link structure is a data structure that uses object reference variables to create links between objects. 3) A(n) ____________________ is another way to refer to an object reference variable. a) referer b) pointer c) stack collection d) primitive variable e) instantiated object Answer: b Explanation: A pointer is another way to refer to an object reference variable. An object reference variable holds the address, or the location, of an object. It’s not important to know where the location is, but it is important to know that the object reference variable holds the location. We say that the object reference variable “points to” the object, hence the name pointer. 4) A self-referential object is an object that a) is its own parent class b) is its own child class c) has a pointer to itself d) has a pointer to another object of the same type e) none of these is correct Answer: d Explanation: A self-referential object is an object that contains a pointer to another object of the same type. It is the building block of a linked list. 1.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 13

5)

A linked list can hold ______ nodes a) 10 b) 100 c) 1000 d) a number specified when the linked list is instantiated. e) any number of

Answer: e Explanation: A linked list is a dynamic data structure. Its size grows and shrinks as needed by the program. It does not have a predefined upper bound on its capacity, though it may be limited by the available memory in the computer. 6) The pointer to the first element in a linked list a) can be used to traverse the list b) can be modified in any way necessary c) should only be modified by the code that adds nodes to the list and deletes nodes from the list d) is optional e) is inefficient Answer: c Explanation: The pointer to the first element in the list is the only way that the program has to access the list. If you traverse the list with it, then your program no longer knows where the first element of the list is. If you otherwise modify it, you may also lose access to the list. It should only be modified (used as the target of an assignment statement) by the code that insesrts nodes into the list and by the code that removes nodes from the list. 7) Creating a separate node class that holds a reference to another node and a reference to an object that is being stored in a list is a good design because it a) makes the code more complicated b) hides the implementation details of a collection c) reduces code reuse d) all of the above e) neither a, b nor c Answer: b Explanation: The definition of an object in a collection should contain just the information that the object needs for its purposes. The implementation of the collection that contains the object is not part of the object. Creating a node class that refers to the object allows the object to exist independent of the implementation details of the linked list.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 13 8) Java provides two Collections classes that can be used to implement stacks. They are ______ and _____. a) the Stack class, the LinkedList class b) one-dimensional arrays, multidimensional arrays c) Exceptions, Errors d) data structures, list structures e) none of the above Answer: a Explanation: The Stack class and the LinkedList class can both be used to implement stacks. The Stack class uses an array-based implementation. The LinkedList class implements the Deque interface and provides a linked-list implementation. 9) An activation record represents a) which students are currently logged in to a campus computer b) which students are enrolled and actively pursuing a degree c) a method that was called and has not yet completed its execution d) a method that terminates due to an exception e) both a) and b) Answer: c Explanation: An activation record is created and put on the program stack when a method is invoked. It contains some administrative data and the local variables and parameters for this invocation of the method. When the method terminates, its activation record is removed (popped) from the program stack. 10) Recursion occurs when a) a program never ends b) a program terminates abnormally c) a program ends normally d) a method calls itself e) none of the above Answer: d Explanation: Recursion occurs when a method makes a call to itself. The method may call itself directly, or it may make a call to itself through calls to other methods. 11) Which of the stack operations must be supported in a linked list implementation? a) push and pop b) push and peek c) pop and peek d) push, pop, and isEmpty e) all of them Answer: e Explanation: An implementation of a stack must support all stack operations: push, pop, peek, isEmpty, and size

3 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 13 12) The constructor for a stack implemented using a linked list creates space for how many elements? a) 0 b) 10 c) 100 d) 1000 e) whatever number the programmer specified when the linked list was instantiated. Answer: a Explanation: A linked list is a dynamic data structure. Nodes in a linked list are created as elements are added. The linked list initially has 0 elements in it. 13) The push operation of a stack implemented using a linked list is O(1) when a) the stack is empty b) the stack is full c) the top of the stack is at the front of the linked list d) the top of the stack is at the end of the linked list e) none of the above Answer: c Explanation:. If the top of the stack is at the front of the linked list, then the push operation simply creates a node and populates it, sets the node’s pointer field to point to the top of the list, sets the pointer to the top of the list to point to this new node, and increments the counter of the number of elements in the stack. Each of these operations is O(1) and executes independent of the number of elements in the stack. Thus, the push operation is O(1) when the top of the stack is at the front of the linked list. 14) Which of the following is not part of the pop operation for a stack implemented using a linked list?

the stack

a) determine if the stack is full b) determine if the stack is empty c) declare a temporary reference variable and set it to point to the element at the top of the stack d) adjust the top reference variable to point to the node pointed to by the next field of the node at the top of e) all of these are part of the pop operation for a stack implemented using a linked list

Answer: a Explanation: A pop operation, using either an array implementation or a linked-list implementation, is not impacted if a stack is full. Pop reduces the size of a stack. Additionally, a stack implemented using a linked list can effectively never be full. 15) Traversing a linked list is a) the process of deleting the list b) the process of visiting every node for some purpose c) the process of removing every node, one at a time d) the process of creating a new linked list with twice the capacity e) none of the above Answer: b Explanation: Traversing a linked list is the process of visiting every node in the list. The toString method needs to visit every node to produce its return value.

4.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 13

True/False Questions: 1) It is only possible to implement a stack using a linked structure. Answer: False Explanation: A stack can be implemented using a linked structure or an array-based structure. 2) In a linked implementation of a stack, a pushed element should be added to the end of the list. Answer: False Explanation: In a linked implementation of a stack, a pushed element should be added to the front of the list. If the element is added to the end of the list, both the push and the pop operations would require linear time, because we would need to go through the entire linked list to get a pointer to the next-to-last element in the list. 3) When an object contains an instance field that is a reference to another object of the same type, we say that the object is selfidentifying Answer: False Explanation: The sentence describes a property that is called self-referential. 4) A linked list is a linear ordering of objects in which an object has a reference to the next object in the list Answer: True Explanation: Each object in the linked list, except the last one, refers to another object in the linked list. The last object in the linked list does not refer to another object. 5) An object can only contain one field that is a reference to another object of the same type. Answer: False Explanation: An object can have any number of fields that refer to other objects of the same type. There are many different types of data structures that can be implemented using such fields in objects. 6) When working with a linked list, the first element of the list must be treated in a different way than the other elements. Answer: True Explanation: Linked lists have a special variable that references the first element of a list. When performing operations on a linked list, such as adding or removing elements, care must be taken so that this variable continues to reference the first element of the list. 7) In a doubly linked list, each element has a reference to the element that immediately precedes it in the list and the element that immediately follows it in the list. Answer: True Explanation: Objects in a doubly linked list have references to two other elements of the same type. One reference is used to point to the preceding element in the list, while the other reference is used to point to the following element in the list. 8) In the linked list implementation of a stack, capacity represents the number of elements for which space is allocated when the list is instantiated. Answer: False Explanation: Capacity is needed in an array-based implementation of a stack, since an array cannot be declared without stating the number of elements that it will have. In a linked list implementation, the stack is initially empty, and no space is allocated for elements. Capacity is not part of a linked list implementation of a stack.

5 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 13 9) Using the rear of the linked list as the top of the stack is the most efficient way to manage the stack. Answer: False Explanation: If the top of the stack is at the rear of the linked list, then push, pop, and peek operations will have to visit every element in the list in order to find the end of the list. This will take time to execute that is proportional to the number of elements in the stack. If the top of the stack is instead at the front of the linked list, then push, pop, and peek need only access the element that is at the top of the list, and the size of the stack does not impact the execution time. 10) When working with a linked list implementation of a stack, the push operation should throw an exception if the stack is empty. Answer: False Explanation: There is no problem with adding an element to an empty linked list. The problems arise when trying to view or remove an element from an empty linked list, so the pop and peek operations are the ones that should throw an exception if appropriate.

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 13

Short Answer Questions: 1) What is wrong with the java.util.Stack implementation of a stack? Answer: The java.util.Stack class is derived from the Vector class, which gives to the stack operations that are not supposed to be supported by a stack data structure. For instance, it includes methods that allow elements contained within the stack to be accessed and modified. A stack is not supposed to have these abilities. 2) What is wrong with using the LinkedList class, which implements the Deque interface, to implement a stack? Answer: Like the java.util.Stack implementation, the Deque interface provides methods that are not actions that a stack should be able to do. 3) Write a push method for a stack implemented as a linked structure. You may assume that the implementation has the top element of the stack referenced by a LinearNode<T> reference top and that an integer variable count keeps track of the number of elements in the stack. Answer: public void push(T element) { LinearNode<T> newNode = new LinearNode<T>(element); newNode.setNext(top); top = newNode; count++; } 4) When working with a linked list, how do you determine the last element in the list? Answer: The last element in the list is the element that does not reference another element. Its reference field is set to null. 5) Is there a limit to the number of self-references that an object may have? Explain. Answer: No, there is no limit. Objects can be designed to have as many references to other objects of the same class as necessary for the purpose of the program. Multiple reference fields can give rise to complex linked structures. 6) A linked list is described as a dynamic structure. What does this mean? Answer: A dynamic structure is one whose size is not fixed. A linked list is dynamic. The number of elements in the list changes as elements are added or removed, so its size changes and is not fixed. 7) Consider the following sequence of steps to add a node to the front of a linked list: - Set the reference field to refer to the first node in the current list. - Set the reference to the front of the list to refer to the new node. Is the order of these steps important? Explain your answer. Answer: Yes, the order of these steps is important. If the order is reversed, that is, the second step is performed first, then any existing nodes in the list will be lost. The node that is being added must refer to the first node in the list before the reference to the list is reset. If the reference to the list is reset before the new node refers to the list, then there will be no reference to the rest of the list.

7.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 13

8) When working with a linked list implementation of a stack, what task must be performed by a pop operation that is not performed by a peek operation? Answer: pop and peek operations are similar in that they both return the element that is at the top of the stack. Additionally, the pop operation removes the element from the stack, whereas the peek operation does not modify the stack. 9) A linked list can be designed so that the nodes consist of just two reference variables. One refers to the element, while the other node is a self-reference for linked list purposes. What is the benefit of this design for a linked list? Answer: In this design, all of the information related to the object that is being managed in the linked list is captured in the element. The object does not have to have a reference to another object as an instance variable, and the object does not have to know that it is part of a linked structure. This supports the separation of the implementation of the linked list from the contents of the linked list. 10) A sentinel, or dummy, node can be used at the front of a linked list. What purpose does this serve? Answer: When adding and removing nodes from a linked list, the first node of the list is treated as a special case. This is because the list reference variable points to this node and will have to be adjusted if a node is added to or removed from the head. With the use of a dummy node, the reference to the top of the list will never change (it will always refer to the dummy node), so the operations of adding and removing nodes can be simplified. 11) A linked list implementation for a stack can be written using the LinkedList class, which implements the Deque interface. The Deque interface supports methods that are not part of a stack How can a programmer use the LinkedList class to implement a stack? Answer: A programmer can write the code to use only those methods that support the basic stack operations: push, pop, peek, isEmpty, and size. 12) What is the first task that a pop operation should perform? Answer: A pop operation should determine if there is an element to pop from the stack. If not, it should throw an exception. 13) Write a peek method for a stack implemented as a linked structure. You may assume that the implementation has the top element of the stack referenced by a LinearNode<T> reference top. Answer: public T peek() throws EmptyCollectionException { if (isEmpty() ) throw new EmptyCollectionException("stack"); T result = top.getElement(); return result; }

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 13 14) Explain how activation records and the program stack are used to manage the invocation of and return from methods. Answer: The program stack is a region of memory where activation records for methods are stored. Activation records contain the method’s local variables and parameters. Each invocation of a method has its own activation record. When the program begins executing, the activation record for the main method is put on the program stack. Whenever a method is called, its activation record is put on the stack and it begins to execute. A method’s activation record is removed from the program stack when the method terminates, at which time control is passed to the method that is now at the top of the program stack. 15) Someone tells you that a particular program uses recursion. What does this mean? Answer: A recursive program is one in which a method invokes (makes a call to) itself. The method may call itself directly, or it may call itself as part of a sequence of method calls, for example, A calls B, which calls C, which calls A.

9 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 14

Chapter 14: Queues Multiple Choice Questions: 1) Which of the following is not a queue operation? a) enqueue b) dequeue c) first d) isEmpty e) all of the above are queue operations Answer: e Explanation: All of the listed operations are queue operations. 2) Which of the following methods removes an element from a queue? a) enqueue b) dequeue c) first d) pop e) push Answer: b Explanation: The dequeue method removes an element from a queue. 3) A queue is a ____________________ data structure. a) LIFO b) FIFO c) link based d) array based e) none of the above Answer: b Explanation: A queue is a FIFO (first in, first out) data structure, meaning that the first element that is put into the queue is the first element to be removed from the queue. 4) In an ideal implementations of a queue, all operations are ______________________ . a) O(1) b) O(n) c) O(n log n) d) O(n2) e) it depends on the operation Answer: a Explanation: In an ideal implementation of a queue, all operations require a constant amount of time.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 14 5) In a array-based implementation of a queue that stores the front of the queue at index 0 in the array, the dequeue operation a) is impossible to implement b) has several special cases c) has order O(n) d) has order O(n2) e) none of the above Answer: c Explanation: It requires a linear amount of time to shift all of the elements of the queue down one array position after an element is removed. 6) The first operation of a queue is similar to the ______ operation of a stack a) push b) pop c) isEmpty d) size e) peek Answer: e Explanation: Both the peek operation of a stack and the first operation of a queue return the element that is at the front of the stack or the queue without removing the element from the stack or queue. 7) The queue operation that returns the element after the element at the front of the queue (that is, the second element in the queue) without removing the element at the front of the queue, is ________. a) dequeue b) dequeueNext c) bypass d) dequeueAndPeek e) none of these is correct Answer: e Explanation: Queue operations add elements one at a time at one end of the queue and remove elements one at a time from the other end. There is no operation that allows a user to access or remove an element that is not at the front of the queue. 8) Java provides the Queue _____ to create programs that use the queue data structure. a) class b) interface c) parent d) child e) interface Answer: b Explanation: Java provides an interface named Queue. The LinkedList class is one of the classes that implements this interface. Though the interface is named Queue, the methods in the interface do not use the names of the queue operations as described in the text. The Queue interface has several methods that are similar to the queue operations but that have slightly different behaviors.

2.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 14 9) One reason to define a Queue ADT (abstract data type) interface is a) to tightly couple the data in the queue elements with the implementation of the queue data structure b) to guide the programmer in how to implement the queue operations c) to separate the operations from the ways that the operations can be implemented d) both b) and c) are correct e) none of these is correct Answer: c Explanation: An interface defines behavior. It indicates what operations must be supported, and the expected inputs to and results of those operations. It does not define how those operations should be implemented. Choice a) is not correct because we generally want a loose connection between the information being managed and the management system. 10) Which of the following statements is generally true about a linked list implementation of a queue? a) Elements are added (enqueue) and removed (dequeue) at the front of the linked list. b) Elements are added and removed at the rear of the linked list. c) The first operation retrieves the element that was most recently added to the linked list. d) The linked list implementation of a queue maintains references to both ends, the front and the rear, of the linked list. e) All of the above statements are generally true about a linked list implementation of a queue. Answer: d Explanation: Elements are added at one end of the queue and removed from the other end of the queue. The most efficient way to do this is to maintain a reference to each end of the linked list that supports the queue. Choices a) and b) may be true of a stack but not a queue. 11) Which of the following are affected by an enqueue operation? a) the count of the number of elements in the queue b)the reference to the rear of the queue c) the reference to the front of the queue d) both a) and b) are true e) all of a), b), and c) are true Answer: d Explanation: Enqueue adds an element to the queue, so the count of the number of elements is increased. Elements are added at the rear of the queue, so the reference to the rear of the queue is adjusted to account for the new element. The front of the queue is unaffected by enqueue, so the reference to the front of the queue is unchanged. 12) Which of the following should be performed first in a dequeue operation? a) declare and initialize reference to the node to be removed from the queue b) adjust the reference to the front of the queue c) decrement the count of the number of elements in the queue d) determine if the queue is empty e) These steps can be performed in any order. Answer: d Explanation: If the queue is empty, an exception should be thrown. If the queue is not empty, then the other steps can be followed, but only after determining that there is an element to remove.

3.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 14 13) A circular array has 20 elements. The index (array subscript) ranges from 0 to 19. What is the subscript of the array element that follows the element with subscript 19? a) 20 b) 0 c) 1 d) 21 e) an exception will be thrown Answer: b Explanation: In a circular array, the end of the array wraps around and joins the beginning of the array. The subscript of the array element that follows the element with subscript 19 is 0, the first element in the array. 14) In a queue implemented using a circular array, rear refers to a) the first available array element at the end of the queue b) the element at the end of the queue c) the number of elements remaining to be used at the end of the array d) the number of elements available at the beginning of the array e) none of the above Answer: a Explanation: Rear refers to the first available array element that can be used for an enqueue operation. 15) A double-ended queue allows a) adding elements at one end and removing them from both ends b) adding elements at both ends and removing them from one end c) adding elements at one end, removing them from the other end, and viewing (first) elements at either end.

d) adding, removing, and viewing elements at either end. e) none of the above Answer: d Explanation: A double-ended queue supports adding, removing, and viewing element at either end.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 14

True/False Questions: 1) A queue is a FIFO structure. Answer: True Explanation: A queue is a FIFO structure, meaning that the first element that is put in is the first element that is removed. FIFO stands for first-in-first-out. 2) It is only possible to implement a queue using an array-based structure. Answer: False Explanation: A queue can be implemented using a linked structure or an array-based structure. 7) In a circular array-based implementation of a queue, the elements must all be shifted when the dequeue operation is called. Answer: False Explanation: A circular array-based implementation of a queue eliminates the need to shift elements, so all queue operations can be achieved in constant time. 4) Java provides a Queue class that implements a queue collection Answer: False Explanation: Java provides a Queue interface, but not a Queue class. The interface defines the behaviors that are needed for a queue, but an interface cannot be instantiated. 5) A queue reverses the order of the elements that it processes Answer: False Explanation: A queue, by virtue of being a first in, first out data structure, preserves the order of the elements that it processes. A stack is a data structure that reverses the order of the elements that it processes. 6) In a linked list implementation of a queue, the dequeue operation is more efficient if it removes elements from the front of the linked list than if it removes elements from the rear of the linked list. Answer: True Explanation: Removing an element from the front of a linked list is O(1). Removing an element from the rear of a linked list requires visiting every element in the list to locate the element preceding the last element, and is therefore O(n). 7) In a linked list implementation of a queue, the enqueue operation compares the element to be added against the existing elements in the queue to determine the correct place to insert it. Answer: False Explanation: Inserting an element in the middle of a list of elements is not a queue operation. The enqueue operation adds elements at one end of the linked list. No comparisons between the new element and the existing elements are made. 8) The dequeue operation should throw an exception if it removes the last element in the queue. Answer: False Explanation: The dequeue operation should throw an exception if it determines that a queue is empty before it attempts to remove an element. Removing the last element of a queue is not a problem and should not throw an exception. 9) In a circular array implementation of a queue, the front and rear references can change so that the value in front is greater than the value in rear. Answer: True. Explanation: If the queue operations have caused the rear reference to wrap around the array, its value may be less than the value of the front reference.

5 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 14 10) In a circular array implementation of a queue, the remainder operator (%) can be used to calculate the value of the rear reference in an enqueue operation. Answer: True Explanation: When the last element in an array is filled, the rear reference has to be set to 0. A single statement that will maintain the correct value for the rear reference is rear = (rear+1) % queue.length;

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 14

Short Answer Questions: 1) Suppose the following sequence of elements are added to a queue in the following order: 50, 26, 32, 18, 26, 51. After the elements are added, the following statement is executed three times. myQueue is the name of the queue object: System.out.println(myQueue.dequeue()); What output is produced? Answer: The values 50, 26, and 32 will be printed, in that order, each on a separate line. 2) Write out the order of elements that are contained in a queue after the following operations are performed. myQueue.enqueue(new Integer(8)); myQueue.enqueue(new Integer(6)); Integer num1 = myQueue.dequeue(); myQueue.enqueue(new Integer(3)); myQueue.enqueue(new Integer(4)); myQueue.enqueue(new Integer(15)); myQueue.enqueue(new Integer(12)); myQueue.enqueue(new Integer(9)); myQueue.dequeue(); myQueue.dequeue(); myQueue.dequeue(); myQueue.enqueue(new Integer(19)); Answer: The resulting queue from front to back is 15,12,9,19. 3) List the five basic operations on a queue. Answer: The five basic operations on a queue are enqueue, dequeue, first, isEmpty and size. 4) What is wrong with implementing a queue by using an array, where index 0 represents the front of the queue? Answer: If a queue is implemented with an array with the front of the queue at index 0, every time an element is removed from the queue, all of the remaining elements have to be shifted down one space. This is an inefficient implementation. 5) Explain how a queue can be implemented using an array, where the enqueue and the dequeue operations are both constant time operations (for simplicity, assume that you will never need to expand the capacity of the array). Answer: In order to implement a queue as an array where both the enqueue and the dequeue operations require a constant amount of time, the queue must be implemented as a circular array, meaning that the end of the array and the beginning of the array is connected. We can use the remainder (%) operator to simulate an array with this property. In this setting, the front of the queue and the back of the queue can always be at different indexes, and if we need to enqueue an element when the end of the queue is located at the last index of the array, we enqueue it as the first element in the array. This allows the enqueue and the dequeue operations to be implemented in constant time.

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 14 6) Write an enqueue method for a queue implemented as a circular array. You may assume that you have access to a method called expandCapacity that will double the size of the array if necessary. The class has instance variables front and rear, which represent the indexes of the front and rear of the queue. It also has an integer variable called count that represents the number of elements in the queue, as well as an array of generic T types called queue that represents the queue. Answer: public void enqueue(T element) { if(count == queue.length) expandCapacity(); queue[rear] = element; rear = (rear+1)%queue.length; count++; } 7) Write an enqueue method for a queue implemented as a linked structure. You may assume that the class has references to LinearNode<T> objects called front and rear, which represent the front and rear of the queue respectively. You may also assume that the class has a variable called count, which represents the number of elements in the queue. Answer: public void enqueue(T element) { LinearNode<T> newNode = new LinearNode<T>(element); if(count == 0) front = newNode; else rear.setNext(newNode); rear = newNode; count++; } 8) We maintain two reference variables for a singly linked list implementation of a queue, one for the front and the other for the rear of the queue. Efficiency considerations dictate which end should be used for the enqueue operation and which end should be used for the dequeue operation. Are the same decisions indicated if a doubly linked list is used instead of a singly linked list? Answer: No. The efficiency issue with a singly linked list is with the dequeue operation. If the element to be removed is at the rear of the linked list, then a list traversal must take place in order to determine the node in the list that precedes the node to be removed. This traversal makes the dequeue operation O(n). It is more efficient to remove from the front of the linked list. If a doubly linked list is used, then the node that precedes the node to be removed can be easily determined by using the reference variable in the node to be deleted that points to the preceding node. Dequeue can use either end of the doublylinked list, and enqueue can use the other end.

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 14 9) The size of a queue using a linked list implementation is essentially unlimited. Is it possible to have an essentially unlimited size of a queue if an array-based implementation is used? Explain. Answer: Yes. If an enqueue operation detects that all of the array elements are occupied, it can create a new array with additional capacity and copy the existing queue elements to it. 10) Suppose there is no count variable stored for the linked implementation of a queue. Is it still possible to implement a constant time size operation? How about if there is no count variable stored for an array-based implementation of a queue? Answer: In the case of a linked implementation of a queue, it is not possible to implement a constant-time size operation. The only way to determine the number of elements in the queue is to traverse the list, which would require a linear number of steps. In the case of the array implementation, it is possible to implement a constant time size operation, by determining the distance between the front and rear indexes. One special case to consider is whether or not the queue is empty (since the front and rear indexes are the same when the queue is empty and when the queue is full). Therefore, it would be necessary to store an isEmpty flag in the class. 11) Give an example of a real-life situation that can be modeled with a queue. Answer: There are many possible answers here. One: Patients visiting an urgent care facility that does not take appointments. Patients are seen in the order of arrival, so the first person to arrive is the first person to be seen. Another: Vehicles traveling along a pay (toll) road and lining up to make a payment at a toll booth. The first car to reach the toll booth is the first car that can pay and continue along the road. And another: Items being manufactured that are traveling down an assembly line. Tasks are performed on the items at stations along the assembly line. The items must be processed at each station in the order that they appear on the assembly line, so the first item to reach a station is the first item to be processed at the station. 12) In an array-based implementation of a queue, what purpose is served by treating the array as circular? Is it required in order to have an array-based implementation of a queue? Answer: Treating an array as a circular data structure allows re-use of the array elements that have been emptied by dequeue operations. It provides more efficient use of memory. An array-based implementation of a queue that is not circular is possible. The code to implement the enqueue and dequeue operations can be simpler than in a circular implementation, but memory use is less efficient because it is not re-used. 13) Is it possible to re-use memory in an array-based implementation of a queue without treating the underlying array as circular? Answer: Yes. If the front of the queue is at subscript 0, and if all array elements are shifted forward when a dequeue operation occurs, then memory can be re-used. The tradeoff is that the dequeue operation becomes O(n) due to the shifting of elements. 14) What is gained by writing an interface to a Queue ADT (Abstract Data Type), as opposed to simply writing a Queue class, to solve a problem. Answer: What is gained is code re-use. A well-defined interface can be re-used to implement queues that manage many different types of elements, and whose queue operations can be implemented in different ways. Without a Queue interface, every time a new queue is needed, a programming team has to ensure that they are providing all of the functionality of a queue in their implementation.

9.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 14 15) Write a size method for a linked list implementation of a queue that does not have a count member. Answer: public int size() { int count; // number of nodes if (head == null) count = 0; else { count = 1; LinearNode<T> temp = head; // for traversal while(temp.getNext() != null) { count++; temp = temp.getNext(); // go to next node } // end while } // end else return count; } // end method size

10 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 15

Chapter 15: Lists Multiple Choice Questions: 1) A(n) _____________________ is a list collection has elements that are ordered by a characteristic of the elements. a) ordered list b) unordered list c) indexed list d) linked list e) array Answer: a Explanation: An ordered list has elements that are ordered by an inherent characteristic of the elements. A linked list or an array can be used to implement a list collection. 2) A(n) _____________________ is a list collection has elements whose elements can be referenced using a numeric index. a) ordered list b) unordered list c) indexed list d) linked list e) array Answer: c Explanation: An indexed list has a numeric index that can be used to refer to an element. Ordered and unordered lists do not have an index. Linked lists and arrays are implementation strategies that can be used for collections. 3) Which operation below is not part of the List interface? a) add an element to the list b) remove an element from the list c) replace an element in the list with another element d) get the size of the list e) grow the size of the list Answer: e Explanation: The size of a list changes as elements are added and removed. The list ‘grows’ by adding elements to it. 4) The List interface is implemented by the ________ class. a) array b) ArrayList c) String d) Object e) Exception Answer: b Explanation: The ArrayList class implements the List interface.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 15 5)

The List ADT (Abstract Data Type) provides how many operations to remove an element from a list? a) 1 b) 2 c) 3 d) 4 e) more than 4

Answer: c Explanation: The List ADT has remove to remove a particular element, removeFirst to remove the first element, and removeLast to remove the last element. 6) What is the nature of the methods that are added to the OrderedListADT and UnorderedListADT interfaces that extend the ListADT interface? a) They are methods to add elements to the list b) They are methods to remove elements from the list c) They are methods to delete the list d) They add a method to determine the location of an element in the list e) They add a method to determine the size of the list Answer: a Explanation: The add method is defined in the OrderedListADT interface. The addToFront, addToRear, and addAfter methods are defined in the UnorderedLIstADT interface. 7) A list collection can be implemented using either a) a stack or a queue b) an Exception or an Error c) add or remove operations d) an array or a linked structure e) both c) and d) are correct Answer: d Explanation: The underlying implementation of a list collection can be either an array or a linked list. An implementation may throw an Exception, but it should not throw an Error. Add and remove operations are both required and are not an either-or choice. Stacks and queues do not allow elements to be added or removed beyond the ends of the stack or queue, and as such are inappropriate for use with a list collection. 8) The Serializable interface allows a) Exceptions to be thrown from methods. b) objects to be read from and written to external files. c) Object class elements to be added to list collections. d) compiler warning messages to be suppressed. e) none of the above Answer: b Explanation: The Serializable interface supports the writing and reading of objects to and from a file. Exceptions do not require an interface in order to be thrown. Objects of the Object class can be added to a list collection using a cast operator. Compiler warning messages should be addressed, not suppressed.

2.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 15 9) The remove operation returns a) an int representing the number of elements remaining in the list after the removal. b) a boolean value indicating if the remove was successful or not. c) the element that was removed. d) a pointer to the list e) The remove operation does not return any of these. Answer: c Explanation: The remove operation returns the element that was removed. The size method returns the count of the number of elements in the list. If an element cannot be located, the remove operation throws an Exception. 10) The find method, as used in the array-based implementation of the remove and contains operations, returns a) the element that was found b) the index of the element that was found c) a true or false value indicating whether the element was found d) the element whose reference variable points to the element that was found e) none of the above Answer: b Explanation: The find method returns the index of the element in the underlying array. The remove operation returns the element that was found. Choice d) refers to a reference variable as part of an element, which might be used in a linked structure implementation of a list collection. 11) The addAfter operation of an unordered list collection is a) O(1) b) O(log n) c) O(n) d) O(n log n) e) a higher order than O(n log n) Answer: c Explanation: the addAfter operation uses two parameters, one that is a reference to the element to add and another that is a reference to the element that precedes the location where the element will be added. The addAfter operation will have to perform a number of comparisons to locate the element that precedes the location where the element will be added, followed by a number of moves of the elements after the location to make room for the added element. Together, the comparisons and moves make this an O(n) operation. 12) As with queues and stacks, the first step in removing an element from a list collection is to a) determine that the collection is not empty. b) determine if the element is in the collection. c) determine if the element is in the first or the last position in the collection. d) determine if the collection will be empty once the element is removed. e) none of these is a reasonable first step in removing an element from a collection. Answer: a Explanation: It is not possible to remove an element from an empty list. There is no point in performing any other steps if the list is empty, so determining this is the first step.

3.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 15 13) Which of the following is a method in the java.util.List interface? a) addBefore b) addAfter c) add d) shift e) resize Answer: c Explanation: The add method is part of the List interface. It is overloaded and has two forms, one that takes an element to add as parameter, and another that takes an element to add and an index at which to add the element. 14) Which of the following is not a way to categorize list collections? a) public b) ordered c) unordered d) indexed e) all of the above are ways to categorize list collections Answer: a Explanation: Choices b), c), and d) are all ways to categorize list collections. 15) When adding elements to an ordered list, the elements are ordered according to a) the order of the calls to the add operation to add them to the list. b) increasing size of storage to hold the element c) the key value of each element d) the address of the location in memory that holds the element. e) none of the above is used to determine the order of the elements in an ordered list. Answer: c Explanation: Each element in an ordered list has a characteristic that is used to determine the ordering of the elements. This characteristic is referred to as a key value. As an element is added to the list, the key value of the element is compared to the key values of the existing elements in the list until the proper location for the element is determined.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 15

True/False Questions: 1) A linked list is a conceptual notion of organizing things in a linear list Answer: False Explanation: A linked list is a type of implementation, not a conceptual notion. A list collection is a conceptual notion of organizing things in a linear list. 2) The size of a list collection is unbounded Answer: True Explanation: A list collection can grow as large as necessary. 3) An array is an example of an indexed list Answer: False Explanation: While an array may seem like an example of an indexed list, one important difference is that an array may have unused elements in between elements that are used. In an indexed list with more than one element, each element has another element adjacent to it. If an element is removed from an indexed list, there is no empty gap between elements. 4) A user does not have any control over the order of the elements in an unordered list Answer: False Explanation: A user can add elements to either end of an unordered list or insert them between other elements. The user controls the order of the list. The list is unordered because there is no inherent relation between the elements in the list. 5) The LinkedList class is an example of a class that implements the List interface. Answer: True Explanation: LinkedList and ArrayList are among the classes that implement the List interface. 6) The contains method of the List ADT (Abstract Data Type) lets you know if a particular element is in a list. Answer: True Explanation: The method returns true if the element is in the list, and false if the element is not in the list. It does not return the element. 7) The primary difference between the OrderedList ADT and the UnorderedList ADT is in how elements are removed from the list Answer: False Explanation: The OrderedList ADT and the UnorderedList ADT differ in how elements are added to the list, not in how elements are removed. The OrderedList ADT supports an add method, while the UnorderedList ADT supports addToFront, addToRear, and addAfter methods. 8) Using a circular array for an array-based implementation of a list would improve the performance of the operation to remove an element from the middle of a list Answer: False Explanation: Removing an element from somewhere other than the rear of the list requires that other elements be shifted to close the gap. A circular array does not eliminate the need to shift elements and does not offer a performance improvement over an array that is not circular.

5 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 15 9) The operation to remove an element from an array implementation of a list collection is O(n). Answer: True Explanation: Removing an element from a list of n elements will require a total of n comparisons and shifts of elements. If the element to be removed is the first element, then it requires 1 comparison and (n-1) shifts. If the element to be removed is the last element, then it requires n comparisons and no shifts. If the element is at position i of the list, then there are i comparisons and (n-i) shifts. 10) The remove operation returns a boolean value that indicates if the element to be removed was found in the list. Answer: False Explanation: The remove operation returns the element to be removed. If the element is not found, an Exception is thrown. It is up to the user program to detect the Exception and to process it.

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 15

Short Answer Questions: 1) Explain the hierarchy of interfaces to support List objects as documented in the textbook. Explain why specific methods appear in particular interfaces. Answer: The text introduces a List ADT interface that contains the methods that are common to all list collection types. For example, all List types need to be able to report how many elements are in the list. It then introduces the OrderedList ADT interface that extends the List ADT interface and introduces the add method that is needed to add an element to an ordered list. The UnorderedList ADT interface also extends the List ADT and it introduces the three variations on add – addToFront, addToRear, and addAfter – that are required to support unordered lists. 2) Why is the find method, used by the remove and the contains operations, declared with private visibility? Answer: The remove and the contains operations are implemented with methods that have public visibility, as their operations are part of the list interface. The find method is used by remove and contains, but it is not part of the list interface. For this reason, it has private visibility and is not available for use by a list collection user directly. 3) The find method, used by the remove, contains, and addAfter operations, returns -1 if an element is not found in an arraybased implementation of a list collection. Why doesn’t it throw an Exception in this case? Answer: The find method is a private method that is used by public methods that provide the interface to the list collection. By returning -1 as a signal that an element is not in the list, the calling method can determine how to respond. In the case of the remove operation, the correct response is to throw an exception, as you cannot remove something that is not present. In the case of the contains operation, the correct response is to return false to indicate that there is no such element in the list. 4) What are the differences between an ordered list, an unordered list, and an indexed list? Answer: An ordered list has elements that are arranged according to some characteristic of each element. When elements are added to the list, they are added to maintain the relationship of this characteristic among adjacent elements. An unordered list is a list in which the elements have no such inherent characteristic that can be used to order them. The elements are still in the list in some order, but the order is determined by the user of the list. An indexed list is also unordered, in that the elements are added to the list in an order determined by the user of the list and not by a relation between characteristics of the elements. However, an indexed list also has an index associated with each element. As an element is added to the list, it is given an index appropriate for its position in the list. All of the indexes of the elements after the added element are adjusted so that they remain contiguous and in order. 5) The java.util.List interface has an add method that takes an index and an element as parameters. It adds the element to the list at the index. Its header is void add(int index, E element) Can the addToFront operation use an implementation of this add method? Answer: Yes. ‘Add to front’ means ‘add at index 0’, so the body of the method could essentially be add(0, element);

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 15 6) Given the list elements and contents below. Which type of list collection could be used to represent them? Explain your choice. rear front of list of list Alice

Billy

Carla

David

Answer: These list elements could most likely be represented by an ordered or an unordered list. The contents of the elements that we can see are arranged alphabetically, so these elements could be represented by an ordered list, where the add operation is implemented to maintain alphabetical order. It’s also possible that they can be represented by an unordered list, where the order that is seen is the order that the user has chosen to arrange the elements in the list. There are no indexes represented in the illustration, so an indexed list is not indicated. 7) Can a list be of more than one type? For example, can a list be both unordered and indexed, or ordered and unordered? Answer: In general, a list should be designed with a single list collection type in mind. Conflicts between the operations of list types can arise if a user treats a list as having multiple types. For example, an ordered list uses relationships between the elements to establish the order of the elements in the list. It has a single add operation that uses the relationships to add in the correct location. If an ordered list is also modified by an addToFront operation for an indexed list, the relationship between elements will most likely not be maintained. 8) Identify some of the methods in the java.util.List interface that support an indexed list. Answer: All of the methods that take an index as a parameter support indexed lists. They include add, get, remove, and set. Additionally, the size method can be used with any list, so it supports indexed lists. 9) Write the header and body for isEmpty. The method returns true if the list is empty and false otherwise. Does the method need to know if the underlying implementation uses an array or a list structure? Answer: isEmpty can be determined from a call to size and does not need to know how the list is implemented. Here are two possible solutions: public boolean isEmpty() { if (size() == 0) return true; else return false; }

public boolean isEmpty() { return (size() == 0); }

10) The contains operation, used to determine if a particular element is in a list, relies on the find support method to locate the element. The find method, in turn relies on which method being implemented in order to work? Answer: find calls the equals method to determine if the element that was passed to find as a parameter is the same as an element in the list. The equals method must be implemented in such a way that it compares those characteristics of an element that are sufficient to determine equality.

8.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 15 11) Elements added to an ordered list must support which interface? Answer: Elements added to an ordered list must implement the Comparable interface. By implementing this interface, the objects can be compared, and an order can be established. The Comparable interface requires that the elements have a compareTo method, which is used by the add operation. 12) In a linked list implementation of the remove operation, the element to be removed is located. What are the possible situations that must be considered as part of removing the element once it is located? Answer: One situation is that the element to be removed is the only element in the list, and the list will be empty after removal. The other situations involve where the element is relative to the other elements in the list. Is the first element? Is it the last element? Is it somewhere in the middle of the list? Each of these requires different adjustments of reference variables as part of the removal. 13) Can the add operations for an unordered list be used to maintain an ordered list? Answer: No. The add operation for an ordered list compares the element to be added against the existing list elements to determine the location of the new element. The add operations for an unordered list – addToFront, addToRear, and addAfter – do not perform any comparisons between an element to be added and the existing elements in the list. Use the class below for questions 14) and 15) public class Student { private String name; private double courseAverage; // accessor, mutator, and // support methods ... } 14) An academic researcher wants to use this class to create Student objects and arrange them in a list in descending order according to the value of their courseAverage member. What is the most appropriate list collection type to use? Answer: Since the list elements will be arranged in an order, an ordered list is the most appropriate list collection type to use. 15) Suppose that a researcher decides to use an ordered list to organize Student objects. What must be done to the Student class to support this? Answer: Elements in an ordered list must be comparable. The Student class must implement the Comparable interface and it must provide a body for the compareTo method.

9 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 16

Chapter 16: Iterators Multiple Choice Questions: 1) An iterator is a) an element in a collection. b) an object that allows access to each element in a collection individually. c) an interface d) a loop control variable e) a five syllable word Answer: b Explanation: An iterator is an object that allows a user to access and use each of the elements in a collection one at a time. It is not an element in a collection. Iterator is an interface, but an iterator is an object. It has a hasNext method that can be used to control a loop, but an iterator is not a loop control variable. 2) Which method below is not part of the Iterator interface? a) add b) remove c) next d) hasNext e) all of these are methods in the Iterator interface. Answer: a Explanation: There is no add method in the Iterator interface. An iterator can remove an element from a collection, but it cannot add elements. 3) The only method in the Iterable interface is a) create b) iterator c) destroy d) remove e) hasNext Answer: b Explanation: The Iterable interface has a single method, iterator. remove and hasNext are methods in the Iterator interface.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 16 4) When writing a class for an array-based implementation of a list, the class that defines an iterator for the list should be a) public b) iterable c) an interface d) an inner class e) none of the above Answer: d Explanation: An inner class is a class that is declared inside of another class. A list iterator class is only for the use of the class that implements the list, and as such is private to the list class. The list class should be iterable, but the list iterator class is not. The list iterator implements the Iterator interface, but it is a concrete class and not itself an interface 5) A user defines a class to implement an iterator for a user-defined collection. When an iterator object is created, it needs to know a) when it was created b) why it was created c) the number of elements in the collection d) the datatype of the elements in the collection e) none of the above Answer: c Explanation: A user-defined iterator needs to know the size of the collection when the iterator is created. The iterator uses this to detect if the collection is modified via a reference to the collection. If modifications are detected, the iterator throws a ConcurrentModificationException.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 16

True/False Questions: 1) Using the hasNext() and next() methods in a loop is the only way to retrieve all of the list elements using an iterator. Answer: False Explanation: The for-each loop can also be used. It does not explicitly declare an iterator, but Java translates the foreach code into code that uses an iterator before the code executes. 2) A user may not be able to predict the order in which an iterator will return elements from a collection Answer: True Explanation: An iterator returns elements in an order that may be collection-dependent. The order may not reflect a user’s assumption about what order should be used. 3) ‘Fail-fast’ means that a program will crash if a collection class supports the Iterable interface but no Iterator object is created. Answer: False Explanation: Fail-fast means that in Iterator object will throw an exception if it detects that a collection is being modified while the iterator is active. 4) An iterator’s remove method requires the use of a for-each loop. Answer: False Explanation: An iterator’s remove method should not be used with a for-each loop. Instead, a while loop could be used to call the iterator’s hasNext method, and the body of the while loop can contain the call to the remove method. 5) When a user writes code to implement a collection class that implements the Iterable interface, they have to write code for the next and hasNext methods. Answer: False Explanation: next and hasNext are methods of the Iterator interface. The Iterable interface has a single method, iterator. 6) When a user defines an Iterator class for a user-defined collection, the user must implement the methods in the Iterator interface in a way that detects if the collection is modified independent of the iterator object. Answer: True Explanation: An iterator is a reference to objects in a collection. The collection also maintains references to the objects. If a reference to the collection modifies the collection while the iterator is active, the iterator throws a ConcurrentModificationException

3 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 16

Short Answer Questions: 1) roster is an ArrayList of Student objects. Write a segment of code that will modify Roster so that its size becomes 0. Use an iterator. Answer: Iterator<Student> it = roster.iterator(); while (it.hasNext() ) { it.next(); it.remove(); } 2) What happens if an Iterator object is active and the underlying collection is updated via collection operations? Answer: The Iterator object will throw a ConcurrentModificationException. If the exception was not thrown, then a program may produce unpredictable results if the Iterator object and the collection methods both accessed the collection. 3) An ordered list contains elements with values 14, 22, -6, and 35. The list has an Iterator object. In what order will the elements be accessed? Answer: The order is not predictable. The compareTo method, used by the add operation of an ordered list class, may indicate a particular order, say, increasing or decreasing. However, the iterator is not bound to honor that order. An iterator only guarantees that all elements will be accessed, not the order in which they will be accessed. 4) What does “fail-safe” mean? How is it used with iterators? Answer: Fail-safe refers to an iterator’s ability to detect list collection modifications while the iterator is active. Since an iterator can access all of the members of a collection, if the collection changes while the iterator is accessing, then unknown errors can occur. If changes to a collection occur and are detected while an iterator is active, the iterator will throw a ConcurrentModificationException. 5) What does it mean for a class to be Iterable? Answer: An Iterable class is one that implements the Iterable interface. The Iterable interface has a single method, iterator, that returns an Iterator object. The returned object can be used to iterate over objects of the class that implements the Iterable interface.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 17

Chapter 17: Recursion Multiple Choice Questions: 1) A method that calls itself is a __________________ method. a) invalid b) static c) final d) recursive e) public Answer: d Explanation: A recursive method is a method that calls itself. 2) ____________________ recursion occurs when a method calls itself, while _________________ recursion when a method calls another method that then calls the original method. a) upward, downward b) downward, upward c) direct, indirect d) indirect, direct e) none of the above Answer: c Explanation: Direct recursion occurs when a method calls itself, while indirect recursion occurs when a method calls another method that then calls the original method. 3) __________________ recursion results from the lack of a base case. a) Indirect b) Direct c) Infinite d) Spiral e) none of the above Answer: c Explanation: Infinite recursion results from the lack of a base case, which causes the recursive path to be followed forever. 4) The _______________________ puzzle is a favorite of computer scientists because of its elegant recursive solution. a) Tower of Hanoi b) Sudoku c) Tetris d) Tic-Tac-Toe e) none of the above Answer: a Explanation: The Tower of Hanoi puzzle has an elegant recursive solution and has therefore become a favorite of computer scientists. 1.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 17

5) In the Towers of Hanoi puzzle, there are ________________ pegs. a) 2 b) 3 c) 4 d) 5 e) The Towers of Hanoi puzzle can include any number of pegs Answer: b Explanation: In the Towers of Hanoi puzzle, there are always exactly three pegs. 6) In indirect recursion, how many method calls can occur between one call to a method and the next one that completes the indirect recursion a) 2 b) 3 c) 4 d) 5 e) There is no limit to the number of intervening calls between a method and its indirect recursive call. Answer: e Explanation: Java does not impose a limit on the number of intervening methods between a call to a method and a call that creates indirect recursion. From a practical standpoint, the fewer the number of calls, the simpler the program will be to understand and the easier the task of tracing the recursion should that become necessary. 7) Which of the following statements is true? a) Recursion should be used in every program. b) Recursion should be avoided all the time. c) Solutions that are easily expressed recursively should be programmed recursively. d) Solutions that are easily expressed recursively should be programmed iteratively. e) None of the above. Answer: c Explanation: Recursion should be used when the solution is easily expressed recursively. 8) Which of the following will result from infinite recursion in Java? a) The program will hang as though there is an infinite loop. b) The program will throw an ArrayOutOfBoundsException. c) The program will not compile. d) The program will run out of memory. e) none of the above. Answer: d Explanation: Infinite recursion will cause a program to run out of memory.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 17 9) How many base cases must a recursive method have? a) A recursive method does not have to have a base case. b) at least 1 c) more than 1 d) more than 2 e) more than 3 Answer: b Explanation: Every recursive method must have at least one base case. It may have more, but it must have at least one. 10) All recursive programs ____________________________________ . a) are more difficult to read than iterative programs. b) can be implemented iteratively. c) are easier to read than iterative programs. d) are shorter than iterative programs. e) none of the above are true. Answer: b Explanation: All recursive programs can be implemented iteratively, although a recursive solution may be easier to code. 11) The recursive solution of the Towers of Hanoi problem has _______________ complexity. a) exponential b) polynomial c) logarithmic d) low e) none of the above Answer: a Explanation: The recursive solution of the Towers of Hanoi problem has exponential complexity, which means that it is significantly inefficient. 12) Which of the following is a proper recursive definition of x raised to the y power? a) 𝑥 𝑦 = 𝑥 ∗ 𝑥 𝑦−1 b) 𝑥 𝑦 = 𝑥 ∗ 𝑥 𝑦−2 c) 𝑥 𝑦 = 𝑥 ∗ 𝑥 𝑦−1 𝑓𝑜𝑟 𝑦 > 1; 𝑥 𝑦 = 𝑥 𝑓𝑜𝑟 𝑦 = 1 d) 𝑥 𝑦 = 𝑥 ∗ 𝑥 𝑦−1 𝑓𝑜𝑟 𝑎𝑙𝑙 𝑥 e) none of the above Answer: c Explanation: Choice c is correct because it has a properly defined base case.

3 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 17 13) There is(are) ____________ base case(s) in the recursive solution to finding a path through a maze. a) 0 b) 1 c) 2 d) 3 e) 4 Answer: c Explanation: There are two base cases in the recursive solution to this problem. The two base cases are: (1) a path has been found, and (2) there is no way to move forward via the current path. 14) A solution with exponential complexity is ____________________ . a) efficient b) inefficient c) easy to implement d) difficult to implement e) none of the above Answer: b Explanation: A solution with exponential complexity is very inefficient. 15) In a recursive solution, _______________ is(are) always necessary. a) short, efficient code b) several variables c) numerous lines of code d) a base case e) none of the above Answer: d Explanation: A base case is always necessary in a recursive solution to avoid infinite recursion.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 17

True/False Questions: 1) In Java, it is possible for a method to call itself. Answer: True Explanation: A method that calls itself is a recursive method. 2) Some problems can only be solved recursively. Answer: False Explanation: Any problem that can be solved recursively can also be solved iteratively. 3) All recursive methods must have a base case. Answer: True Explanation: If a recursive method does not have a base case, it will yield an infinite recursion which will crash a program. 4) A method that calls a different method, which then calls the original calling method is a recursive method. Answer: True Explanation: This is an example of indirect recursion. 5) Recursive solutions to problems should be used whenever possible. Answer: False Explanation: There are some cases where the iterative solution is less complex and more straightforward to code. In these cases, recursion is not the best choice. 6) In the Towers of Hanoi puzzle, it is legal to move a larger disk to a peg that already contains a smaller disk. Answer: False Explanation: In the Towers of Hanoi puzzle, the only valid moves move a disk to a peg that only contains smaller disks. 7) The Towers of Hanoi puzzle cannot be solved iteratively. Answer: False Explanation: Any problem that can be solved recursively can also be solved iteratively. Therefore, the Tower of Hanoi puzzle must have an iterative solution. 8) Determining whether or not there is a path through a maze has a recursive solution. Answer: True Explanation: It is possible to traverse a maze recursively, and therefore there is a recursive solution to determining whether or not there is a path through a maze. 9) A program with infinite recursion will act similarly to a program with an infinite loop. Answer: False Explanation: A program with infinite recursion will run out of memory. This will cause the program to crash. A program with an infinite loop will appear to “hang.” 10) Recursive solutions are always more efficient than iterative solutions Answer: False Explanation: Some recursive solutions are very efficient, but some are very inefficient.

5 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 17

Short Answer Questions: 1) What is recursion? Answer: Recursion is a common programming technique where a method calls itself. 2) Give a recursive definition of the sum of the first n integers, S(n). Answer: S(0) = 0 S(n) = n + S(n – 1) for n > 0 3) Write a recursive method that computes the sum of the first n integers. Answer: public int sum(int n) { if(n == 0) return 0; else return n + sum(n-1); } 4) Write the recursive definition of the factorial of a number. Answer: 1! = 1 𝑛! = 𝑛 ∗ (𝑛 − 1)! 𝑓𝑜𝑟 𝑛 > 1 5) Write a recursive method that returns the factorial of an integer. Answer: public int factorial(int n) { if(n == 0) return 1; else return n*factorial(n-1); }

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 17 6) What is wrong with the following recursive method that computes the sum of all of the odd positive integers less than or equal to n? public int sumOfOdds(int n) { if(n%2 == 0) return sumOfOdds(n-1); else return n + sumOfOdds(n-2); } Answer: This method has no base case, and therefore running it would cause infinite recursion. 7) Write a recursive definition for K(n), which represents the product of all of the even integers less than or equal to n. Answer: 𝐾(1) = 0 𝐾(2) = 2 𝐾(𝑛) = 𝑛 ∗ 𝐾(𝑛 − 2) 𝑖𝑓 𝑛 𝑖𝑠 𝑒𝑣𝑒𝑛 𝑎𝑛𝑑 𝑔𝑟𝑒𝑎𝑡𝑒𝑟 𝑡ℎ𝑎𝑛 2 𝐾(𝑛) = 𝐾(𝑛 − 1) 𝑖𝑓 𝑛 𝑖𝑠 𝑜𝑑𝑑 𝑎𝑛𝑑 𝑔𝑟𝑒𝑎𝑡𝑒𝑟 𝑡ℎ𝑎𝑛 2 8) Write a recursive method that computes the product of all of the even integers less than or equal to n. Answer: public int productOfEvens(int n) { if(n <= 1) return 0; if(n == 2) return 2; if(n%2 == 0) return n*productOfEvens(n-2); else return productOfEvens(n-1); } 9) The Fibonacci sequence is defined as the sequence that begins with 0 and 1, and every other number in the sequence is the sum of the two preceding numbers. Write a recursive mathematical definition of the numbers in the Fibonacci sequence. Answer: 𝐹(1) = 0 𝐹(2) = 1 𝐹(𝑛) = 𝐹(𝑛 − 1) + 𝐹(𝑛 − 2) 𝑓𝑜𝑟 𝑛 > 2

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 17 10) The Fibonacci sequence is defined as the sequence that begins with 0 and 1, and every other number in the sequence is the sum of the two preceding numbers. Write a recursive method that computes the 𝑛𝑡ℎ number in the Fibonacci sequence. Answer: public int fibonacci(int n) { if(n == 1) return 0; if(n == 2) return 1; return fibonacci(n-1) + fibonacci(n-2); } 9) The Lucas sequence is defined as the sequence that begins with 2 and 1, and every other number in the sequence is the sum of the two preceding numbers. A recursive method to generate the 𝑛𝑡ℎ term in the Lucas sequence is: public int lucas(int n) { if(n == 1) return 2; if(n == 2) return 1; return lucas(n-1) + lucas(n-2); } When calculating lucas(8), how many times is lucas(5) calculated? Answer: lucas(8) calls lucas(7) and lucas(6). Each of these makes calls also. Here is a partial call tree down to lucas(5): lucas(8) / lucas(7) / \ lucas(6) lucas(5) / \ lucas(5) lucas(4)

\ lucas(6) / lucas(5)

\ lucas(4)

There are 3 calls to lucas(5), so lucas (5) is calculated 3 times in the calculation of lucas(8). 12) Describe a recursive solution to the Towers of Hanoi puzzle with N disks. Answer: The solution is: (1) Move the top N-1 disks to the extra peg. (2) Move the largest disk from the original peg to the destination peg. (3) Move the N-1 disks from the extra peg to the destination peg. The first step is the same problem again, with the extra peg and the destination peg interchanged, and therefore this subproblem can be solved recursively. The base case is when N = 1, in which case we simply move the disk without any recursive call. 13) What is/are the base case(s) when calculating the sum of the first n positive integers recursively? Answer: The base case occurs when n = 1, the smallest positive integer. 8.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 17

14) Describe a recursive solution to determine whether a String object is a palindrome. You may assume that the string only contains lower case characters (i.e. no numbers, spaces, punctuation, etc.). Hint: It may be easiest to describe your solution using pseudocode. Answer: isPalindrome(String s) if the length of the string is 1 return true else if the length of the string is 2 and the two characters are the same return true else if the first and the last characters are the same return isPalindrome(the string created by removing the first and last characters) else return false 15) Write a recursive Java method that takes a String as a parameter and returns true if the String is a palindrome. You may assume that the string only contains lower case characters (i.e. no numbers, spaces, punctuation, etc). Answer: public boolean isPalindrome(String s) { if(s.length() == 1) return true; else if(s.length() == 2 && s.charAt(0) == s.charAt(1)) return true; else if(s.charAt(0) == s.charAt(s.length() – 1)) return isPalindrome(s.substring(1, s.length() - 1)); else return false; }

9 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 18

Chapter 18: Searching and Sorting Multiple Choice Questions: 1) _____________________ is the process of finding a designated target element within a group of items. a) Sorting b) Searching c) Recursing d) Helping e) none of the above Answer: b Explanation: Searching is the process of finding a designated target element in a search pool. 2) As the number of items in a search pool grows, the number of comparisons required to search _______________ . a) increases b) decreases c) stays the same d) goes to 0 e) none of the above Answer: a Explanation: The more items in the search pool, the more comparisons are required to find the element. 3) A __________________ search looks through the search pool one element at a time. a) binary b) clever c) insertion d) selection e) linear Answer: e Explanation: In a linear search, the algorithm iterates through the pool one at a time in a linear manner. 4) A _______________ search is more efficient than a linear search. a) binary b) selection c) insertion d) bubble e) none of the above Answer: a Explanation: A binary search is more efficient than a linear search, but it assumes that the search pool is ordered.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 18 5) In a binary search, _______________________________ . a) it is assumed that all of the elements are integers. b) it is assumed that all of the elements are Strings. c) it is assumed that the search pool is small. d) it is assumed that the search pool is ordered. e) it is assumed that the search pool is large. Answer: d Explanation: In a binary search, it is assumed that the search pool is ordered. 6) ____________________ is the process of arranging a group of items into a defined order. a) Searching b) Sorting c) Selecting d) Helping e) none of the above Answer: b Explanation: Sorting is the process of arranging a group of items into a defined order. 7) Which of the following is not a sorting algorithm? a) Bubble sort b) Quick sort c) Merge sort d) Selection sort e) all of the above are sorting algorithms Answer: e Explanation: All of the algorithms listed are examples of sorting algorithms. 8) Which data structures are used by a radix sort? a) stacks b) queues c) heaps d) both a) and b) are correct e) a), b), and c) are all correct Answer: b Explanation: A radix sort uses queues to hold the elements being sorted during intermediate stages.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 18 9) The ___________________ algorithm sorts values by repeatedly comparing neighboring elements in the list and swapping their position if they are not in order relative to each other. a) insertion sort b) selection sort c) bubble sort d) quick sort e) merge sort Answer: c Explanation: Bubble sort works in the way described above. 10) The __________________ algorithm sorts a list of values by repetitively inserting a particular value into a subset of the list that has already been sorted. a) insertion sort b) selection sort c) bubble sort d) quick sort e) merge sort Answer: a Explanation: Insertion sort works in the way described above. 11) The ___________________ is the number of possible values of the digits or characters in a sort key. a) radix b) asymptote c) thread d) order e) none of the above Answer: a Explanation: In a radix sort, the radix is the number of queues, which is the number of possible values of each digit or character in a sort key. 12) ________ can be used to sort the same set of objects in multiple ways a) insertion sort b) selection sort c) bubble sort d) random sort e) Comparator objects Answer: e Explanation: Comparator objects can be created for a class that support comparing elements in the class in a particular way. Multiple Comparator objects can be created to compare elements in different ways.

3 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 18 13) In order to compare objects of a class in different ways, a) the class must implement the Comparable interface b) the class must implement the Comparator interface c) the class must inherit from the Comparator class d) a separate class must be created that implements the Comparator interface and provides a body for the compare method e) None of these is correct. Answer: d Explanation: Comparator objects are not part of the class whose objects are being compared, so the class does not need to extend or inherit anything other than what it already inherits or extends. Comparator objects are separate from the class of objects being compared but are used by the sort method of the Arrays class to determine the sort order. 14) Suppose we have algorithms that solve a particular problem that have the following complexities. Which one is most efficient? a) O(1) b) O(log2n) c) O(n2) d) O(n3) e) O(2n) Answer: a Explanation: The algorithm with constant time complexity (O(1)) is the most efficient. 15) Which of the following algorithms has a worst case complexity of O(n log 2n)? a) insertion sort b) selection sort c) bubble sort d) merge sort e) none of the above Answer: d Explanation: Merge sort has a worst-case complexity of O(n log2n).

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 18

True/False Questions: 1) In a radix sort, the radix is the number of elements to be sorted. Answer: False Explanation: In a radix sort, the radix is the number of possible values for a component of the sort key. For example, if the sort key is a positive integer and a component is a single digit, then the radix is 10, the number of possible digits. 2) The underlying data structure used in a radix sort is a stack Answer: False Explanation: A radix sort puts elements into queues, not stacks. 3) A linear search always requires more comparisons than a binary search. Answer: False Explanation: If the element that is being searched for is the first element in the list, then a linear search would require less comparisons than a binary search. 4) If there are more items in a search pool, then it will typically require more comparisons to find an item. Answer: True Explanation: As the number of elements in the search pool increases, the number of comparisons necessary to find the item increases as well. 5) Bubble sort is the most efficient searching algorithm. Answer: False Explanation: Merge sort and quick sort are more efficient than bubble sort. 6) Quick sort works by separating a list into two lists, and recursively sorting the two lists using quick sort. Answer: True Explanation: Quick sort works by dividing a list into two lists, and then recursively sorting the two lists using quick sort. 7) The sort method of the Arrays class sorts the elements of an array by using a comparator Answer: True Explanation: The comparator is used to determine how to compare two elements in the array for the purposes of sorting the array. 8) Implementing the Comparator interface requires writing a body for the compareTo method. Answer: False Explanation: The Comparator interface requires a body for the compare method. It is the Comparable interface that requires a body for the compareTo method. 9) With each comparison, a binary search eliminates approximately half of the items remaining in the search pool. Answer: True Explanation: A binary search cuts the number of items remaining in the search pool in half with each comparison. 10) The selection sort algorithm sorts a list of values by repeatedly putting a particular value into its final, sorted position. Answer: True Explanation: The selection sort algorithm finds the value that goes into the next open spot in the list and puts it there.

5 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 18

Short Answer Questions: 1) Write a method that accepts an integer and an array of integers, and returns true if the integer is contained in the array. The method should use a linear search. Answer: public boolean linearSearch(int a, int[] array) { boolean found = false; int i = 0; while(i < array.length && !found) { if(array[i] == a) found = true; i++; } return found; } 2) Write a method that accepts an integer and an array of integers and returns true if the integer is contained in the array. You may assume that the array is sorted, and your method should use a binary search. Answer: public boolean binarySearch(int a, int[] array) { int first = 0; int last = array.length-1; int mid; while(first <= last) { mid = (first+last)/2; if(array[mid] == a) return true; else if(array[mid] > a) last = mid - 1; else last = mid + 1; } return false; }

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 18 3) Write a method that accepts an integer array as a parameter and sorts it using the bubble sort algorithm. Answer: public void bubbleSort(int[] array) { int temp; for(int i = array.length-1; i >=0; i--) { for(int j = 0; j < i; j++) { if(array[j] > array[j+1]) { temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; }//end if }//end for j }//end for i } 4) Write a method that accepts an array of integers as a parameter and sorts them using the selection sort algorithm. Answer: public void selectionSort(int [] array) { int minIndex, temp; for(int i = 0; i < array.length; i++) { minIndex = i; for(int j = i+1; j < array.length; j++) { if(array[j] < array[minIndex]) minIndex = j; }//end for j temp = array[i]; array[i] = array[minIndex]; array[minIndex] = temp; }//end for i } 5) If binary search is more efficient than linear search, why not just sort an array and then use binary search whenever we need to search for an element in an unsorted array? Answer: The overhead introduced by sorting the array before searching may be great enough to make the sorting/binary search combination less efficient than using linear search alone.

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 18 6) In the binary search algorithm, if the number of elements in the search pool is even, which value is used as the midpoint? Explain. Answer: If the number of elements in the search pool is even, there is no well-defined midpoint. The algorithm ends up using the last element in the first half of the search space as the midpoint, since integer division will throw away the remainder. 7) Suppose we would like to swap the elements at index i and index j in an array. Does the following code work? If so, explain how. If not, explain why it fails. array[i] = array[j]; array[j] = array[i]; Answer: This fails because the first step overwrites the element stored in array[i]. Therefore, the second line will copy the value that is already stored at array[j] back into array[j]. A temporary variable is required to properly swap the two elements in an array. First, the value of one element is copied into the temporary variable. Then, the value of the second element is copied into the first element. Finally, the value that was copied into the temporary variable is copied into the second element. 8) InventoryItem is a class that defines an item in the inventory of a warehouse. One of the fields, partNumber, is unique to each item in the inventory. partNumber is stored as an int, but it is comprised of 6 octal digits, that is, digits in the range 0 – 7 inclusive. If InventoryItem objects are sorted according to the partNumber field, what is the radix? Answer: There are 8 octal digits, so the radix (the number of queues needed for a radix sort) is 8. 9) Explain how quick sort works. Answer: Quick sort works by first selecting a pivot. The list is then divided into two sublists containing elements that are smaller than the pivot, and elements that are bigger than the pivot, with the pivot in the middle of these two lists. Then quick sort is recursively called on the two sublists. The base case of the recursion is a list with a single element, which is already considered sorted. 10) Explain how merge sort works. Answer: Merge sort works by dividing the list into two sublists and then recursively calling merge sort on them. After the sublists are recursively sorted, they are merged together using a merge subroutine. The base case of the recursion is a list with a single element, which is considered already sorted.

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 18 11) Write out the state while being sorted using the insertion sort algorithm: 91

6

3

55

110

8

1

703

Answer: 6

91

3

55

110

8

1

703

3

6

91

55

110

8

1

703

3

6

55

91

110

8

1

703

3

6

55

91

110

8

1

703

3

6

8

55

91

110

1

703

1

3

6

8

55

91

110

703

1

3

6

8

55

91

110

703

12) Write out the state of the list while being sorted using the selection sort algorithm: 91

6

3

55

110

8

1

703

Answer: 1

6

3

55

110

8

93

703

1

3

6

55

110

8

93

703

1

3

6

55

110

8

93

703

1

3

6

8

110

55

93

703

1

3

6

8

55

110

93

703

1

3

6

8

55

93

110

703

1

3

6

8

55

93

110

703

13) Explain how radix sort works. Answer: Radix sort works by moving the elements of the list to queues based on the value of fields in the sort key. If the sort key is numeric, for example, then the fields are the digits, and the resulting sorted list should have the keys in numeric order. If the sort key is alphabetic, then the fields are letters of the alphabet, and the resulting sorted list should have the keys in alphabetic order. There is one queue for each possible value of the field. The elements are moved to the queues based on the least significant field of the sort key first, then by the next-least-significant field, and so on, until the last set of moves places the elements into queues according to the most significant field. By removing the elements from the lowest-valued queue first, then the next lowest-valued queue, and on, the elements will be retrieved in sorted order.

9.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 18 Use the following class declaration for questions 14) and 15) public class Frammis { private Integer quantity; private String name; // constructors, accessor, and mutator methods // go here } 14) Write the declaration of a class that implements the Comparator interface that would allow Frammis objects to be sorted by quantity. Answer: public class QuantityCompare implements Comparator<Frammis> { public int compare(Frammis f1, Frammis f2) { Integer quantity1 = f1.getQuantity(); Integer quantity2 = f2.getQuantity(); return quantity1.compareTo(quantity2); } } 15) Write the declaration of a class that implements the Comparator interface that would allow Frammis objects to be sorted by name. Answer: public class NameCompare implements Comparator<Frammis> { public int compare(Frammis f1, Frammis f2) { String name1 = f1.getName(); String name2 = f2.getName(); return name1.compareTo(name2); } }

10 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 19

Chapter 19: Trees Multiple Choice Questions: 1) A user has designed an interface for a binary tree abstract data type (ADT). Which method below requires knowledge of the purpose and organization of the binary tree in order to design an implementation? a) find b) add c) contains d) isEmpty e) size Answer: b Explanation: An add method requires detailed knowledge of the purpose and organization of the binary tree in order to determine where to add an element to the tree. 2) A tree in which every node can have at most n children is referred to as a __________________ tree. a) binary b) ternary c) n-ary d) general e) graph Answer: c Explanation: An n-ary tree is one in which all nodes can have at most n children. 3) Which of the following best describes a balanced tree? a) A balanced tree has all nodes at exactly the same level. b) A balanced tree has no nodes at exactly the same level. c) A balanced tree has half of the nodes at one level and half the nodes at another level. d) A balanced tree has all of the nodes within one level of each other. e) none of the above correctly describe a balanced tree. Answer: d Explanation: Although a tree that has all nodes at exactly the same level is balanced, not all balanced trees have this property. Therefore, choice A is not the best answer. Choice d is the best answer because it correctly defines a balanced tree. 4) A full binary tree of height n has _________________ leaves. a) 2n b) 3n c) 2n d) 2(n+1) e) 3(n+1) Answer: a Explanation: A full binary tree has exactly 2n leaves, since every leaf is at the same height, and every internal node has exactly 2 children. 1.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 19

5) Which of the following tree traversals traverses the subtrees from left to right and then visits the root? a) Preorder b) Inorder c) Postorder d) Level-order e) none of the above Answer: c Explanation: A postorder traversal visits the root after traversing both subtrees. 6) Which of the following traversals is not easily implemented recursively? a) Preorder b) Inorder c) Postorder d) Level-order e) all of the above are easily implemented recursively Answer: d Explanation: A level-order traversal is not easily implemented recursively. It is implemented iteratively using a queue. 7) Which of the following traversals is implemented using a queue as a supporting data structure? a) Preorder b) Inorder c) Postorder d) Level-order e) none of the above are implemented using a queue Answer: d Explanation: The level-order traversal is easily implemented using a queue. 8) One method of implementing a tree using an array involves storing the child of the element at the index n in the array at indexes ______________________________ . a) n+1 and n+2 b) 2n and 22n c) 2n+1 and 2n+2 d) n-1 and n-2 e) none of the above will work Answer: c Explanation: Choice c represents the most straight-forward and elegant solution to implementing a tree using an array.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 19 9) What property of the tree does its order specify? a) maximum height b) maximum number of leaves c) maximum number of internal nodes d) maximum number of edges e) maximum number of children per node Answer: e Explanation: The order of a tree represents the maximum number of children per node. 10) A balanced binary tree with m elements will have height ______________ . a) 2m b) 2m c) logm 2 d) log2 m e) none of the above Answer: d Explanation: In general, a balanced n-ary tree with m elements will have height logn m. 11) A _________________ can be used as the basis for an expert system. a) queue b) stack c) ternary tree d) 4-ary tree e) decision tree Answer: e Explanation: A decision tree can be used as the basis for an expert system. 12) Which of the following traversals visits the root before visiting the left and right subtrees? a) Preorder b) Inorder c) Postorder d) Level-order e) none of the above Answer: a Explanation: The preorder traversal visits the root before the subtrees

3 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 19 13) The find method to locate an element in a binary tree can be implemented a) iteratively b) recursively c) independently d) both a) and b) are correct e) all of a), b), and c) are correct Answer: d Explanation: Finding an element in a binary tree can be either an iterative process or a recursive process. 14) Which of the following traversals never visits the root? a) Preorder b) Inorder c) Postorder d) Level-order e) none of the above Answer: e Explanation: If an algorithm does not visit a node, it is not a traversal. 15) Which of the following traversals visits the nodes that are closer to the top of the tree before visiting those that are closer to the bottom? a) Preorder b) Inorder c) Postorder d) Level-order e) none of the above Answer: d Explanation: The level-order traversal visits each node at each level of the tree from the top to the bottom.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 19

True/False Questions: 1) In a tree, a node that does not have any children is called a leaf. Answer: True Explanation: A leaf is a node in a tree that does not have any children. 2) The height of a tree and the depth of a tree are different. Answer: False Explanation: Height and depth are synonyms in the context of trees. 3) A binary tree is a tree in which any node can have at most two children. Answer: True Explanation: In a binary tree, a node can only have two children (but it may have one child or zero children). 4) Since trees are nonlinear structures, it is impossible to implement them using an array. Answer: False Explanation: There are several different array-based implementations of trees. 5) The methods in the Binary Tree ADT all return references to elements. Answer: False Explanation: The find and the getRoot methods return references to elements. isEmpty and contains return true or false. Size returns an int. toString returns a String. The iterator traversal methods return references to Iterator objects. 6) There are four basic ways to traverse a tree, and they are all implemented recursively. Answer: False Explanation: There are four ways to traverse a tree, but a level-order traversal is not implemented recursively (it is implemented iteratively using a queue). 7) A decision tree cannot be used as the basis for an expert system. Answer: False Explanation: A decision tree can be used as the basis for an expert system. 8) In an inorder traversal, the elements of a tree are visited in order of their distance from the root. Answer: False Explanation: A level-order traversal visits the elements of a tree in order of their distance from the root. 9) In a postorder traversal, the root is the last element visited in the tree. Answer: True Explanation: A postorder traversal visits the right subtree, then the left subtree, and then the root. So the root is always the last element to be visited. 10) Recursive methods that work with binary trees are often implemented with a private support method. Answer: True Explanation: Methods in binary trees may have different behavior when the call is at the root level vs. at an internal or a leaf node. Using a private support method with different behavior and/or signature enables the code to address these different needs.

5 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 19

Short Answer Questions: 1) How many leaves will be contained in a full binary tree of height 5? Answer: A full binary tree of height 5 will contain 25 = 32 leaves. 2) What does it mean for a tree to be balanced? Answer: In a balanced tree, all of the leaves are at the same level or at least within one level of each other. 3) If a tree has order 4, what does this mean? Answer: In a tree of order 4, all nodes must have 4 or fewer children. 4) Explain the implementation of a level-order traversal of a tree. Answer: The implementation of a level-order traversal of a tree involves a queue data structure. The main part of the algorithm dequeues a node from the queue, enqueues its left and right child, and then visits the node. The first step of the algorithm enqueues the root, and it continues until the queue is empty. 5) Explain the implementation of a postorder traversal. Answer: A postorder traversal of a tree is a recursive algorithm. The algorithm performs a postorder traversal on the left subtree (if it exists), and then performs a postorder traversal on the right subtree (if it exists). Finally it visits the root node. 6) Consider the following tree structure. A /

\

B / D

C \

E

\ F

In what order will the nodes be visited using a postorder, a preorder, an inorder, and a level-order traversal? Answer: Postorder – D, E, B, F, C, A; Preorder – A, B, D, E, C, F; Inorder – D, B, E, A, C, F; Level-order – A, B, C, D, E, F 7) Explain how a binary tree can be implemented using an array. Answer: A binary tree can be implemented using an array by storing the left child of the element at index n at index 2n+1 and 2n+2. This makes finding the children of a node a simple computation.

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 19 8) Suppose we are implementing a binary tree as a linked structure of BinaryTreeNode objects. Write a method that will print out all of the nodes of tree via a preorder traversal. You may assume that the class has a reference to a BinaryTreeNode object called root. In addition, your method may take a reference to a BinaryTreeNode object as a parameter. Answer: public void preorder(BinaryTreeNode root) { System.out.println(root.getElement()); if(root.getLeftChild() != null) preorder(root.getLeftChild()); if(root.getRightChild() != null) preorder(root.getRightChild()); } 9) Suppose we are implementing a binary tree as a linked structure of BinaryTreeNode objects. Write a method that will print out all of the nodes of tree via an inorder traversal. You may assume that the class has a reference to a BinaryTreeNode object called root. In addition, your method may take a reference to a BinaryTreeNode object as a parameter. Answer: public void inorder(BinaryTreeNode root) { if(root.getLeftChild() != null) inorder(root.getLeftChild()); System.out.println(root.getElement()); if(root.getRightChild() != null) inorder(root.getRightChild()); } 10) What is a decision tree? Answer: A decision tree is a tree where the nodes represent questions, and the paths from the nodes represent potential answers to the question. They can be used as the basis for an expert system. 11) What is the root of a tree? Answer: The root of the tree is the unique node in the tree that does not have a parent node. It is at the top of the hierarchy, at depth 0. 12) What are the leaves of a tree? Answer: The leaves of a tree are the nodes in the tree that have no children. 13) What is a disadvantage of implementing a tree as an array using computed links? Answer: The biggest disadvantage of this method of implementing a tree is that if the tree is not full, space is wasted. In particular, there may be many indexes in the array that contain no elements, but the space for elements has already been allocated. In a linked implementation of a tree, this is not a problem.

7.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 19 14) What are the issues involved in implementing an add or a remove method for a binary tree? Answer: A designer must know the purpose and the organization of the binary tree in order to know how to add an element to the tree. Considerations include how to traverse the tree to determine the location of the new element, and any rearrangement of the elements in the tree that may result. Similar knowledge is needed when deleting an element from a binary tree. The organization of the tree must be maintained. Rearrangement of links between elements depends on whether the element being removed is a leaf, an internal node, or the root. 15) What differences can there be between a complete binary tree and a full binary tree? Answer: A full tree is a complete tree, but a complete tree may not be a full tree. In particular, every non-leaf node in a complete binary tree may not have exactly two children.

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 20

Chapter 20: Binary Search Trees Multiple Choice Questions: 1) A _____________________ is a tree whose elements are organized to facilitate finding a particular element when needed. a) full tree b) complete tree c) binary tree d) search tree e) none of the above Answer: d Explanation: A search tree is a tree whose elements are organized to facilitate finding a particular element when needed. 2) In a binary search tree, the elements in the right subtree of the root are __________________ the root element. a) greater than b) less than c) greater than or equal to d) less than or equal to e) equal to Answer: c Explanation: The elements in the right subtree of the root are greater than or equal to the root element. 3) In a binary search tree, the elements in the left subtree of the root are __________________ the root element. a) greater than b) less than c) greater than or equal to d) less than or equal to e) equal to Answer: d Explanation: The elements in the left subtree of the root are less than the root element. 4) When adding a new element to a binary search tree, the element is added as a(n) ______________. a) internal node b) subtree c) leaf d) root e) none of the above Answer: c Explanation: An element added to a binary search tree is added as a leaf.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 20 5) A binary search tree that is highly unbalanced is called a ________________ tree. a) full b) complete c) degenerate d) unsearchable e) none of the above Answer: c Explanation: A binary search tree that is highly unbalanced is called a degenerate tree. 6) When removing an element from a binary search tree, we must always ______________________. a) make sure that the new tree is a binary search tree b) build a new tree c) find its inorder successor d) remove all of its children e) An element should never be removed from a binary search tree. Answer: a Explanation: When removing an element from a binary search tree, it is important that the resulting tree is a binary search tree. 7) When removing an element from a binary search tree that is a leaf, ______________ will ensure that the resulting tree is still a binary search tree. a) replacing it with its only child b) replacing it with its inorder successor c) simply deleting it d) all of the above e) neither a, b, nor c Answer: c Explanation: If the element that we wish to remove is a leaf, then simply deleting it will ensure that the resulting tree is still a binary search tree. 8) When removing an element from a binary search tree that has a single child, _____________________ will ensure that the resulting tree is still a binary search tree. a) replacing it with its only child b) replacing it with its inorder successor c) simply deleting it d) all of the above e) neither a, b, nor c Answer: a Explanation: Replacing the element with its only child will guarantee that the resulting tree is a binary search tree.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 20 9) When removing an element from a binary search tree that has two children, _______________________ will ensure that the resulting tree is still a binary search tree. a) replacing it with its only child b) replacing it with its inorder successor c) simply deleting it d) all of the above e) neither a, b, nor c Answer: b Explanation: Replacing it with its inorder successor will ensure that the resulting tree is a binary search tree. 10) Finding an element in a balanced binary search tree that contains n elements requires _____________________ comparisons. a) O(1) b) O(n) c) O(2n) d) O(log2 n) e) none of the above Answer: d Explanation: If the search tree is balanced, then finding an element only requires a number of comparisons logarithmic in the number of elements contained in the tree. 11) In the worst case, a general binary search tree could require __________________ comparisons to find an element. a) O(1) b) O(n) c) O(2n) d) O(log2 n) e) none of the above Answer: b Explanation: If the elements of a binary search tree are inserted in increasing or decreasing order, then finding an element will require a number of comparisons that is linear in the number of elements. 12) If a binary search tree becomes unbalanced after an element is added, it is sometimes possible to efficiently rebalance the tree by ___________________ . a) using left and right rotations b) selecting a leaf node to use as a new root c) reconstructing the tree from scratch d) all of the above e) it is impossible to rebalance a tree efficiently Answer: a Explanation: Left and right rotations are useful in rebalancing a tree.

3 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 20 13) Adding an element to a binary search tree requires that the element must a) be an int b) have a value that is in between the smallest and the largest value already in the binary search tree c) be Comparable d) have a positive value e) none of the above Answer: c Explanation: The basis of adding an element to a binary search tree is comparing the element to the elements that are already in the tree to determine the correct location for the new element. For this reason, elements must be Comparable, that is, they must implement the Comparable interface. 14) What is returned when a node to be removed from a binary search tree is not present in a tree? a) nothing b) the root element c) the element whose search value is closest to the one that should be removed. d) the parent element of the node being removed e) none of the above Answer: a Explanation: An exception is thrown if a remove operation is attempted and the element to be removed is not found in the binary search tree. In this situation, no element is returned. 15) The balance factor of a node in an AVL tree is a) the number of nodes below it b) the number of nodes above it c) the height of its right subtree minus the height of its left subtree d) the depth of the node from the root e) always positive Answer: c Explanation: An AVL tree maintains a balance factor for every node in the tree. The balance factor is computed by subtracting the height of the left subtree from the height of the right subtree. The balance factor is used to determine when a tree needs to be rebalanced.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 20

True/False Questions: 1) A binary search tree is always a full tree. Answer: False Explanation: A binary search tree is not necessarily a full tree. 2) Finding an element in a binary search tree always requires O(log 2 n) comparisons. Answer: False Explanation: In a degenerate binary search tree, finding an element may require O(n) comparisons in the worst case. 3) In a binary search tree, a new element is always added as a leaf. Answer: True Explanation: The new element will always be added as a leaf in a binary search tree. 4) In a balanced binary search tree, adding an element always requires approximately O(log 2 n) steps. Answer: True Explanation: Adding an element to a binary search tree requires as many steps as finding an element. Since adding finding an element in a balanced binary search tree always requires O(log 2 n) steps, adding an element does as well. 5) In a binary search tree, the elements in the right subtree of the root are always larger than the element stored at the root. Answer: False Explanation: The right subtree of the root may contain elements that are equal to the root. 6) Left and right rotations can be used to rebalance an unbalanced binary search tree. Answer: True Explanation: In some cases, a binary search tree can be rebalanced by a left or a right rotation. 7) An AVL tree is often implemented so that a node contains a reference to its parent node. Answer: True Explanation: AVL trees may need to rebalance a subtree after an addition of a node or the removal of a node. The rebalancing may need to be done from the point of addition or removal back to the root of the tree. For this reason, each node in an AVL tree needs to be able to refer to its parent node. 8) An ordered set of elements can be maintained using a linked list or a binary search tree. It is generally faster to locate an element in a binary search tree than it is to locate an element in a linked list. Answer: True Explanation: Searching in a linked list is O(n), while searching in a balanced binary search tree is O(log n). 9) A Red/Black tree is often implemented so that a node contains a reference to its parent node. Answer: True Explanation: Like an AVL tree, a red/black tree may need to rebalance a subtree after the addition of a node or the removal of a node. The rebalancing may need to be done from the point of addition or removal back to the root of the tree. For this reason, each node in a red/black tree needs to be able to refer to its parent node. 10) The most efficient binary search trees are balanced. Answer: True Explanation: A balanced binary search tree requires O(log n) steps to find or to add an element.

5 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 20

Short Answer Questions: 1) What is a binary search tree? Answer: A binary search tree is a binary tree that has the binary search property. That means that for every subtree rooted by node n, all of the elements in the left subtree are less than the element stored at n, and all the elements in the right subtree are greater than or equal to the element stored at n. 2) Explain how to add an element to a binary search tree. Answer: Elements are added to a binary search tree as leaves. The add operation follows a path in the tree as it would if it were performing a find operation, and it adds the new element as a child of the leaf that it finds (as left child if it is less than or a right child if it is greater than or equal to). 3) Describe how to find an element in a binary search tree. You may use English sentences or pseudocode. Answer: Let x be the element that is being searched for. The algorithm begins by checking to see if the root is equal to x. If it is, it halts, returning a reference to the element at the root. Otherwise it compares x to the root. If the root is not a leaf and x is larger, then it recursively calls the method on the right subtree, and if it is smaller, it recursively calls the method on the left subtree. If the node is a leaf, it returns null, meaning that the item is not found. Example Pseudocode Answer: find(x, root) : if(x = root.getElement()) return root.getElement() else if (x < root.getElement() and root.hasLeftChild()) return find(x, root.getLeftChild()) else if ( x > root.getElement() and root.hasRightChild()) return find(x, root.getRightChild()) else return null 4) Draw a binary search tree that results from inserting the following elements: 12, 16, 9, 1, 15, 13 Answer: 12 9 / 1

/

\ 16 / \ 13 15

5) What is the inorder successor of a node in a binary search tree? Answer: The inorder successor of a node in a binary tree is the next element that is visited in an inorder traversal. In a binary search tree, this is the next element in the ordering of the elements of the binary search tree. 6) What is special about the order in which the nodes are visited in an inorder traversal of a binary search tree? Answer: An inorder traversal on a binary search tree results in the elements being visited in ascending, sorted order. 6.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 20

7) Do the find and add operations on a binary search tree always require at most O(log 2 n) comparisons? If so, why? If not, why not? Answer: The answer is ‘no’. If the tree is degenerate, meaning highly unbalanced, then a find or an add operation may require more than O(log2 n) comparisons. In the worst case, these operations will require a linear number (O(n)) of comparisons. 8) What can make a balanced binary search tree become unbalanced? Answer: Adding a node to, or removing a node from, a balanced binary search tree may result in a tree that is no longer balanced. 9) In an AVL tree, each node keeps track of its own balance factor. What value(s) of the balance factor will trigger a rebalancing? Answer: The balance factor of a node is the difference in the heights of its left- and right subtrees. If the balance factor is greater than 1 or less than -1, then the subtree rooted at that node must be rebalanced. 10) Explain the process of removing an element from a binary search tree. Answer: When an element is removed from a binary search tree, the resulting tree must also have the binary search property. Three cases must be considered. If the element is a leaf node, it can be safely deleted. If the element is a node that has exactly one child, the child can replace the removed element. If the element has two children, the inorder successor of the node must be found, and it can be used to replace the deleted node. 11) Describe the steps involved in performing a right rotation on a node in a binary search tree. Answer: Let the root node be denoted root, and denote its right child as right and its left child as left. First, we make left the new root element. Next, we make root the right child element of left. Finally, we make the former right child of left the left child of root. 12) Why is it important to keep a binary search tree balanced? Answer: A balanced binary search tree has the most efficient add and find operations. They will require O(log 2 n) comparisons in the worst case. 13) If a node in an AVL tree requires rebalancing, what other nodes in the tree may also require rebalancing? Answer: If a node in an AVL tree requires rebalancing, then every node from this node up to the root of the tree must be checked and rebalanced if necessary. For this reason, each node in an AVL tree maintains a link to its parent node.

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 20 14) Consider the following binary search tree. 12 / /

9

1

\ 16 / \ 13 15

Show the tree that is the result of removing the following elements (in order): 13, 16, 12. Answer: /

15

9 / 1 15) Suppose we have a class called BinaryTree that includes a find method. If we extend the class to create a BinarySearchTree class, should we override the find method or use it as is? Explain. Answer: The find method in the BinaryTree class method will not be as efficient as it could be, since it is not using the binary search property. Given that the primary reason for using a binary search tree is being able to quickly find elements via the binary search property, it would only make sense to override the find method.

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 21

Chapter 21: Heaps and Priority Queues Multiple Choice Questions: 1) In a heap with_______ nodes, the next element to be added to the heap will start a new level in the heap. a) 2 b) 3 c) 4 d) 5 e) 6 Answer: b Explanation: If a heap has 3 nodes, then it is a full tree. Level 2, the last level in the heap, has 2 nodes. Adding an element means that a new node will be created that is a child of the left-most Level 2 node. 2) When the removeMin operation removes the minimum element from a minheap, that element is initially replaced by its a) left child b) right child c) the smaller of the left or the right child d) the element in the last node that was added e) none of these is correct Answer: d Explanation: The root node of a minheap has the smallest element. When removing the root of a minheap, the root is initially replaced by the rightmost element at the last level of the tree. This is the element that is in the last node that was added to the tree. After making this element the root of the tree, the element is compared against its smallest child and exchanged if necessary, to maintain the proper parent-child relation. The comparisons continue until the correct position for this element is determined. 3) Maintaining a heap as a complete binary tree means that a) the tree is unbalanced b) leaf nodes are created at the lowest level in left- to right order c) the tree is degenerate d) every leaf node is at the same level e) none of the above Answer: b Explanation: A complete tree is balanced, so a) cannot be correct. A degenerate tree is not balanced and thus is not complete, so c) cannot be correct. Choice d) is part of the definition of a full tree. Choice b) represents an important component of the description of a complete tree.

1 Pearson © 2017


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 21 4) A(n)____________________ is a collection that is ordered using two ordering rules a) priority queue b) interface c) exception d) stack e) none of the above Answer: a Explanation: A priority queue is a collection that is ordered by two ordering rules. One, the priority, is used to determine which items are addressed first. Second, items with the same priority are ordered using a first-in, first-out principle, and are thus queued. 5)

Adding an element to a heap is ______________ a) O(1) b) O(n) c) O(log n) d) O(n log n) e) none of the above

Answer: c Explanation: The addElement operation is O(log n). This is true in both a link implementation and in an array implementation of a heap. 6) A priority queue can be implemented using a) a list of queues b) a minheap c) a stack d) both a) and b) are correct e) all of a), b), and c) are correct Answer: d Explanation: A priority queue can be implemented using a list of queues, where each queue corresponds to a particular priority. It can also be implemented using a minheap, where the compareTo method for each element is designed to compare priorities of elements first, then to compare the order of the elements second if the priorities are the same. 7) Sorting an array using a heap sort means that an element removed from a minheap will be a) the next array element in descending order b) the next array element in ascending order c) re-inserted into its proper position in the minheap d) an array element, but its position in the sorted array is not known e) None of these is true Answer: b Explanation: If the elements of an array are added to a minheap, then the removeMin operation will remove the next smallest element in the heap. As elements are removed using removeMin, the removed elements are in ascending order.

2 Pearson © 2017


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 21 8) Heap sort is an __________ sorting algorithm. a) O(1) b) O(n) c) O(n log n) d) O(𝑛2 ) e) none of the above Answer: c Explanation: Heap sort involves adding each element to a heap, then removing each element from the heap. Adding and removing are each O(log n) operations, and there are n elements to be added and removed, so heap sort is O(n log n). 9) Which of the following is not part of the operation of adding an element to a heap? a) Add the node for the element at the appropriate location in the heap b) Reorder the heap to maintain the proper order of the nodes. c) Rebalance the heap. d) Reset the pointer to the last node that was added to the heap. e) All of these are part of the operation of adding an element to a heap. Answer: c Explanation: A heap is maintained as a balanced binary tree by adding new nodes at the same level in left to right order, and by going to a new level only when the prior level is full. There is no rebalancing needed. 10) In a minheap in which all elements are distinct, the largest element is at a) the root of the tree b) the next level below the root of the tree c) a node that is not a leaf node d) a leaf node of the tree e) The largest element could be anywhere in the tree. Answer: d Explanation: In a minheap in which all elements are distinct, each node is smaller than its children. The children are larger than the parent, so the elements get larger as the levels increase. The largest element is going to be at a leaf node. Since there are no elements larger than it, it cannot have any children. 11) When discussing a heap, the phrase “the last leaf in the tree” refers to a) the rightmost leaf at the last level of the tree b) the leftmost leaf at the last level of the tree c) the node that is farthest from the root of the tree d) the node with the largest value e) the node that will be the last one to be removed from the tree Answer: a Explanation: The “last leaf in the tree” refers to the last node that was added to the tree. Nodes are added from left to right at the same level until a level is filled, then a new level is started. For this reason, the last node that was added to a tree – “the last leaf in the tree” – is the rightmost leaf at the last level of the tree. This may in fact be the node that is farthest from the root of the tree if this is the first leaf of a new level, but that is not always going to be the case.

3 Pearson © 2017


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 21 12) Which of the following is not a heap operation when working with a maxheap? a) addElement b) findMax c) removeMax d) removeElement e) All of these are heap operations that can be used when working with a maxheap. Answer: d Explanation: The only remove operation for a maxheap is removeMax, to remove the largest element in the heap. There is no general operation to remove an element that is not the largest (for a maxheap) or the smallest (for a minheap). 13) A ____________________ is a complete binary tree in which each element is greater than or equal to both of its children. a) binary search tree b) stack c) full tree d) maxheap e) none of the above Answer: d Explanation: A maxheap is a complete binary tree in which each element is greater than or equal to both of its children. 14) In a maxheap, the largest element in the structure is always ______________________ . a) a leaf b) an internal node c) the root d) the left child of the root e) the right child of the root Answer: c Explanation: In a heap, the root is always the largest element in the tree. 15) Which of the following is always true when adding an element to a heap? a) The new element will always be a leaf. b) The new element will always be the root. c) The new element will always be an internal node. d) The new element will always have 2 children. e) none of the above is always true Answer: e Explanation: When adding an element to a heap, it can end up anywhere in the tree.

4 Pearson © 2017


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 21

True/False Questions: 1) The difference between a minheap and a maxheap is the order of the nodes between parents and children. Answer: True Explanation: In a minheap, each node is less than or equal to its left and its right child. In a maxheap, each node is greater than or equal to its left or right child. 2) As an Abstract Data Type, a Heap interface inherits from a BinaryTree interface Answer: True Explanation: A heap is implemented as a binary tree. The Binary Tree interface does not define operations for adding elements to or removing elements from a binary tree, so a heap can provide these operations in its interface without conflict. 3) When adding an element to a heap, the element is initially added as a root node. Answer: False Explanation: The element is initially added as a leaf node. It is then compared to its parent and exchanged if necessary. This comparison with its parent and exchanging continues until the element is in its proper location. 4) In a minheap, the findMin operation is O(1). Answer: True Explanation: The findMin operation returns a reference to the smallest element in a minheap. Since the smallest element in a minheap is at the root, the process of locating this element takes constant time. 5) A school sets up the following schedule for students to register for classes for next term: students in the Senior class register on Monday, Juniors on Tuesday, Sophomores on Wednesday, and finally students in the Freshman class on Thursday. On each day, students of the appropriate class register in first come, first served order. This is an example of a set of priority queues. Answer: True Explanation: Each day is a different priority. Within a day, students are processed in the order in which they arrive at the registration location. 6) One of the benefits of implementing a heap with links is that a node does not need a link to its parent. Answer: False Explanation: Adding an element to a heap requires traversal of the path from the leaf node holding the added element to its parent, and potentially to its parent’s parent, etc., to locate the appropriate place for the added element. Each node needs to have a reference to its parent in order to support this traversal. 7) In a maxheap, the largest element is always the root. Answer: True Explanation: In a maxheap, the children of an node always contain elements that are smaller than the element in the parent node. Therefore, the root always contains the largest element in a heap. 8) Whenever a new element is added to a maxheap, it always becomes the root. Answer: False Explanation: A new element added to a maxheap may or may not become the root. 9) A heap sort sorts elements by constructing a heap out of them, and then removing them one at a time from the root. Answer: True Explanation: A heap sort uses the heap property to sort elements by constructing a heap out of them, and then removing them one at a time.

5 Pearson © 2017


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 21 10) Implementing a heap using an array simplifies the management of the last added node in the heap. Answer: True Explanation: When using an array to implement a heap, the last added node is the last element that was added to the array. It is in the last occupied position in the array.

6 Pearson © 2017


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 21

Short Answer Questions: 1) In what ways is a heap different from a binary tree? Answer: A heap is a complete binary tree. Binary trees in general do not have to be complete. A heap also has an ordering applied to the elements stored in the tree, in which the children of an element are larger than or equal to (in the case of a minheap) or smaller than or equal to (in the case of a maxheap) the parent element. Binary trees may have an order applied to the elements, for example, a binary search tree, but ordering is not an inherent property of a binary tree. 2) What properties does a heap share with a binary tree? Answer: A heap is a binary tree, in that it is a series of nodes in which each node has links to 0, 1, or two other nodes, and such that each node has at most one other node linking to it. It uses the methods defined in the Binary Tree interface. 3) Where is the largest element in a minheap found? Answer: In a minheap, each node has an element that is smaller than or equal to its children. The largest element will be an element that has no children, since there is no element that is larger than it, so the largest element will be in a leaf node. 4) What steps are involved in removing an element from a minheap? Answer: The removal operation for a minheap is removeMin, which removes the smallest element from the minheap. The smallest element is at the root. A replacement element for the root node must be determined to maintain the property of being a tree. The element that is in the last node that was added to the tree is promoted to the root position in the tree, which preserves the tree property. This element is by definition a leaf node, and it can be moved without concern for its children. Next, the new root element must be compared against its smallest child and exchanged if necessary to preserve the relation between nodes in a minheap. This comparison / exchange process continues until no exchange is necessary, at which time the element is in its correct position in the tree, and the minheap relation is restored. 5) When comparing an array-based implementation of a heap against a linked implementation, which is more efficient? Answer: The two implementations have the same complexity. The addElement and the removeMax / removeMin operations are O(log n) in either implementation. The array implementation is able to save a few steps due to the organization of the nodes in the array, but these steps are a constant-time consideration, and do not significantly impact the efficiency of the implementation. 6) A heap is a complete binary tree. What is required for the tree to be complete? Answer: Complete means that a tree is balanced, which means that all leaf nodes are within one level of each other, and that all of the leaves at the lowest level are at the left side of the tree. 7) A heap is a binary tree. What operations does a heap add to the BinaryTree interface? Answer: A BinaryTree interface contains operations that are appropriate for a general binary tree. The BinaryTree inrterface does not define operations for adding or removing elements from a binary tree, as these may be related to a property of the tree such as the order of the nodes. The Heap interface adds operations to add an element, to locate the smallest (minheap) or largest (maxheap) element, and to remove the smallest (minheap) or largest (maxheap) element.

7 Pearson © 2017


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 21 8) What is a maxheap? Answer: A maxheap is a binary tree in which for each node, the children of the node contain elements that are less than or equal to the element in the parent node. 9) Explain how an element is added to a maxheap. Answer: An element is added to a heap as a leaf, and then it is moved up the tree until the tree has the heap property again. This means it is moved up the tree until it is smaller than its parent node, and all of its children are smaller than it. 10) What is a priority queue? Answer: A priority queue is a collection in which each element has a priority associated with it. Elements with higher priority are processed before elements with a lower priority. Within a given priority, elements are processed in a first come, first served order. Within a given priority, the elements are arranged in a queue. Each priority can be thought of as having its own queue. 11) How can a heap be used to implement a priority queue? Answer: Elements in a heap must be Comparable, which means that they have a compareTo method. The compareTo method can be written so that the element that has greater priority is ‘greater than’ an element with lower priority. If the priorities are the same, then the positions in the queue determine the resulting relation between the elements. This compareTo method can then be used to add elements to a maxheap. The element at the root of the maxheap is the element with the highest priority, or it is the next element in the queue if there are other elements with the same priority. When it is removed, the resulting heap will have the next appropriate element as the root. 12) In an array implementation of a heap, which element is the root of the binary tree? Answer: The first element, at subscript 0, is the root of the binary tree representing a heap. 13) Explain how heap sort works. Answer: First, a maxheap is created on the elements that need to be sorted. Next, the elements are removed, one-byone, from the root. The elements will be removed from the heap in descending order, and therefore they can be sorted. To sort the list in ascending order, a minheap can be used instead. 14) What is the complexity of heap sort? How is it calculated? Answer: The complexity of heap sort is determined by the complexity of the two operations, addElement and removeMin /removeMax. Each of these operations is O(log n) for a single element, and are thus O(n log n) for the entire set of elements being sorted. Taken together, the complexity of heap sort is O(n log n).

8 Pearson © 2017


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 21 15) An array is sorted into ascending order. The following sequence of steps will put the array into descending order: 1) 2)

Copy the array into a maxheap Remove the elements from the maxheap and put them in order into the array.

Is this the best way to put the array into descending order? Answer: No. The sequence of steps describes a heap sort, which is O (n log n). A more efficient way to reverse the order of the sort of the array would be to exchange/swap the first and last elements, the second and one less than the last, etc. 𝑛 Each exchange takes constant time, and there are exchanges performed for an array of size n, so this operation would be O(n). 2 For a large array, this could be substantially faster than using a heap sort.

9 Pearson © 2017


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 22

Chapter 22: Sets and Maps Multiple Choice Questions: 1) A set is a) an ordered list of elements b) a collection of elements with no duplicate elements c) a collection whose elements have two important attributes, keys and values d) a collection of elements, each of which reference 0, 1, or 2 other elements in the collection e) a collection of elements all of which are the same Answer: b Explanation: Choice b) is the definition of a set. Choice c) is the definition of a map. Choice d) is part of the definition of a binary tree. 2) A map is a) an ordered list of elements b) a collection of elements with no duplicate elements c) a collection whose elements have two important attributes, keys and values d) a collection of elements, each of which reference 0, 1, or 2 other elements in the collection e) a collection of elements all of which are the same Answer: c Explanation: Choice c) describes a map. Choice b) describes a set. Choice d) is part of the definition of a binary tree. 3) In a map, a) the values are unique b) the keys are unique c) the size of each element is unique d) the references are unique e) the exceptions are unique Answer: b Explanation: The elements of a map contain key-value pairs in which each key in the set is unique. The values in a set need not be unique. 4) Which operation below is not part of the Map interface? a) Given a key, determine the value associated with the key in a map. b) Determine if a key is in an element in a map. c) Determine if a value is in in an element in a map. d) Given a value, determine the key that is associated with the value in a map. e) All of these operations are part of the Map interface Answer: d Explanation: It is not possible to determine the key that is associated with a given value as a map operation. Choices a), b), and c) are all operations that are part of the Map interface.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 22 5) When implementing a set or a map using hashing, the two parameters for the constructor of the collection are the ___ and the ___ of the hash table a) minimum size, maximum size b) starting subscript, ending subscript c) initial capacity, load factor d) number of rows, number of columns e) none of the above Answer: c Explanation: The initial capacity determines the starting size of the hash table. The load factor is used to determine the number of elements must be in the hash table before the table is resized. 6) A perfect hashing function a) maps elements of the same size to the same position in the hash table b) maps elements to the next sequentially available space in the hash table c) maps elements of the same class to the same position in the hash table d) maps each element to a unique position in the hash table e) is not possible Answer: d Explanation: A perfect hashing function is one in which there are no collisions. Each element is mapped to a unique position in the hash table. 7) The load factor of a hashing function determines a) the limit on the size of the elements that are added to the hash table b) how full a hash table must be before it is resized c) the size of the argument to the hashing function d) how quickly an element can be located in the hash table e) none of these is correct Answer: b Explanation: The load factor indicates the percent of the capacity that must be in the hash table before it is resized 8) A hashCode method returns a(n) a) int b) double c) key d) value e) String Answer: a Explanation: The hashCode method returns an int, which is used to locate the position of an object in the hash table.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 22 9) The TreeMap and TreeSet classes use a ________ for the underlying data structure. a) heap b) double-ended queue c) red/black tree d) circular queue e) full tree Answer: c Explanation: A red/black binary search tree is used as the underlying data structure to hold the map or the set elements of TreeSet and TreeMap classes. 10) In a set, the ______ must be unique. a) data types b) keys c) values d) elements e) none of the above Answer: d Explanation: Sets do not have duplicate elements, so each element is unique. Choice b) is the correct answer if the collection is a map instead of a set. 11) A(n) ______ occurs when two elements have the same resulting value from the hashing function. a) collision b) collusion c) coercion d) capacity e) instantiation

function.

Answer: a Explanation: A collision occurs when two elements are mapped to the same location in the hash table by the hashing

12) Which of the following pairs of data items could be stored in a map? a) a student’s name and the student’s student ID number b) a student’s name and the student’s grade point average (GPA) c) a student’s name and the student’s year in school d) a student’s name and the name of the dormitory in which the student lives e) None of these pairs are appropriate for storage in a map. Answer: a Explanation: There may be two students who have the same name, but there should not be two students who have the same student ID number. The student ID number can be used as the key, and the student name can be used as the value. In the other choices, neither of the fields in the pair is unique and thus cannot be used for the key field.

3 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 22

True/False Questions: 1) A set is an ordered collection of elements. Answer: False Explanation: A set is an unordered collection. There is no positional relation between the elements in a set. 2) In a map, each value has a unique key. Answer: False Explanation: In a map, the keys are unique, but the values are not necessarily unique. Each element has a unique key, but it is possible for different elements to have unique keys and the same value. 3) The elements in a map are unique. Answer: True Explanation: A map does not have duplicate entries, so each element in a map is unique. 4) The contains operation of the Set interface returns a count of the number of occurrences of an element in the set Answer: False Explanation: The contains operation determines if an element is present in a set. It returns true if the element is a member of a set and false if the element is not a member of a set. 5) When instantiating an implementation of a Map interface, a type must be supplied for both the key and for the value. Answer: True Explanation: The Map interface has two generic type parameters, one for the type of the key and another for the type of the value. When a map is created by instantiating a class that implements the Map interface, types for each of these must be supplied. 6) The primary purpose of a set is to determine if a particular element is a member of the set. Answer: True Explanation: The contains operation represents the primary purpose of a set, the determining whether a particular element is present in a set or not. 7) Set is not the only collection type that supports testing for membership. Answer: True Explanation: The List collection type also supports testing to see if an element is in a collection. However, sets are designed to perform this task efficiently. 8) Sets and maps can be implemented using either binary trees or by using a hashing function. Answer: True Explanation: Binary tree implementations use red/black binary search trees as the underlying data structure. A hashing function is used in conjunction with a hash table to store and access the elements in the map or the set. 9) A hashing function is a function that maps elements of a set or a map to other elements that are in the set or the map. Answer: False Explanation: A hashing function maps elements to locations in a hash table. 10) When implementing a map class or a set class using a tree data structure, a heap is used for the tree. Answer: False Explanation: A red/black binary search tree is used as the underlying data structure.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 22

Short Answer Questions: 1) What should the hashCode function return if it is passed the same object more than once? Answer: The hashCode function should return the same value for each of the calls. If it returned different values for the two calls, then it could not reliably locate an object in a hash table after it has been added to the table. 2) If the equals method indicates that two objects are not equal, then what should the hashCode function return for these objects? Answer: If the objects are not equal, the behavior of the hashCode function is undefined. It would be best if it returned different values for different objects. 3) Maps and sets are both collections of objects. In what ways are they different? Answer: A set is a collection in which the objects are distinct. It can be efficiently searched to determine if the set contains a particular object. A map contains objects that have keys and values. All of the keys in a map must be distinct, but the values may not be distinct. A map can be searched to determine if it contains a particular key or value, and to retrieve the value associated with a particular key. 4) The map collection has a ‘get’ operation. Why doesn’t the set collection have a ‘get’ operation? Answer: There is no purpose to a ‘get’ operation on a set. A set has a contains operation, which can be used to determine if the set contains a particular object. If contains returns true, then the object that was passed as an argument to contains is the same as the object that is in the set. 5) When implementing and instantiating a map, how many types must be supplied? Answer: Two. One of the types indicates the data type of the key. The other indicates the data type of the value. 6) A fastener company has products that are referenced by their names and by their part numbers. Here is a small sample list: name bolt nut washer screw bolt nut washer

part number a11b12 a11c12 a11d12 a12d12 b12b12 b12c12 b12d12

Based on this small sample list, explain how you would implement this information in a map. Answer: The part numbers appear to be unique, so the part number field is a good candidate for the key field. The product name is a good candidate for the value field. 7) When implementing a hashCode function, must the function make use of the entire object that it receives as an argument? Answer: No. The hashCode function takes an object as a parameter and returns a value that corresponds to a location in the hash table. If the definition of the class of the object is such that there is a key field in the object, then this field could be used by the hashCode function to determine the object’s location in the hash table. 5.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 22

8) What are the parameters that are passed to the constructor of the HashMap or the HashSet class? Answer: The parameters are used for the hash table. They are the initial capacity and the load factor. The initial capacity is the starting size of the hash table. The load factor is the percent of the hash table that must be filled before the hash table is resized. 9) What does it mean for a hashing function to be “perfect”? Is this a desirable property, or should it be avoided? Answer: A perfect hashing function is one in which each element in the collection is mapped to a unique location in the hash table. There are no collisions. If it can be achieved, this is a very desirable property. 10) A HashMap object is created with an initial capacity of 500 and a load factor of 0.8. How many elements are in the map when the hash table is resized? Answer: 500 x 0.8 = 400, so adding the 400th element to the map will trigger the resize operation on the hash table.

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 23

Chapter 23: Multi-way Search Trees Multiple Choice Questions: 1) A 2-3 tree is a form of a a) binary search tree b) multi-way search tree c) either a binary or a trinary search tree d) map e) set Answer: b Explanation: A 2-3 tree is a form of a multi-way search tree. It has similarities to a binary search tree, but it also has important differences. 2) Which of the following is true about a 2-3 tree? a) A node may contain more than one element b) A node may have more than two children c) A 2-node has 0 or 3 children d) A 2-node has 0 or 3 children e) All of these statements are true Answer: e Explanation: All of choices a) through d) are true statements about a 2-3 tree 3) How many levels apart are the leaf nodes in a 2-3 tree? a) 0 b) 1 c) 0 or 1 d) 0, 1, or 2 e) the number of levels is not specified Answer: a Explanation: All of the leaf nodes of a 2-3 tree are at the same level. 4) Which choice below represents the number of children that a node in a 2-3 tree can not have? a) 0 b) 1 c) 2 d) 3 e) All of these are possible numbers of child nodes in a 2-3 tree. Answer: b Explanation: A 2-node can have 0 or 2 children. A 3-node can have 0 or 3 children. No node can have a single child.

1 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 23 5)

A 2-3 tree contains a single element. How many nodes will the tree have after a new element is inserted? a) 0 b) 1 c) 2 d) 3 e) It is not possible to predict the number of nodes

Answer: b Explanation: If a 2-3 tree contains a single element, then that element is in the root node and the root node is a 2-node. When a new element is added, it is added to the root node and the root node becomes a 3-node. No new nodes are added when the second element is introduced to the 2-3 tree, so the number of nodes is 1, the root node. 6) How many elements can a 2-4 tree hold before it must have more than one node? a) 5 b) 4 c) 3 d) 2 e) The answer depends on the particular values of the elements. Answer: c Explanation: A 2-4 tree can have nodes that contain 1, 2, or 3 elements. Thus, the first three elements inserted into a 2-4 tree are all added to the root node. Inserting the 4 th element causes the root node to split, a new root node to be formed, and child nodes to be added. 7) 2-3 tree and 2-4 trees are examples of a) binary trees b) binary search trees c) heaps d) B-trees e) None of these is correct Answer: d Explanation: 2-3 trees and 2-4 trees belong to the general category of trees known as B-trees. 8) When working with different B-trees for a given number of elements, as the order of the B-tree goes up, the number of nodes in the B-tree tends to a) go down b) go up as well c) stay the same d) oscillate between two values e) none of the above Answer: a Explanation: The order of a B-tree determines the maximum number of elements per node. If the number of elements in a node increases and the number of elements in the tree is unchanged, then the number of nodes will tend to decrease.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 23 9) A 𝐵 + -Tree improves on a B-tree by offering a) fewer nodes b) more nodes c) sequential access to all elements of the tree d) fewer levels e) more levels Answer: c Explanation: A 𝐵+ -Tree maintains two copies of every element in an internal node, one at its location in the B-tree structure and the other in a corresponding leaf node. Leaf nodes also contain a link to the next leaf node. In this way, all of the elements of a 𝐵 + -Tree can be accessed sequentially without having to traverse the tree structure. 10) B-Trees were introduced to address which constraint in the design of efficient binary tree algorithms? a) the execution speed of the computer b) the version of the operating system that is installed c) sparsely populated trees d) problems in which all of the elements may not fit in memory at the same time e) None of these is correct. Answer: d Explanation: Secondary storage, primarily disk storage, is much slower to access (read from and write to) than primary storage. If the data for a problem is such that all of the elements cannot be in main memory at the same time, then a design in which multiple elements can occupy a node can reduce the number of times that a computer program has to access secondary memory while running. Reducing the access to secondary memory will result in a program that executes faster. 11) In a B-tree of order 6, each internal node other than the root node has at least ____ elements and at least ________ children. a) 6, 5 b) 5, 6 c) 6, 6 d) 3, 2 e) 2, 3 Answer: e Explanation: The minimum number of elements in an internal, non-root node in a B-tree of order 6 is 2. The number of children is one more than the number of elements, so the minimum number of children is 3. 12) A B-tree is a search tree. What is the efficiency of searching for an element in a B-tree? a) O(1) b) O(n) c) O(log n) d) O(n log n) e) O(𝑛2 ) Answer: c Explanation: Searching for an element in a B-tree is approximately the same as searching for an element in a balanced binary search tree. It is O(n log n).

3.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 23 13) The height of a 2-3 tree increases a) down from the leaf nodes b) when they use secondary storage c) up from the root node d) when an element is removed e) none of the above Answer: c Explanation: When the root node has to be split, the element with the middle becomes the new root node, and the resulting nodes that hold the other elements become children of the new root node. Adding a new root node adds a level to the tree, so 2-3 trees grow at the root. 14) When removing an element from a 2-3 tree, rotation and ______ may both be employed to maintain the properties of the B-tree. a) reducing the height of the tree b) increasing the height of the tree c) reflection d) reinsertion e) None of these is correct Answer: a Explanation: When removing an element from a 2-3 tree, the tree may no longer hold enough data to support the current height of the tree. For example, if the element at the root node is being removed and the root node is a 2-node with two children, then the children may be joined, with some reorientation of elements in children, in a 3-node to replace the root. When this happens, the overall height of the tree is reduced. 15) The non-leaf root of a B-tree of order m has a minimum of how many children? a) 0 b) 1 c) 2 d) m/2 e) None of these is correct Answer: c Explanation: If the root of a B-tree is a leaf node, then it has no children. If it has any children, it has at least 2. The maximum number of children it can have is m.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 23

True/False Questions: 1) In a 2-3 tree, each element is in its own node. Answer: False Explanation: If a node is a 3-node, then it contains 2 elements. 2) The root node of a 2-3 tree is always a 2-node. Answer: False Explanation: The root node is a 2-node when the first element is inserted, but it becomes a 3-node when the second element is inserted. It may be a 2-node or a 3-node at different times, depending on the elements that comprise the 2-3 tree. 3) Inserting an element into a 2-3 tree may add more than one node to the tree. Answer: True Explanation: If the leaf node at the point of insertion is a 3-node and the parent of this node is also a 3 node, then the tree may have several more nodes in it after nodes are split and elements are promoted. 4) The easiest element to remove from a 2-3 tree is an element that is in a 3-node that is a leaf node. Answer: True. Explanation: In this case, the element is removed and the 3-node becomes a 2-node. Since it is a leaf node, there are no adjustments necessary to account for child nodes. 5) A 2-4 tree extends the concept of a 2-3 tree by allowing a node to have 1, 2, or 3 elements and 0, 2, 3, or 4 children. Answer: True Explanation: In addition to a 2-node and a 3-node, a 2-4 tree has a 4-node, a node in which has 3 elements and 0 or 4 children. 6) The height of a 2-3 tree increases when an element is inserted. Answer: False Explanation: The height of a 2-3 tree will increase if an insert causes elements to be moved up all the way to the root node, and the root node was a 3-node before an element was moved up to it. There are other cases, though, where the height is unaffected. For example, if the insertion is into a leaf node that is a 2-node, then that node simply becomes a three node, and no new nodes are added to the tree. 7) Rotation may be used when deleting an element from a 2-3 tree to maintain the balance and properties of a 2-3 tree. Answer: True Explanation: If an element that is being deleted is the only element in a leaf node – that is, if the leaf node is a 2-node – then removing the element means that the node is no longer a valid node in a 2-3 tree. Rotating the elements by shifting them to other nodes, or reducing the height of the tree, are two ways in which the properties of a 2-3 tree can be maintained. 8) A 𝐵 + -Tree ensures that each non-root node in the tree is at least 2/3 full. Answer: False Explanation: The text of the problem describes a 𝐵 ∗ -Tree. A 𝐵 + -Tree is designed to provide sequential access to the elements in the tree without the overhead of tree traversal. 9) A linked representation of a B-tree is the best way to implement the collection, regardless of the amount of data to be held in the tree. Answer: False Explanation: A significant downside to a linked representation has to do with secondary storage. If the elements are objects, then the B-tree holds references to the objects, not the objects themselves. If objects are moved between primary and secondary storage, references will become stale. An array-based implementation of a B-tree may be a safer approach.

5.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 23

10) The middle child node of a 3-node in a 2-3 tree has one or two elements whose values are between the values of the elements in the parent node. Answer: True. Explanation: A 3-node has two elements and 0 or 3 children. If it has three children, then the elements in the leftmost child node are less than the smaller element in the parent node. The elements in the rightmost node are greater than or equal to the larger element in the parent node. The elements in the middle node are greater than or equal to the smaller element in the parent node and less than the larger element in the parent node.

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 23

Short Answer Questions: 1) Explain the difference between a 2-node and a 3-node. Answer: The terms 2-node and 2-node describe nodes in a 2-3 tree. A 2-node is a node that has a single element and has 0 or 2 children. It is most like a node in a binary tree, except that it cannot have a single child node. A 3-node is a node has 2 elements and 0 or 3 children. 2) When does a 2-node become a 3-node? Answer: A 2-node becomes a 3-node when it is a leaf node and an element is inserted into the 2-3 tree. Another way that a 2-node can become a 3-node is when an element is moved up from a child node in order to maintain the properties of a 23 tree. 3) Where are elements inserted into a 2-3 tree? Is your answer different if it is a 2-4 tree? What about if it is a B-tree? Answer: Like a binary search tree, elements are inserted at leaf nodes. This is true for any of the multi-way search trees listed above. 4) A new 2-3 tree is created. Explain the steps in inserting the following elements in this order into the initially empty tree: 13, 23, 17. Answer: The tree is initially empty. Inserting 13 involves creating a node for the root and inserting the element with 13 into it. The root element is now a 2-node and is a leaf node. The tree looks like this: (13) Inserting 23 into the tree containing 13 involves adding the element 23 to the leaf node containing 13. The root node is now a 3-node and is still a leaf node. The tree looks like this: (13 23) Inserting 17 into the tree involves locating the leaf node for the insertion, which is the root node, then adding it to the node. However, the node cannot hold another element, so it is split, and the middle element, 17, is moved up. A new root node is created and 17 is added to it, with the node containing 13 as the left node and the node containing 23 as the right node. The root node has 17. The tree looks like this: (17) / (13)

\ (23)

All nodes are now 2-nodes. The nodes containing 13 and 23 are leaf nodes.

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 23 5) Starting with the 2-3 tree from question 4), insert the elements 19 and 29. Sketch the tree after each insertion. Answer: In inserting 19, the first comparison is against 17, the root node. The next comparison is against 23, the right child of 17. The node containing 23 is a leaf node, so 19 is inserted into the node containing 23, making it a 3-node. The tree looks like this: (17) / (13)

\ (19 23)

Inserting 29 will lead to the same leaf node containing 19 and 23. However, inserting 29 violates the number of elements in a node, so the middle element, 23, is moved up to share the root node with 17. The tree looks like this: (17 23) / (13)

\ (19 29)

However, this still violates the rules for a 2-3 tree. The root node is a 3-node but it only has 2 children. The right leaf node is split into two leaf nodes. The resulting tree is now:

/ (13)

(17 23) | \ (19) (29)

The root is a 3-node and has 3 children. Each leaf node is a 2-node. 6) Starting with the 2-3 tree from question 5), remove the element 17. Sketch the tree. Answer: 17 is in a 3-node at the root of the tree. Removing 17 means promoting its inorder successor, 19. The tree looks like this: (19 23) / \ (13) (29) However, the root node is a 3-node with only 2 children. Rotate 19 down to the left child node, which makes the root of the tree a 2-node. The tree now looks like this: (23) / \ (13 19) (29)

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 23 7) Sketch the tree that results from removing element 35 from the tree below: (45) /

\

(30)

(60 82)

/

\

(22)

/

\

(35 50) (51 55)

(87)

Answer: 35 is in a 3-node that is a leaf node. Removing 35 reduces the node to a 2-node. As it is a leaf node, it has no children to address. The tree looks like this: (45) /

\

(30) / (22)

(60 82) \ (50)

/

\

(51 55)

(87)

8) An internal 4-node in a 2-4 tree has 3 elements and 4 children. The elements, in ascending order, are e1, e2, and e3. The child nodes, from left to right, are c1, c2, c3, and c4. What is the relation between the elements in the node and the children of the node? Answer: 𝑐1 < 𝑒1 ≤ 𝑐2 ≤ 𝑒2 ≤ 𝑐3 ≤ 𝑒3 ≤ 𝑐4 9) What event occurs to increase the height of a 2-3 tree? Answer: A level is added to a 2-3 tree when an element is inserted and elements are moved up in the tree in such a way that the root node must be split. Splitting the root node creates a new level to the tree. 10) What is the concern about secondary storage when working with a search tree? Answer: Primary storage or primary memory is the random-access memory that the program has to use. If there is not enough primary memory to hold all of the data for the tree, then the program will use secondary memory for some of it. Secondary memory is typically much slower than primary memory, and using it incurs more time. Using more time impacts the efficiency of an algorithm, so if a search tree can be designed in such a way as to minimize the use of secondary storage, it will be more efficient. 11) Are there improvements on the concept of a B-tree? Answer: There are two variations on B-trees that improve aspects of their use. One, 𝐵 ∗ -trees, has a higher minimum capacity of elements in each node, which may reduce wasted space in some implementations. Another, 𝐵 + -trees, addresses issues with sequential access. 𝐵 + -trees allow quick access to elements in order, but at the cost of data duplication and additional overhead to manage duplicate copies of elements.

9 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 23 12) What issues need to be considered when designing a linked implementation of a B-tree? Answer: The primary issue is whether all of the tree will fit in primary storage, or if secondary storage will need to be employed. If the use of secondary storage is a possibility, then a linked implementation may not be ideal. The problem with linked storage is due to the links to the objects that represent the elements in the B-tree. If the elements are moved back and forth from primary to secondary storage, then the links – the addresses where the object are – may not be current and may become stale. 13) What is involved in using a B-tree as a search tree? Answer: Searching for a value in a B-tree first involves locating the node that contains the element. Once the node is found, the next part is locating the element in the node. 14) In a B-tree of order m, how many elements can be inserted into the tree before a new node is created? Answer: In a B-tree of order m, each node can hold up to m-1 elements. The first m-1 elements inserted into the tree will all be in the root node. When the 𝑚𝑡ℎ element is inserted, it will require the root node to be split, which will lead to the creation of additional nodes. 15) What is the maximum number of elements that can be held in a two-level B-tree of order 4? Answer: A B-tree of order 4 has nodes that can hold 3 elements and have 4 children. If the tree has two levels, then the first level is the root node, and the nodes on the second level are all leaf nodes. The total node count is 1 (root) + 4 (children), which is 5 nodes. If each node can hold 3 elements, then 5 x 3 = 15 is the maximum number of elements that can be held in a B-tree of order 4 that has two levels.

10 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 24

Chapter 24: Graphs Multiple Choice Questions: 1) In graph terminology, the nodes are referred to as ____________________. a) vertices b) edges c) parents d) children e) none of the above Answer: a Explanation: In a graph, the nodes are referred to as vertices, and the connections between vertices are called edges. Unlike a tree, there is no notion of parent or child in a graph. 2) In a(n) _____________________ graph, an edge from node labeled A to a node labeled B is the same as having an edge from B to A. a) directed b) undirected c) sparse d) tree-like e) none of the above Answer: b Explanation: In an undirected graph, an edge from A to B is the same as an edge from B to A. This is not true in a directed graph, where the two edges are distinct. 3) Which of the following describes vertices that are adjacent? a) They are close to one another in the visual representation of the graph. b) They are far apart in the visual representation of the graph. c) There is no edge connecting them. d) There is an edge connecting them. e) None of the above describes adjacent vertices. Answer: d Explanation: A pair of vertices is said to be adjacent if there is an edge connecting them. Their location in the visual representation of the graph has no bearing on adjacency. 4) A graph in which every edge is connected to every other edge is said to be ___________________ . a) sparse b) complete c) full d) balanced e) connected Answer: b Explanation: A complete graph is a graph in which every vertex is adjacent to every other vertex. 1.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 24

5) A connected graph has which of the following properties? a) For any pair of vertices, there is an edge between them. b) Every vertex is adjacent to every other vertex. c) No vertex is adjacent to every other vertex. d) For any pair of vertices, there is a path between them. e) There exists a vertex that is adjacent to every other vertex. Answer: d Explanation: In a connected graph, for any pair of vertices, there is a path between them. 6) A graph is said to have a(n) ________________, if there exists a path where the first and last vertices are the same, and no edge is repeated. a) connected component b) algorithm c) cycle d) weight e) complete component Answer: c Explanation: A cycle is a path through a graph in which the starting and ending nodes are the same, and no edges are repeated in the path. 7) A digraph is a __________________________ . a) graph in which every cycle contains 2 edges. b) graph in which every cycle contains 3 edges. c) graph in which there are no cycles. d) graph in which there are 2 cycles. e) directed graph. Answer: e Explanation: A digraph is another name for a directed graph. 8) A graph with integer weights or costs associated with edges is sometimes called a(n) _________________. a) acyclic graph b) directed graph c) network d) adjacency matrix e) none of the above Answer: c Explanation: A weighted graph is sometimes referred to as a network.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 24 9) A breadth-first traversal of a graph uses which of the following data structures? a) binary search tree b) stack c) queue d) array e) none of the above Answer: c Explanation: A breadth-first traversal of a graph uses a queue as a supporting data structure. 10) A depth-first traversal of a graph uses which of the following data structures? a) binary search tree b) stack c) queue d) array e) none of the above Answer: b Explanation: A depth-first traversal of a graph uses a stack as a supporting data structure. 11) A spanning tree of a graph is a tree with that always has which of the following properties? a) It includes some of the edges and some of the vertices of the graph. b) It includes all of the edges and some of the vertices of the graph. c) It includes some of the edges and all of the vertices of the graph. d) It includes all of the edges and all of the vertices of the graph. e) none of the above Answer: c Explanation: A spanning tree always includes all of the vertices of a graph and some of the edges. 12) A(n) ___________________ is a two-dimensional array that can be used to represent a graph. a) adjacency list b) adjacency matrix c) digraph list d) graph node e) none of the above Answer: b Explanation: An adjacency matrix is a two-dimensional array that can be used to represent a graph.

3 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 24 13) A __________________ traversal can be used to determine if a graph is connected. a) inorder b) preorder c) depth-first d) breadth-first e) none of the above Answer: d Explanation: A breadth-first traversal of a tree can be used to determine if a graph is connected. This is due to the fact that a graph is connected if and only if the number of vertices in the breadth first traversal is the same as the number of vertices in the graph. 14) Consider a digraph with the following vertices and edges: vertices: A, B, C, D edges: (A,B), (B,A), (C,D) Which of the following statements are true? a) The graph has a cycle b) The graph is connected c) The graph is acyclic d) all of the above are true e) neither a, b, nor c are true. Answer: a Explanation: This graph has a cycle formed by edges (A,B) and (B,A). It is not connected because there is no path between A and D, for example. 15) A(n) _______________________ is one implementation of a graph where the graph is implemented as a linked structure, and each node contains a structure that contains links to all other nodes. a) adjacency list b) adjacency matrix c) digraph list d) graph node e) none of the above Answer: a Explanation: An adjacency list is a linked implementation of a graph.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 24

True/False Questions: 1) In an undirected graph, an edge of the form (A, B) is the same as an edge of the form (B, A). Answer: True Explanation: In an undirected graph, the order of the nodes in an edge does not matter. 2) A complete graph on n vertices has n(n-1)/2 edges. Answer: True Explanation: In a complete graph, every vertex is connected to every other vertex via an edge, and therefore it always has n(n-1)/2 edges. 3) In order to create a topological ordering of vertices in a directed graph, the graph cannot have a cycle. Answer: True Explanation: A topological ordering of vertices in a directed graph, in which vertex A can be said to precede vertex B if there is an edge from A to B, is only possible if the graph is acyclic. 4) A network is a type of graph in which there is a cost associated with each edge. Answer: True Explanation: A network, also called a weighted graph, is a graph in which each edge has an associated weight or cost. 5) A graph is a special kind of tree. Answer: False Explanation: A tree is a particular kind of directed graph in which each node except the root has a connection to it, and in which the root has a path to every non-root node. 6) A breadth-first traversal uses a stack as a supporting data structure. Answer: False Explanation: A breadth-first traversal uses a queue as a supporting data structure. 7) An adjacency matrix is one approach to implementing a graph that uses a two-dimensional array. Answer: True Explanation: An adjacency matrix is a two-dimensional array that specifies connections between nodes. 8) A spanning tree of a graph does not necessarily include all of the edges of the graph. Answer: True Explanation: A spanning tree includes all of the vertices of a graph, and only some of the edges. 9) A cycle is a path that starts and ends on the same vertex. Answer: False Explanation: A cycle is a path that starts and ends on the same vertex and does not repeat any edges. 10) A minimum spanning tree of a weighted graph is a spanning tree in which the sum of the weights of the edges is less than or equal to the sum of the weights for any other spanning tree for the same graph. Answer: True Explanation: A minimum spanning tree of a graph is the spanning tree with the lowest total weight.

5 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 24

Short Answer Questions: 1) Is every tree a graph? Is every graph a tree? Explain. Answer: A tree is a special kind of graph which has a specified root vertex, and it contains no cycles. A graph is more general than a tree, as it does not necessarily have a root vertex, and it may contain cycles. Therefore, every tree is a graph, but not every graph is a tree. 2) Can a tree ever have a cycle? Explain. Answer: No, a tree cannot have a cycle. This is because a child may not have more than one parent, and therefore it is impossible to get to the same vertex in a path without repeating an edge. 3) What is a complete graph? How many edges are contained in a complete graph on n vertices? Answer: A complete graph is a graph in which every pair of vertices are connected via an edge. It follows that every complete graph on n vertices has exactly n(n-1)/2 edges. 4) Consider the following undirected graph. vertices: A, B, C, D, E edges: (A,B),(C,D), (B,D), (B,C) Is the graph connected? Answer: The graph is not connected, because there is no path between the node labeled E and any of the other vertices. 5) Consider the following undirected, weighted graph: vertices: Chicago, New York, Boston, Washington edges: (Chicago, Boston, 159), (Chicago, New York, 129), (Chicago, Washington, 219), (Boston, New York, 89), (New York, Washington, 59) What is the least expensive path between Chicago and Washington? Answer: The edge between Chicago and Washington has a cost of 219. The path formed by the edge between Chicago and New York, then the edge between New York and Washington, has a cost of 129 + 59 = 188. This is the least expensive path between Chicago and Washington. 6) Write out all of the edges in a complete, undirected graph on 4 vertices, where the vertices are labeled A, B, C, and D. Answer: (A,B), (A,C), (A,D), (B,C), (B,D), (C,D) 7) Explain how a breadth-first traversal of a graph works. Answer: A breadth-first traversal of a graph uses a queue as a supporting data structure. It begins enqueuing the starting vertex and marking it as visited. After that, it iterates a loop until the queue is empty. At each iteration, it dequeues the first element in the queue, enqueues all of its unvisited neighboring vertices, and then marks them all as visited. At the end of this process, all of the vertices will have been visited (assuming the graph is connected).

6.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 24 8) What data structure is used to support a depth-first traversal of a graph? Answer: A stack is the data structure that is used to support a depth-first traversal of a graph. 9) Consider the following undirected graph. vertices: A, B, C, D, E edges: (A,B),(C,D), (B,D), (B,C), (C,E), (D,E) Give a spanning tree for this graph. Answer: One spanning tree for this graph is the edges (A,B),(B,D),(B,C),(D,E). 10) Consider the following undirected graph. vertices: A, B, C, D, E edges: (A,B),(C,D), (B,D), (B,C), (C,E), (D,E) Write out an adjacency matrix for this graph. Answer: A B C D E

A F T F F F

B T F T T F

C F T F T T

D F T T F T

E F F T T F

11) What is the maximum number of edges in a directed graph on n vertices? Explain how you arrived at your solution. Answer: A complete graph on n vertices has n(n-1)/2 edges. This is the maximum number of edges that an undirected graph can have. For a directed graph, it is possible to have 2 edges for each pair of vertices, and therefore we multiply the maximum number of edges in an undirected graph by 2. The result is n(n-1). 12) What is the difference between a spanning tree and a minimum spanning tree? Answer: A spanning tree for a graph is an acyclic set of vertices and edges such that every vertex appears in the original graph appears. A minimum spanning tree is a spanning tree that has a weight that is less than or equal to the weight of all other spanning trees for the graph. 13) Explain how an adjacency matrix can be used to represent a weighted graph. Answer: An adjacency matrix uses boolean values to indicate if there is an edge between two vertices. This approach could be modified so that an object could be used to represent the cost or the weight of an edge. A null value can be used to indicate that there is no edge between a pair of vertices. 14) What does it mean for a graph to be connected? Answer: A graph is connected if for every pair of vertices, there exists a path between them.

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 24 15) Can an edge be part of more than one cycle in a graph? Explain. Answer: Yes, an edge can be part of more than one cycle. For example, consider the following graph. vertices: A, B, C, D, E edges: (A,B),(C,D), (B,D), (B,C), (C,E), (D,E) In this graph, the edge (C,D) is part of the cycle (B,C),(C,D),(D,B) and also part of the cycle (C,E),(E,D),(D,C).

8 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 25

Chapter 25: Databases Multiple Choice Questions: 1) The four primary operations on data can be expressed by which acronym? a) JUNK b) CRUD c) LIFO d) FIFO e) LIST Answer: b Explanation: The four primary operations on data in a data base are create, read, update, and delete. The acronym that captures this is CRUD. 2) In a relational database, the information and the relations between information are organized into a) tables b) rows c) classes d) objects e) inheritance hierarchies Answer: a Explanation: A relational database uses tables to hold both the information in the database and the relations between the information. 3) A driver is used to a) operate a program b) connect to a database c) move data around d) manage the objects in a program e) None of these is correct Answer: b Explanation: A driver is a specialized piece of software that is used to establish communications from a program to a database. Database requests from the program and responses from the database are sent via the driver. 4) A relational database conserves space by a) using smaller numbers b) reducing the size of strings c) using only lowercase letters d) avoiding data replication e) None of these is correct Answer: d Explanation: A database uses relations between tables to minimize the number of copies of data items.

1.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 25 5)

If a table has been created in a database, then a subsequent attempt to create the same table in the same database will a) create a new table with ‘(2)’ at the end of the table name b) replace the initial table. c) fail with an exception. d) remove all of the elements from the initial table e) None of these is correct

Answer: c Explanation: A table can only be created once. Subsequent attempts to create the same table in the same database will fail. An exception will be thrown indicating that the table already exists. 6) If a table is created and it is later determined that additional fields should be added to the table, it is usually preferable to a) delete the existing table and re-create it with the additional fields b) create a parallel table that holds just the additional fields c) re-define an existing field in the table to hold the additional data d) delete the entire database and start over e) alter the table to add the additional fields Answer: e Explanation: Fields can be added to a table using the ALTER TABLE statement. In this way, the existing data that is in the table is preserved. Deleting the table or deleting the database would destroy the existing data. 7) The smallest unsigned integer type that can be used for a field in a MySQL database is a(n) a) smallInt b) tinyint c) littleInt d) shortInt e) None of these is correct Answer: b Explanation: tinyint is the smallest (in terms of storage space) unsigned integer datatype that can be used in a field definition in a MySQL database table. Other database systems may have a similar field. 8) The MySQL command to remove the field backOrder from the table named inventory is a) ALTER TABLE inventory DROP COLUMN backOrder b) DELETE COLUMN backOrder FROM inventory c) DROP COLUMN backOrder FROM inventory d) REMOVE FIELD backOrder FROM inventory e) None of these is correct Answer: a Explanation: The ALTER TABLE command can be used to modify a table by either adding fields (ADD COLUMN) or removing fields (DROP COLUMN). The statement in answer a) is correct.

2 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 25 9) _________________ is how information is retrieved from a database. a) Assessing b) Interceding c) Querying d) Altering e) Removing Answer: c Explanation: Querying a database is the way that information is retrieved from a database. The information that is retrieved can be about the organization of the database or about the contents of one or more tables. 10) The SQL statement most often used to retrieve data from a database is a) RETRIEVE ... FROM b) FIND ... IN c) ACCESS DATA GET ... d) SELECT ... FROM e) None of these is correct Answer: d Explanation: The SELECT ... FROM statement in SQL is used to retrieve data from a database. The fields/columns to be retrieved are listed between SELECT and FROM. Following FROM is the table or list of tables from which to perform the selection. A WHERE clause can be optionally supplied to restrict the values that are retrieved. 11) The WHERE clause, if present, contains a) a condition that evaluates to TRUE or FALSE b) the number of records to retrieve at a time c) a list of tables from which to select d) the separator to use between retrieved records e) additional fields to retrieve from if the initial list is empty. Answer: a Explanation: The WHERE clause is used to restrict the set of values that are retrieved in a SELECT ... FROM statement to just those values that make the condition TRUE. Values that make the condition FALSE are not retrieved. 12) In order to select all of the fields / columns from a table, use ______ between SELECT and ALL a) * b) ANY c) ALL d) ALL_COLUMNS e) ALL_DATA Answer: a Explanation: An asterisk is used to indicate that all columns should be retrieved.

3 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 25 13) The direction of the sort order of the records retrieved by a SELECT … FROM statement is indicated by a) UP or DOWN b) SMALLER TO LARGER or LARGER TO SMALLER c) ASC or DESC d) MIN or MAX e) None of these is correct Answer: c Explanation: The direction of sorting is indicated by using ASC (ascending) or DESC (descending) as the last part of the ORDER BY clause. 14) How do you retrieve data from a table that has been dropped? a) You prefix the table name with the qualifier DROPPED. b) Use the SQL statement SELECT ... FROM FORMER c) You indicate the dropped table name in the WHERE clause d) Use the (-1) qualifier after the table name to retrieve from the prior version of the table. e) You do not retrieve data from a table that has been dropped.

dropped.

Answer: e Explanation: Data is removed once a table is dropped. It is not possible to retrieve data from a table after it has been

15) What will be deleted from a table by a DELETE FROM statement if the WHERE clause is not provided? a) The first field/column in the table b) The most recently-added data c) Everything d) Nothing – the WHERE clause is required. e) None of these is correct. Answer: c Explanation: If the WHERE clause is not present on the DELETE FROM statement, then all data will be deleted from the table.

4 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 25

True/False Questions: 1) Database is an abstract class in the Java Collections library Answer: False Explanation: A database is a repository for data that is organized for efficient storage and data access. It is implemented as an application that is outside of a Java program but is accessible from within a Java program. 2) In a relational database, the information that is stored in the database is organized into tables. Answer: True Explanation: The data and the relations between data items are all stored in tables in a relational database. 3) A The rows in a table in a relational database are referred to as fields. Answer: False Explanation: The rows of a table are referred to as records. The individual data items that make up the record are the fields of the record. 4) The acronym JDBC refers to ‘Java Data Binary Connector’. Answer: False Explanation: JDBC refers to ‘Java Database Connectivity’, which is an API that allows the management of data within a database from within a Java program. 5) The first task in working with a database from a Java program is to create and populate one or more tables. Answer: False Explanation: The first task is to establish a connection to the database. Without a connection to the database, other tasks such as creating tables and inserting records into the tables cannot be accomplished. 6) A database driver is a piece of software that allows a program to interact with a database. Answer: True Explanation: A database driver is a specialized piece of software that communicates requests from a program to a database and returns responses from the database to the program. 7) CREATE TABLE is an SQL statement that is used to create a table in a database Answer: True Explanation: A CREATE TABLE statement creates a table in a database. The name of the table and a list of the fields and the corresponding types of the fields must be supplied as part of the CREATE TABLE statement. 8) A field in a table that is designated as a PRIMARY KEY is a field that will always have the same value. Answer: False Explanation: All of the values of a PRIMARY KEY are unique. The PRIMARY KEY is comprised of one or more fields. 9) A field can be removed from a table by using the ALTER TABLE … DROP COLUMN statement. Answer: True Explanation: Removing a field / column from a table is done by using the ALTER TABLE statement and including the DROP COLUMN command. 10) Using the ALTER TABLE statement to remove all of the fields / columns by using the DROP COLUMN command accomplishes the same result as the DROP TABLE statement. Answer: False Explanation: Using ALTER TABLE … DROP COLUMN will remove all of the columns from a table. Using the DROP TABLE statement will remove the columns and remove the table.

5.


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 25

Short Answer Questions: 1) What is a database management system? Answer: A database management system is software that the supports the rapid retrieval of data contained within a database, and also provides basic functions to manage the data. 2) What are the four primary operations that can be performed on or with the data in a database? Answer: The four primary operations are known by the acronym CRUD: Create data, Read data, Update data, and Delete data. 3) What is the basic organizational unit of a relational database? Answer: The basic organizational unit of a relational database is a table. Tables are used to hold the information (data) in the database and also the relationships between pieces of data in the database. 4) What is the purpose of the JDBC API? Answer: The JDBC API, which is part of the Java Development Environment, provides classes and methods to access and manage data in a database from within a Java program. 5) The basic SQL statement to create a table in a database is CREATE TABLE. What additional information is required in the statement besides CREATE TABLE? Answer: One of the pieces of information that is required when creating a table is the name of the table. The table name is supplied after the words CREATE TABLE. Following the table name is a parenthesized, comma-separated list of fields / columns for the table, along with their datatype and other characteristics such as being a PRIMARY KEY field. 6) Suppose you learn, after you have created a table and added records to the table, that additional fields are required in the table. Discuss the differences between using the ALTER TABLE statement to add the new fields vs. dropping the table and using CREATE TABLE to create a new table with the correct fields. Answer: Dropping a table deletes all of the data in the table. If you then use CREATE TABLE to re-create the table with the new fields / columns , you will have to re-populate the table to add the data that was deleted when the original table was dropped. With the ALTER TABLE statement, the new fields are added to the existing records in the database. Once the new fields are populated in all existing records, any fields / columns that may no longer be needed could be deleted. Using ALTER TABLE in this way preserves the data in the table and eliminates the task of re-populating the table. 7) Write an SQL statement to create a table named parts that has two columns: a field for a part number, which will be automatically set to the next part number when a new part is added, and a description field, which will hold up to 255 characters of text. Answer: CREATE TABLE parts (part_number INT UNSIGNED NOT NULL AUTO INCREMENT, description varchar(255))

6 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 25 8) Assuming that the table described in question 7) was properly created, write an SQL statement to add a column that will hold the quantity of the part that is in stock. The quantity will never be less than zero. Answer: ALTER TABLE parts ADD COLUMN (quantity_in_stock UNSIGNED INT) 9) Assuming that the table described in question 7) was properly updated in question 8), write one or more SQL statements to add the following items to the table: Bracket, quantity 25; Flange, quantity 8. Answer: INSERT parts (description, quantity_in_stock) VALUES ("Bracket", 25) INSERT parts (description, quantity_in_stock) VALUES ("Flange", 8) 10) Assuming that the table described in question 7) was properly updated in question 8) and populated in question 9), write an SQL statement that will retrieve the part_number field of all records in the table for which the quantity_in_stock field is less than 10. Answer: SELECT part_number FROM parts WHERE quantity_in_stock < 10 11) When adding records to a table using an INSERT statement, why don’t we provide a value for the columns in the table that are listed as AUTO INCREMENT? Answer: Columns that are listed as AUTO INCREMENT will have the next consecutive value assigned to them automatically when the record is added to the table. Database users do not assign values to AUTO INCREMENT fields directly. 12) What is a ResultSet? Answer: ResultSet is a class of object that is returned by a database query. One of the objects that is a data member of a ResultSet object is its ResultSetMetaData object, which is used to retrieve and process the information that was returned by the query. 13) A ResultSet object is organized as a two-dimensional table. What is represented by the rows and the columns of the ResultSet object? Answer: The columns of the ResultSet object are the fields that it contains, which are the fields that were returned by the database query. The rows of the ResultSet object are the records that were returned by the query. 14) What is the difference between deleting everything from a table and dropping a table? Answer: When everything is deleted from a table, the table is still present in the database but it is empty. Records can be inserted into the table. When a table is dropped, not only is its data removed, but the table itself is removed. Records cannot be inserted into a dropped table.

7 .


Java Foundations: Introduction to Program Design & Data Structures, 5e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 25 15) Explain the general process of updating data in a database. Answer: The process of updating data in a database consists of three basic steps. The first step is to retrieve the data to be updated. The second step is to change the values in the retrieved data. The third step is to use the changed values to update the database.

8 .


Turn static files into dynamic content formats.

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