Mid-Term STUDY GUIDE Chapter 1 Multiple Choice Questions: 1) A Java program is best classified as a) hardware b) software c) storage d) processor e) input Answer: b. Explanation: Programs are classified as software to differentiate them from the mechanisms of the computer (hardware). Storage and the processor are two forms of hardware while input is the information that the program processes. 2) 6 bits can be used to represent ___ distinct items or values a) 6 b) 20 c) 24 d) 32 e) 64 Answer: e. Explanation: With n bits, we can represent 2n different values. 26 = 64. 3) When executing a program, the processor reads each program instruction from a) secondary memory (storage) b) the Internet c) registers stored in the processor d) main memory e) could be any of these Answer: d. Explanation: The program is first loaded from secondary memory into main memory before it is executed so that the processor is not slowed down when reading each instruction. This idea of executing programs stored in memory is called the Stored Program Computer and was pioneered by Von Neumann in the 1940s. 4) Which memory capacity is the largest? a) 1,500,000,000,000 bytes b) 100 gigabytes c) 3,500,000 kilobytes d) 10 terabyte e) 12,000,000 megabytes Answer: e. Explanation: We convert each of these capacities to bytes (rounding off) to compare them. The value in a remains the same, 1 ½ trillion bytes. The value in b is 100 billion bytes. The value in c is 3 ½ billion bytes. The value in d is 10 trillion bytes. The answer in e is 12 trillion bytes. 5) Volatility is a property of a) RAM b) ROM c) disk d) software e) computer networks Answer: a. Explanation: Volatility means that the contents of memory are lost if the electrical power isshut off. This is true of RAM, but not ROM or disk. Software and computer networks are not forms of memory. 6) The ability to directly obtain a stored item by referencing its address is known as a) random access b) sequential access c) read-only access d) fetch access e) volatility Answer: a. Random access is meant to convey that accessing any item is equally easy, and that any item is retrievable based solely on its address. Random access is the form of access used by both RAM and ROM memory. Disk access, called direct access, is a similar idea and direct and random access are sometimes referred to synonymously. Sequential access is used by tape. 7) In order for a computer to be accessible over a computer network, the computer needs its own a) MODEM b) Communication line c) Network address d) Packet e) Router Answer: c. Explanation: In order to differentiate between the computers on a network, each is given its own, unique, network address. In this way, a message intended for one computer can be recognized by that computer through the message’s destination address. A MODEM is a device that is used to allow a computer to communicate to another computer over the telephone line. The communication line is the network media itself. A packet is a piece of information being sent from over a network. A router is a hardware device used to take a message from one network and move it to another based on the message’s destination address. 8) A URL (Universal Resource Locator) specifies the address of a) A computer on any network b) A computer on the Internet c) A local area network (LAN) on the Internet d) A document or other type of file on the Internet e) A java program on the Internet Answer: d. URLs are used to locate documents (or other types of files such as an image or sound file) anywhere on the Internet. The URL contains the address of the LAN or WAN and the specific computer from which the file is to be retrieved, but specifies the file’s address, not just the computer’s address. 9) It is important to dissect a problem into manageable pieces before trying to solve the problem because a) most problems are too complex to be solved as a single, large activity b) most problems are solved by multiple people and it is easy to assign each piece to a separate person c) it is easier to integrate small pieces of a program into one program than it is to integrate one big chunk of code into one program d) our first solution may not solve the problem correctly e) all of the above Answer: a. Any interesting problem will be too complex to solve easily as a single activity. By decomposing the problem, we can build small solutions to each piece and then integrate the pieces. Answer d is true, but is not the reason why we will break a problem down into pieces. 10) Once we have implemented the solution, we are not done with the problem because a) the solution may not be the best (most efficient) b) the solution may have errors and need testing and fixing before we are done c) the solution may, at a later date, need revising to handle new specifications d) the solution may, at a later date, need revising because of new programming language features e) all of the above Answer: e. Explanation: A program should not be considered as a finished product until we are reasonably assured that it is efficient and error-free. Further, it is common that programs require modification in the future because of a change to specifications or a change to the language or computer running the program. 11) Of the following list, which one is not true regarding Java as a programming language? Lewis/Loftus/Cocking: Chapter 1 Test Bank TB 3 a) It is a relatively recent language, having been introduced in 1995 b) It is a language whose programs do not require translating into machine language before they are executed c) It is an object-oriented programming language d) It is a language that embraces the idea of writing programs to be executed using the World Wide Web e) All of the above are true Answer: b. Explanation: All languages require translation into machine language. The other statements are all true about Java. 12) Comments should a) rephrase the code it explains in English b) be insightful and explain what the instruction's intention is c) only be included in code that is difficult to understand d) be used to define variables whose names are not easy to understand e) all of the above Answer: b. Explanation: One might answer e, but that then includes a and c, making “all of the above” incorrect. Comments should not rephrase in English what an instruction says, but instead should explain what that instruction is doing in relation to the program. Introductory programmers often have difficult explaining their code and wind up stating the obvious in their comments. While answer d is partially correct, it is not entirely true, all variables should have comments that explain their use. 13) The main method for a Java program is defined by a) public static void main( ) b) public static void main(String[ ] args); c) public static void main(String[ ] args) d) private static void main(String[ ] args) e) the main method could be defined as in a, c or d but not b Answer: c. Explanation: In a, the missing parameter is not allowed. The parameters are defined later in the text, but in affect, they allow the user to run the program and include some initial arguments if the program calls for it. In b, the semicolon at the end of the statement is not allowed. In d, “private” instead of “public” would make the program unexecutable by anyone and thus makes the definition meaningless. 14) The instruction: System.out.println("Hello World"); might best be commented as: a) // prints "Hello World" to the screen b) // prints a message c) // used to demonstrate an output message d) // e) // meaningless instruction Answer: c. Explanation: Comments in a and b state the obvious while the comments in d and e are meaningless. The comment in c explains why the instruction appears in the program. 15) Which character below is not allowed in an identifier? a) $ b) _ c) 0 (zero) d) q e) ^ Answer: e. Explanation: Java identifiers can consist of any letter, digit, $ or _ as long as the identifier starts with a letter or _. ^ is not a legal character. 16) Which of the following would not be syntactically legal in Java? a) public class Foo b) System.out.println("Hi"); c) { } d) s t a t i c main(String[ ] args) e) only b is legally valid, all of the rest are illegal Answer: d. Explanation: The Java compiler would not recognize “s t a t i c” as “static” because the Java compiler treats white space (blanks) as separators between entities. The other statements are all legal, including “{ }” which is a block that happens to have no statements inside of it. 17) Which of the following would be a legal Java identifier? a) i b) class c) ilikeclass! d) idon'tlikeclass e) i-like-class Answer: a. Explanation: Java identifiers cannot have the characters “!”, “'” or “-” in them making answer c, d and e wrong. The word “class” is a reserved word in Java and cannot be used as an identifier. The identifier “i” is perfectly legal although not necessarily a good identifier since it is not descriptive of its use. 18) Which of the following stores data in binary format? a) ROM b) RAM c) a hard disk d) a CD e) all of the above Answer: e. Explanation: All information in a computer is stored in binary, that is, using 0s and 1s. 19) An error in a program that results in the program outputting $100 instead of the correct answer, $250 is a) a programmer error b) a syntax error c) a run-time error d) a logical error e) a snafu Answer: d. Explanation: While this is an error (answer a), programmers classify the type of error in order to more easily solve the problem. Syntax errors are caught by the compiler and the program cannot run without fixing all syntax errors. Run-time errors arise during program execution and cause the program to stop running abnormally. Logical errors are errors whereby the program can run to completion, but gives the wrong answer. If the result should have been $250, then the logic of the program is wrong since it output $100. A snafu is a term expressing a messed up situation in combat and should not be used by respectable programmers! 20) Following Java naming convention, which of the following would be the best name for a class about store customers? a) StoreCustomer b) Store Customer c) storeCustomer d) STORE_CUSTOMER e) Store-Customer Answer: a. Explanation: The Java naming convention states that classes should all start with an upper case letter and that multiple-word names should start each new name with an upper case letter while the remaining characters are lower case. Words should either be connected together without spaces, or connected with the “_” character. Answers b and e are not legal names, and using Java naming convention, c would qualify as a variable name and d would qualify as a constant. 21) Which of the following would be a good variable name for the current value of a stock? a) curstoval b) theCurrentValueOfThisStockIs Lewis/Loftus/Cocking: Chapter 1 Test Bank TB 5 c) currentStockVal d) csv e) current Answer: c. Explanation: Java allows long variable names but the programmer must find a good compromise between an excessive long name (as with b) and names too short to understand their use (a and d). The name current might be reasonable if there are no other “current” values being referenced in the program. 22) Which of the following is a legal Java identifier? a) 1ForAll b) oneForAll c) one/4/all d) 1_4_all e) 1forall Answer: b. Explanation: Java identifiers cannot start with a number (so the answers in a, d and e are illegal) and cannot include the “/” character, so the answer in c is illegal. 23) A color image is broken down into individual pixels (points), each of which is represented by a) a 1 for white and a 0 for black b) 3 values denoting the shade of red, green and blue in the image c) a single number indicating the intensity of color between white and black d) two numbers, a value that denotes where between white and black the color is, and a brightness e) none of the above, it is not possible to represent a color image. Answer: b. Explanation: Black and white images are stored using 0s and 1s while color images are stored using three values, one each for the degree of red, the degree of blue, and the degree of green. 24) Which of the following characters does not need to have an associated “closing” character in a Java program? a) { b) ( c) [ d) < e) all of these require closing characters Answer: d. Explanation: { is used to open a block, and so } is needed to close the block. ( is used to open an expression and so ) is needed to close an expression. [ is used to start an array index so ] is needed to close the array index. < is “less than” and > is “greater than” and these are not needed together, so < requires no closing character. 25) Forgetting a semicolon will cause a) a syntax error b) a run-time error c) a logical error d) no error at all e) converting the statement into a comment Answer: a. Explanation: If a semicolon is missing where one should be present, the compiler will generate a syntax error. Chapter 2: Objects and Primitive Data Multiple Choice Questions: Use the following class definition to answer questions 1-4. public class Questions1_4 { public static void main(String[ ] args) { System.out.print("Here"); System.out.println("There " + "Everywhere"); System.out.println("But not" + "in Texas"); } } 1) The program will print the word "Here" and then print a) "There Everywhere" on the line after "Here" b) "There" on the line after "Here" and "Everywhere" on the line after "There" c) "There Everywhere" on the same line as "Here" d) "ThereEverywhere" on the same line as "Here" e) "ThereEverywhere" on the line after "Here" Answer: c. Explanation: System.out.print will output the word "Here" but will leave the cursor at that point rather than starting a new line. The next statement will output "There Everywhere" immediately after the word "Here". Since there is a blank space within the quote marks for "There", there is a blank space inserted between "There" and "Everywhere". 2) The final println command will output a) "But not in Texas" b) "But notin Texas" c) "But not" on one line and "in Texas" on the next line d) "But not+in Texas" e) "But not + in Texas" Answer: b. Explanation: The “+” performs String concatenation, so that "But not" and "in Texas" are concatenated together. Notice that there is no blank space after "not" or before "in" so that when they are concatenated, they are placed together without a blank space. 3) How many lines of output are provided by this program? a) 1 b) 2 c) 3 d) 4 e) 5 Answer: b. Explanation: There will be one line of output for the first two statements combined because the print statement does not return the cursor to start a new line. And since the second statement is a println, it returns the cursor and the last println outputs its message on a separate line. 4) A reasonable comment for this program might be a) // a program that demonstrates the differences between print, println and how + works b) // a program that outputs a message about Texas c) // a program that demonstrates nothing at all d) // a program that outputs the message “Here There Everywhere But not in Texas” e) // a program that has three output statements in it Answer: a. Explanation: Remember that comments should not state the obvious (ruling out d and e) but instead should explain what the program is doing or why. This program demonstrates print and println and +. 5) Consider the following statement: System.out.println("1 big bad wolf\t8 the 3 little pigs\n4 dinner\r2night"); This statement will output ___ lines of text a) 1 b) 2 c) 3 d) 4 e) 5 Answer: b. Explanation: The \t escape sequence inserts a tab, but leaves the cursor on the same line. The \n escape sequence causes a new line to be produced so that “4 dinner” is output on the next line. The escape sequence \r causes the carriage to return (that is, the cursor to be moved back to the left margin) but because it does not start a new line, “2night” is output over “4 dinn” resulting in a second line that looks like “2nighter”. 6) If you want to output the text "hi there", including the quote marks, which of the following could do that? a) System.out.println("hi there"); b) System.out.println(""hi there""); c) System.out.println("\"hi there"); d) System.out.println("\"hi there\""); e) none, it is not possible to output a quote mark because it is used to mark the beginning and ending of the String to be output. Answer: d. Explanation: \" is an escape sequence used to place a quote mark in a String, so it is used here to output the quote marks with the rest of the String. 7) Of the following types, which one cannot store a numeric value? a) int b) double c) char d) all of these can store numeric values e) none of these can store numeric values Answer: c. Explanation: int is used to store whole numbers (integers) and double is used to store a real or floating point value (value with a decimal point). A char stores a single character including letters, punctuation marks and digits. However, storing the numeric digit ‘5’ is not the same as storing the number 5. 8) What value will z have if we execute the following assignment statement? double z = 5 / 10; a) z will equal 0.0 b) z will equal 0.5 c) z will equal 5.0 d) z will equal 0.05 e) none of the above, a run-time error arises because z is a double and 5 / 10 is an int Answer: a. Explanation: 5 and 10 are both int values, so 5 / 10 is an integer division. The result is 0. Even though z is a double and can store the real answer, 0.5, it only gets 0 because of the integer division. In order to get 0.5, we would have to first cast 5 or 10 as a double. 9) What value will z have if we execute the following assignment statement? int z = 50 / 10.00; a) 5 b) 5.0 c) 50 d) 10 e) none of the above, a run-time error arises because z is an int and 50 / 10.00 is not Answer: e. Explanation: Because 10.00 is not an int, the division produces a double precision value which cannot be stored in the int z. For this to work, the result of the division must be cast as an int before being stored in z, or the value 10.00 would have to first be cast as an int before the division takes place. 10) A cast is required in which of the following situations? a) using charAt to take an element of a String and store it in a char b) storing an int in a double c) storing a double in a double d) storing a double in an int e) all of the above require casts Answer: d. Explanation: For a, charAt returns a char, so there is no problem. In b, the situation is a widening operation taking a narrower type and storing the value in a wider type. Only in d is there a situation where a wider type is being stored in a narrower type, so a cast is required. 11) If x is an int and y is a double, all of the following are legal except which assignment statement? 1) y = x; 2) x = y; 3) y = (double) x; 4) x = (int) y; 5) all of the above are legal Answer: b. Explanation: Since x is an int, it cannot accept a double unless the double is cast as an int. There is no explicit cast in the assignment statement in b. In a, a cast is not necessary because a double (y) can accept an int value (x), and in c and d, explicit casts are present making them legal. 12) Given the following assignment statement, which of the following answers is true regarding the order that the operators will be applied based on operator precedence? a = (b + c) * d / e – f; a) *, /, +, b) *, +, /, c) +, *, /, d) +, /, *, e) +, -, *, / Answer: c. Explanation: Order of precedence is any operator in ( ) first, followed by * and / in a left-to-right manner, followed by + and – in a left-to-right manner. So, + is first since it is in ( ), followed by * followed by / since * is to the left of /, followed finally by -. 13) What will be the result of the following assignment statement? Assume b = 5 and c = 10. int a = b * (-c + 2) / 2; a) 30 b) –30 c) 20 d) –20 e) –6 Answer: d. Explanation: The unary minus is applied first giving –c + 2 = -8. Next, the * is performed giving 5 * 8 = -40, and finally the / is performed giving –40 / 2 = -20. 14) Assume that x, y and z are all ints equal to 50, 20 and 6 respectively. What is the result of x / y / z? a) 0 b) 12 c) 16 d) A syntax error as this is syntactically invalid e) A run-time error because this is a division by 0 Answer: a. Explanation: This division is performed left to right, so first 50 / 20 is performed. Since 50 and 20 are ints, this results in 2. Next, 2 / 6 is performed which is 0. Notice that if the division were performed right to left, the evaluation would instead be 50 / (20 / 6) = 50 / 3 = 16. 15) What is output with the statement System.out.println(x+y); if x and y are int values where x=10 and y=5? a) 15 b) 105 c) 10 5 d) x+y e) An error since neither x nor y is a String Answer: a. Explanation: Java first computes x+y and then casts it as a String to be output. x + y = 10 + 5 = 15, so the statement outputs 15. 16) What is output with the statement System.out.println(""+x+y); if x and y are int values where x=10 and y=5? a) 15 b) 105 c) 10 5 d) x+y e) An error since neither x nor y is a String Answer: b. Explanation: The "" casts the rest of the expression as a String, and so the two + signs are used as String concatenation, and so x + y becomes x concatenated with y, or 105. 17) If you want to store into the String name the value "George Bush", you would do which statement? a) String name = "George Bush"; b) String name = new String("George Bush"); c) String name = "George" + " " + "Bush"; d) String name = new String("George" + " " + "Bush"); e) Any of the above would work Answer: e. Explanation: There are two ways to store a character string into a String variable, by constructing a new String using "new String(string value); " or by using an assignment statement, so either a or b will work. In c and d, we have variations where the String concatenation operator + is used. So all four approaches will work. 18) Consider having three String variables a, b and c. The statement c = a + b; can also be achieved by doing a) c = a.length( ) + b.length( ); b) c = (int) a + (int) b; c) c = a.concat(b); d) c = b.concat(a); e) c = a.plus(b); Answer: c. The statement c = a + b uses the concatenation operator + (not to be confused with numeric addition). The same result can be achieved by passing a the concat message with b as the parameter. Answer d will set c to be b + a rather than a + b. 19) In the String major = "Computer Science", what is returned by major.charAt(1)? a) 'C' b) 'o' c) 'm' d) "C" e) "Computer" Answer: b. Explanation: Neither d nor e would be correct because charAt returns a char (single character) whereas these answers are Strings. So, the question is, which character is returned? In Java, the first character of a String is numbered 0. So charAt(1) returns the second character of the String, or 'o'. 20) Which of the following would return the last character of the String x? a) x.charAt(0); b) x.charAt(last); c) x.charAt(length(x)); d) x.charAt(x.length( )-1); e) x.charAt(x.length( )); Answer: d. Explanation: Since last is not defined, b is syntactically invalid. The 0th character is the first in the String, so a is true only if the String has a single character. The answer in c is syntactically invalid as length can only be called by passing the message to x. Finally, d and e are syntactically valid, but since length returns the size of the String, and since the first character starts at the 0th position, the last character is at x.length()-1, so e would result in a run-time error. 21) Which library package would you import to use the class Random? a) java.beans b) java.io c) java.lang d) java.text e) java.util Answer: e. Explanation: This is a java utility, and so is found in the java.util package. 22) Since you cannot take the square root of a negative number, you might use which of the following instructions to find the square root of the variable x? a) Math.sqrt(x*x); b) Math.sqrt((int) x); c) Math.sqrt(Math.abs(x)); d) Math.abs(Math.sqrt(x)); e) Math.sqrt(-x); Answer: c. Explanation: Math.abs returns the absolute value of x. If x is negative, Math.sqrt(x) causes a run-time error, but Math.sqrt(Math.abs(x)) does not since x is first converted to its positive equivalent before the square root is performed. Answer a returns x (square root of x2 is x). In answer b, casting x to an int will not resolve the problem if x is negative. In answer d, the two Math functions are performed in opposite order and so if x is negative, it still generates a run-time error. Answer e will only work if x is not positive and so if x is positive, it now generates a run-time error. 23) Assume that x is a double that stores 0.362491. To output this value as 36%, you could use the NumberFormat class with NumberFormat nf = NumberFormat.getPercentInstance( ); Which of the following statements then would output x as 36%? a) System.out.println(x); b) System.out.println(nf); c) System.out.println(nf.x); d) System.out.println(nf.format(x)); e) System.out.println(format(x)); Answer: d. Explanation: nf is an object and so must be passed a message to use it. The method to format a double is called format and the value to be formatted is the parameter passed to format. Therefore, the proper way to do this is nf.format(x). The answer in a will merely output 0.362491 while the answers to b, c and e are syntactically invalid. For questions 24 and 25, refer to the class defined below: import cs1.Keyboard; public class Questions { public static void main(String[ ] args) { int x, y, z; double average; System.out.println("Enter an integer value"); x = Keyboard.readInt( ); System.out.println("Enter another integer value"); y = Keyboard.readInt( ); System.out.println("Enter a third integer value"); z = Keyboard.readInt( ); average = (x + y + z) / 3; System.out.println("The result of my calculation is " + average); } } 24) Questions computes a) The correct average of x, y and z as a double b) The correct average of x, y and z as an int c) The average of x, y and z as a double, but the result may not be accurate d) the sum of x, y and z e) the remainder of the sum of x, y and z divided by 3 Answer: c. Explanation: Because the division is an int division, even though the result is stored in a double, the resulting double may not be accurate. For instance, if x, y and z are 1, 2 and 4, the double average should be 2.33333 but average will instead be 2.00000. 25) What is output if x = 0, y = 1 and z = 1? a) 0 b) 0.0 c) 0.6666666666666666 d) 0.6666666666666667 e) 0.67 Answer: b. Explanation: The division is performed as an int division since x, y, z and 3 are all ints. Therefore, average gets the value 0.0. It is output as 0.0 instead of 0 because average is a double, which outputs at least one decimal digit unless specified otherwise using the DecimalFormat class. Chapter 3: Program Statements Multiple Choice Questions: 1) During program development, software requirements specify a) how the program will accomplish the task b) what the task is that the program must perform c) how to divide the task into subtasks d) how to test the program when it is done e) all of the above Answer: b. Explanation: The specification phase is to understand the problem at hand so that the programmer can determine what needs to be done to solve the problem. The other efforts listed above are part of the design phase (a, c) and testing phase (d). 2) In which phase of program development would you expect the programmer(s) to determine the classes and objects needed? a) Software requirements b) Software design c) Software implementation d) Software testing e) Could occur in any of the above Answer: b. Explanation: Determining which classes and objects to use or create is part of the design. 3) Which of the following would not be considered an algorithm? a) a recipe b) a computer program c) pseudocode d) a shopping list e) travel directions Answer: d. Explanation: An algorithm is a step-by-step description of how to solve a problem, written at some level of specificity. The recipe and probably the pseudocode are written at a “high level” whereas a program and perhaps travel directions are written in more detail. A shopping list is not a step-by-step description, so it would not qualify as an algorithm. 4) If a programmer follows the four phases of program development as intended, which of the four phases should require the least amount of creativity? a) Software requirements b) Software design c) Software implementation d) Software testing e) None of the above, all four levels would require equal creativity Answer: c. Explanation: Once the implementation phase has been reached, the algorithm should have already been specified, so the only effort involved in the implementation phase is of translating from the design (which is probably in an English-like pseudocode) to the programming language, and entering the code through an editor. The requirements and design phases require understanding the problem and coming up with a solution respectively, requiring creativity, and the testing phase will require diagnostic abilities usually forcing the programmer(s) to be creative in how the errors are found and fixed. 5) The idea that program instructions execute in order (linearly) unless otherwise specified through a conditional statement is known as a) boolean execution b) conditional statements c) try and catch d) sequentiality e) flow of control Answer: e. Explanation: The “flow of control” describes the order of execution of instructions. It defaults to being linear (or sequential) but is altered by using control statements like conditionals and loops. 6) Of the following if statements, which one correctly executes three instructions if the condition is true? a) if (x < 0) a = b * 2; y = x; z = a – y; b) { if (x < 0) a = b * 2; y = x; z = a – y; } c) if { (x < 0) a = b * 2; y = x; z=a–y; } d) if (x < 0) { a = b * 2; y = x; z = a – y; } e) b, c and d are all correct, but not a Answer: d. Explanation: In order to have three instructions execute in the if clause when the condition is true, the three statements must be placed in a block following the condition. This is the syntax used in d. In a, there is no block. In b, the block is placed around the entire if statement such that the if clause is only a = b * 2; and the other two statements are not part of the if statement, but follow it. The syntax in c is illegal resulting in a syntax error. Don’t forget that the structure of your code (how it lines up) is immaterial to the compiler. 7) Which of the sets of statements below will add 1 to x if x is positive and subtract 1 from x if x is negative but leave x alone if x is 0? a) if (x > 0) x++; else x--; b) if (x > 0) x++; else if (x < 0) x--; c) if (x > 0) x++; if (x < 0) x--; else x = 0; d) if (x == 0) x = 0; else x++; x--; e) x++; x--; Answer: b. Explanation: if x is positive, x++ is performed else if x is negative x-- is performed and otherwise, nothing happens, or x is unaffected. In a, c, d and e, the logic is incorrect. In a, x-- is done if x is not positive, thus if x is 0, x becomes –1 which is the wrong answer. In c, if x is positive, then x++ is performed. In either case, the next statement is executed and if x is not negative, the else clause is performed setting x to 0. So if x is positive, it becomes 0 after this set of code. In d, x++ and x-- are both performed if x is not 0. And in e, this code does not attempt to determine if x is positive or negative, it just adds one and then subtracts 1 from x leaving x the same. Given the nested if-else structure below, answer questions 9-11. if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2; 8) If x is currently 0, a = 5 and b = 5, what will x become after the above statement is executed? a) 0 b) 2 c) 3 d) 4 e) 5 Answer: c. Explanation: Since (a > 0) is true, the next condition is checked. Since (b < 0) is false, the else clause for this condition is executed. Since (a > 5) is false the else clause for this condition is executed, which is x = x + 3. Therefore, 3 is added to x, so it is now 3. 9) If x is currently 0, a = 0 and b = -5, what will x become after the above statement is executed? a) 0 b) 2 c) 3 d) 4 e) 5 Answer: b. Explanation: Since (a > 0) is not true, the else clause for this condition is executed, which is x = x + 2, so x is now 2. 10) If x is currently 0, a = 1 and b = -1, what will x become after the above statement is executed? a) 0 b) 2 c) 3 d) 4 e) 5 Answer: e. Explanation: Since (a > 0) is true, the if clause is executed, which is another if statement. Its condition (b < 0) is true, so its if clause is executed, which is x = x + 5, so x is now 5. 11) Consider the following code that will assign a letter grade of ‘A’, ‘B’, ‘C’, ‘D’, or ‘F’ depending on a student’s test score. if(score >= 90) grade = 'A'; if(score >= 80) grade = 'B'; if(score >= 70) grade = 'C'; if(score >= 60) grade = 'D'; else grade = ‘F’; a) This code will work correctly in all cases b) This code will work correctly only if grade >= 60 Lewis/Loftus/Cocking: Chapter 3 Test Bank TB 25 c) This code will work correctly only if grade < 60 d) This code will work correctly only if grade < 70 e) This code will not work correctly under any circumstances Answer: d. Explanation: The problem with this code is that it consists of three if statements followed by one ifelse statement, rather than a nested if-else statement. So the logic is improper. If the student’s grade falls into the ‘A’ category, then all 4 conditions are true and the student winds up with a ‘D’. If the student’s grade falls into the ‘B’ category, then the first condition is false, but the next three are true and the student winds up with a ‘D’. If the student’s grade falls into the ‘D’ category, then the only condition that is true is the one that tests for ‘D’ and so the grade is assigned correctly. If the student’s grade falls into the ‘F’ category, then none of the conditions are true and an ‘F’ is assigned correctly. So, only if the grade < 70 does the code work correctly. 12) Assume that count is 0, total is 20 and max is 1. The following statement will do which of the following? if (count != 0 && total / count > max) max = total / count; a) The condition short circuits and the assignment statement is not executed b) The condition short circuits and the assignment statement is executed without problem c) The condition does not short circuit causing a division by zero error d) The condition short circuits so that there is no division by zero error when evaluating the condition, but the assignment statement causes a division by zero error e) The condition will not compile because it uses improper syntax Answer: a. Explanation: Since count is 0, (count != 0) is false. Because the left-hand side of an && condition is false, the condition is short circuited, and so the right-hand side is not evaluated. Thus, a potential division by zero error is avoided. Because the condition is false, the statement max = total / count is not executed, again avoiding a potential division by zero error. 13) What is wrong, logically, with the following code? if (x > 10) System.out.println("Large"); else if (x > 6 && x <= 10) System.out.println("Medium"); else if (x > 3 && x <= 6) System.out.println("Small"); else System.out.println("Very small"); a) There is no logical error, but there is no need to have (x <= 10) in the second conditional or (x <= 6) in the third conditional b) There is no logical error, but there is no need to have (x > 6) in the second conditional or (x > 3) in the third conditional c) The logical error is that no matter what value x is, “Very small” is always printed out d) The logical error is that no matter what value x is, “Large” is always printed out e) There is nothing wrong with the logic at all Answer: a. Explanation: Because this is a nested if-else statement, if (x > 10) is true, then the first println statement is executed and the rest of the statement is skipped. If (x > 10) is not true, then the first else clause is executed and the next if condition is tested. At this point, (x > 10) is known to be false and therefore (x <= 10) must be true, so there is no need to check this inequality. Similarly, if (x > 6) is false, then the second else clause is executed and the third if condition is tested. However, (x <= 6) must be true, so there is no need to check this inequality. 14) Consider the following outline of a nested if-else structure which has more if clauses than else clauses. Which of the statements below is true regarding this structure? if (condition1) if (condition2) statement1; else statement2; a) syntactically it is invalid to have more if clauses than else clauses b) statement2 will only execute if condition1 is false and condition2 is false c) statement2 will only execute if condition1 is true and condition2 is false d) statement2 will only execute if condition1 is false, it does not matter what condition2 is e) statement2 will never execute Answer: b. Explanation: The else clause must be matched to the most recent if statement. Therefore, the else goes with the if statement that tests condition2, not the if statement that tests condition1. So, if condition1 is true and condition2 is false, then statement2 will execute. TB 26 Lewis/Loftus/Cocking: Chapter 3 Test Bank 15) Assume that x and y are int variables with x = 5, y = 3, and a and d are char variables with a = 'a' and d = 'A', and examine the following conditions: Condition 1: (x < y && x > 0) Condition 2: (a != d || x != 5) Condition 3: !(true && false) Condition 4: (x > y || a == 'A' || d != 'A') a) All 4 Conditions are true b) Only Condition 2 is true c) Condition 2 and Condition 4 are true only d) Conditions 2, 3 and 4 are all true, Condition 1 is not e) All 4 Conditions are false Answer: d. Explanation: Condition 1 is not true because (x < y) is false, making the entire condition false. Since (c != d) is true, Condition 2 is true even though (x != 5) is false. Condition 3 is true because (true && false) is false, but !false is true. Condition 4 is true because (x > y) is true, making the entire Condition true. Therefore, Conditions 2, 3 and 4 are true while Condition 1 is false. 16) If x is an int where x = 1, what will x be after the following loop terminates? while (x < 100) x *= 2; a) 2 b) 64 c) 100 d) 128 e) None of the above, this is an infinite loop Answer: d. Explanation: With x = 1, the loop condition is true and the statement executes, doubling x, which is now 2. Since the loop condition is still true, the statement executes again, doubling x to 4. The condition remains true for the next 4 iterations, where x becomes 8, 16, 32 and 64. Since (x < 100) is still true when x = 64, the loop iterates again and x becomes 2 * 64 = 128. Now, (x < 100) is no longer true and the loop terminates with x = 128. 17) If x is an int where x = 0, what will x be after the following loop terminates? while (x < 100) x *= 2; a) 2 a) 64 b) 100 c) 128 d) None of the above, this is an infinite loop Answer: e. Explanation: Since x starts at 0, x *= 2; results in 0 * 2, or x = 0. Since x remains 0, (x < 100) remains true, and the loop repeats. x continues to be 0 and so the condition never changes to false, and thus the loop never terminates. 18) Given the following code, where x = 0, what is the resulting value of x after the for-loop terminates? for(int i=0;i<5;i++) x += i; a) 0 b) 4 c) 5 d) 10 e) 15 Answer: d. Explanation: Each pass through the for-loop results with the current value of the loop index, i, being added to x. The first time through the loop, i = 0 so x = x + 0 = 0. The second time through the loop i = 1 so x = x + 1 = 1. The third time through the loop i = 2 so x = x + 2 = 3. The fourth time through the loop i = 3 so x = x + 3 = 6. The fifth and final time through the loop i = 4 so x = x + 4 = 10. 19) How many times will the following loop iterate? Lewis/Loftus/Cocking: Chapter 3 Test Bank TB 27 int x = 10; while (x > 0) { System.out.println(x); x--; } a) 0 times b) 1 time c) 9 times d) 10 times e) 11 times Answer: d. Explanation: Since the condition is tested before the loop body executes, the loop will not execute once x == 0. So, the loop iterates for x = 10, x = 9, …, x = 1, or 10 times. 20) Given two String variables, s1 and s2, to determine if they are the same length, which of the following conditions would you use? a) (s1.equals(s2)) b) (s1.length( ).equals(s2)) c) (s1.length( ).equals(s2.length( )) d) (s1.length( ) == s2.length( )) e) length(s1) == length(s2) Answer: d. Explanation: Since s1 and s2 are Strings, we can only obtain their length by passing the length( ) message to each one. The length( ) method returns an int that we can directly compare against another int using ==, as done in d. The answers for b and c are syntactically invalid since s1.length( ) returns an int, and so cannot be passed the message .equals( ). The answer in e is also syntactically invalid. Finally, the answer in a determines if the two Strings are the exact same. While their lengths will be equal if this is true, two Strings may have equal length but not be equal, so this is logically incorrect. 21) Given a String, s, which is assumed to have at least one character in it, which of the following conditions would determine if the first character of the String is the same as the last character? f) (s.charAt(0) == s.charAt(s.length( ))) g) (s.charAt(1) == s.charAt(s.length( ))) h) (s.charAt(0) == s.charAt(s.length( ) - 1)) i) (s.charAt(0) == s.charAt(s.length( ) + 1)) j) (s.charAt(0) == s.charAt(last)) Answer: c. Explanation: The first character of a String starts at position 0. So, if a String’s length is 5, then its last character is at position 4. Therefore, the last character is at position s.length( ) – 1. The answer in e could be correct, but only if last had been previously set equal to s.length( ) – 1. 22) Given that s is a String, what does the following loop do? for(int j = s.length( ); j > 0; j--) System.out.print(s.charAt(j-1)); a) it prints s out backwards b) it prints s out forwards c) it prints s out backwards after skipping the last character d) it prints s out backwards but does not print the 0th character e) it yields a run-time error because there is no character at s.charAt(j-1) for j = 0 Answer: a. Explanation: The variable j counts down from the length of the String to 1, each time printing out the character at position j-1. The character at length – 1 is the first character printed and this is the last character of the String. It continues until it reaches j = 1, and prints out the character at position j – 1, or the 0th character, so it prints the entire String backwards. 23) The following nested loop structure will execute the inner most statement (x++) how many times? for(int j = 0; j < 100; j++) for(int k = 100; k > 0; k--) x++; a) 100 b) 200 c) 10,000 d) 20,000 e) 1,000,000 Answer: c. The outer loop iterates 100 times. Each time it iterates, the inner loop, and the x++ statement, execute 100 times. Therefore, the statement x++ executes 100*100 = 10,000 times. Consider the following paint method and answer questions 24-25: public void paint(Graphics page) { int x, y = 200; page.setColor(Color.blue); for(x = 100; x < 200; x += 20) page.fillRect(x, y, 10, y-x); } 24) This paint method will draw several bars (sort of like a bar graph). How many bars will be displayed? a) 4 b) 5 c) 6 d) 10 e) 20 Answer: b. Explanation: Since x iterates from 100 up to 200 in units of 20, it iterates 5 times (x = 100, x = 120, x = 140, x = 160, x = 180). 25) The size of each rectangle (bar) a) increases in height while staying the same width b) increases in width while staying the same height c) increases in both width and height d) stays the same size e) decreases in height while staying the same width Answer: e. Explanation: The width is a constant 10. The height is y-x where x increases by 20 each iteration, so the height decreases by 20. Chapter 4: Writing Classes Multiple Choice Questions: 1) The behavior of an object is defined by the object’s a) instance data b) constructor c) visibility modifiers d) methods e) all of the above Answer: d. Explanation: The methods dictate how the object reacts when it is passed messages. Each message is implemented as a method, and the method is the code that executes when the message is passed. The constructor is one of these methods but all of the methods combine dictate the behavior. The visibility modifiers do impact the object’s performance indirectly. 2) The relationship between a class and an object is best described as a) classes are instances of objects b) objects are instances of classes c) objects and classes are the same thing d) classes are programs while objects are variables e) objects are the instance data of classes Answer: b. Classes are definitions of program entities that represent classes of things/entities in the world. Class definitions include instance data and methods. To use a class, it is instantiated. These instances are known as objects. So, objects are instances of classes. Program code directly interacts with objects, not classes. 3) To define a class that will represent a car, which of the following definitions is most appropriate? a) private class car b) public class car c) public class Car d) public class CAR e) private class Car Answer: c. Explanation: Classes should be defined to be public so that they can be accessed by other classes. And following Java naming convention, class names should start with a capital letter and be lower case except for the beginning of each new word, so Car is more appropriate than car or CAR. 4) Which of the following reserved words in Java is used to create an instance of a class? a) class b) public c) public or private, either could be used d) import e) new Answer: e. Explanation: The reserved word “new” is used to instantiate an object, that is, to create an instance of a class. The statement new is followed by the name of the class. This calls the class’ constructor. Example: Car x = new Car( ); will create a new instance of a Car and set the variable x to it. 5) In order to preserve encapsulation of an object, we would do all of the following except for which one? a) Make the instance data private b) Define the methods in the class to access and manipulate the instance data c) Make the methods of the class public d) Make the class final e) All of the above preserve encapsulation Answer: d. Explanation: Encapsulation means that the class contains both the data and the methods needed to manipulate the data. In order to preserve encapsulation properly, the instance data should not be directly accessible from outside of the classes, so the instance data are made private and methods are defined to access and manipulate the instance data. Further, the methods to access and manipulate the instance data are made public so that other classes can use the object. The reserved word “final” is usedto control inheritance and has nothing to do with encapsulation. 6) If a method does not have a return statement, then a) it will produce a syntax error when compiled b) it must be a void method c) it can not be called from outside the class that defined the method d) it must be defined to be a public method e) it must be an int, double, or String method Answer: b. Explanation: All methods are implied to return something and therefore there must be a return statement. However, if the programmer wishes to write a method that does not return anything, and therefore does not need a return statement, then it must be a void method (a method whose header has “void” as its return type). 7) Consider a sequence of method invocations as follows: main calls m1, m1 calls m2, m2 calls m3 and then m2 calls m4, m3 calls m5. If m4 has just terminated, what method will resume execution? a) m1 b) m2 c) m3 d) m5 e) main Answer: b. Explanation: Once a method terminates, control resumes with the method that called that method. In this case, m2 calls m4, so that when m4 terminates, m2 is resumed. 8) A variable whose scope is restricted to the method where it was declared is known as a(n) a) parameter b) global variable c) local variable d) public instance data e) private instance data Answer: c. Explanation: Local variables are those that are “local” to the method in which they have been declared, that is, they are accessible only inside that method. Global variables are those that are accessible from anywhere, while parameters are the variables passed into a method. Instance data can be thought of as global variables for an entire object. 9) A class’ constructor usually defines a) how an object is initialized b) how an object is interfaced c) the number of instance data in the class d) the number of methods in the class e) if the instance data are accessible outside of the object directly Answer: a. Explanation: The constructor should be used to “construct” the object, that is, to set up the initial values of the instance data. This is not essential, but is typically done. The interface of an object is dictated by the visibility modifiers used on the instance data and methods. 10) Having multiple class methods of the same name where each method has a different number of or type of parameters is known as a) encapsulation b) information hiding c) tokenizing d) importing e) method overloading Answer: e. Explanation: When methods share the same name, they are said to be overloaded. The number and type of parameters passed in the message provides the information by which the proper method is called. 11) Instance data for a Java class a) are limited to primitive types (e.g., int, double, char) b) are limited to Strings Lewis/Loftus/Cocking: Chapter 4 Test Bank TB 37 c) are limited to objects(e.g., Strings, classes defined by other programmers) d) may be primitive types or objects, but objects must be defined to be private e) may be primitive types or objects Answer: e. Explanation: The instance data are the entities that make up the class and may be any type available whether primitive or object, and may be public or private. By using objects as instance data, it permits the class to be built upon other classes. This relationship where a class has instance data that are other classes is known as a has-a relationship. 12) An example of passing a message to a String where the message has a String parameter occurs in which of the following messages? a) length b) substring c) equals d) toUpperCase e) none of the above, it is not possible to pass a String as a parameter in a message to a String Answer: c. Explanation: The length and toUpperCase messages do not have parameters and substring has two int parameters. For equals, a String must be passed as a parameter so that the String receiving the message can be compared to the String passed as a parameter. For questions 13-15, use the following class definition import java.text.DecimalFormat; public class Student { private String name; private String major; private double gpa; private int hours; public Student(String newName, String newMajor, double newGPA, int newHours) { name = newName; major = newMajor; gpa = newGPA; hours = newHours; } public String toString( ) { DecimalFormat df = new DecimalFormat("xxxx"); // xxxx needs to be replaced return name + "\n" + major + "\n" + df.format(gpa) + "\n" + hours } } 13) Which of the following could be used to instantiate a new Student s1? a) Student s1 = new Student( ); b) s1 = new Student( ); c) Student s1 = new Student("Jane Doe", "Computer Science", 3.333, 33); d) new Student s1 = ("Jane Doe", "Computer Science", 3.333, 33); e) new Student(s1); Answer: c. Explanation: To instantiate a class, the object is assigned the value returned by calling the constructor preceded by the reserved word new, as in new Student( ). The constructor might require parameters, and for Student, the parameters must be are two String values, a double, followed by an int. 14) Assume that another method has been defined that will compute and return the student’s class rank (Freshman, Sophomore, etc). It is defined as: public String getClassRank( ) TB 38 Lewis/Loftus/Cocking: Chapter 4 Test Bank Given that s1 is a student, which of the following would properly be used to get s1’s class rank? a) s1 = getClassRank( ); b) s1.toString( ); c) s1.getHours( ); d) s1.getClassRank( ); e) getClassRank(s1); Answer: d. Explanation: To call a method of an object requires passing that object a message which is the same as the method name, as in object.methodname(parameters). In this situation, the object is s1, the method is getClassRank, and this method expects no parameters. Answers a and e are syntactically illegal while answer b returns information about the Student but not his/her class rank, and there is no “getHours” method so c is also syntactically illegal. 15) Another method that might be desired is one that updates the Student’s number of credit hours. This method will receive a number of credit hours and add these to the Student’s current hours. Which of the following methods would accomplish this? a) public int updateHours( ) { return hours; } b) public void updateHours( ) { hours++; } c) public updateHours(int moreHours) { hours += moreHours; } d) public void updateHours(int moreHours) { hours += moreHours; } e) public int updateHours(int moreHours) { return hours + moreHours; } Answer: d. Explanation: This method will receive the number of new hours and add this to the current hours. The method in d is the only one to do this appropriately. Answer c is syntactically invalid since it does not list a return type. The answer in e returns the new hours, but does not reset hours appropriately. The Coin class, as defined in Chapter 4, consists of a constructor, and methods flip, isHeads and toString. The method isHeads returns true if the last flip was a Heads, and false if the last flip was a Tails. The toString method returns a String equal to “Heads” or “Tails” depending on the result of the last flip. Using this information, answer questions 16 – 17 16) A set of code has already instantiated c to be a Coin and has input a String guess, from the user asking whether the user guesses that a coin flip will result in “Heads” or “Tails”. Which of the following sets of code will perform the coin flip and see if the user’s guess was right or wrong? a) c.flip( ); if(c.isHeads( ).equals(guess)) System.out.println("User is correct"); b) if(c.flip( ).equals(guess)) System.out.println("User is correct"); c) if(c.isHeads( ).equals(guess)) System.out.println("User is correct"); Lewis/Loftus/Cocking: Chapter 4 Test Bank TB 39 d) c.flip( ); if(c.toString( ).equals(guess)) System.out.println("User is correct"); e) c.flip( ).toString( ); if(c.equals(guess)) System.out.println("User is correct"); Answer: d. Explanation: c.flip( ) must be performed first to get a Coin flip. Next, the user’s guess is compared against the value of the Coin’s flip. The Coin c stores the result as an int and the user’s guess is a String. Using getFace( ) returns the int value but using the toString method will return the String “Heads” or “Tails”. So, the code compares c.toString( ) with the user’s guess using the String method equals. 17) What does the following code compute? int num = 0; for(int j = 0; j < 1000; j++) { c.flip( ); if(c.isHeads()) num++; } double value = (double) num / 1000; 1) the number of Heads flipped out of 1000 flips 2) the number of Heads flipped in a row out of 1000 flips 3) the percentage of heads flipped out of 1000 flips 4) the percentage of times neither Heads nor Tails were flipped out of 1000 flips 5) nothing at all Answer: c. Explanation: The code iterates 1000 times, flipping the Coin and testing to see if this flip was a 0 (“Heads”) or 1 (“Tails”). The variable num counts the number of Heads and the variable value is then the percentage of Heads over 1000. 18) In the Rational class, defined in chapter 4, the methods reduce and gcd are declared to be private. Why? a) Because they will never be used b) Because they will only be called from methods inside of Rational c) Because they will only be called from the constructor of Rational d) Because they do not use any of Rational’s instance data e) Because it is a typo and they should be declared as public Answer: b. Explanation: All items of a class that are declared to be private are only accessible to entities within that class, whether they are instance data or methods. In this case, since these two methods are only called from other methods (including the constructor) of Rational, they are declared private to promote information hiding to a greater degree. Note that answer c is not a correct answer because the reduce method calls the gcd method, so one of the methods is called from a method other than the constructor. Use the following information to answer questions 19 - 20. The Die class from chapter 4 has two constructors defined as follows. Assume MIN_FACES is an int equal to 4. public Die( ) public Die(int faces) {{ numFaces = 6; if(faces < MIN_FACES) numFaces = 6; faceValue = 1; else numFaces = faces; } faceValue = 1; } 19) The instruction Die d = new Die(10); results in a) The Die d having numFaces = 6 and faceValue = 1 b) The Die d having numFaces = 10 and faceValue = 1 c) The Die d having numFaces = 10 and faceValue = 10 d) The Die d having numFaces = 6 and faceValue = 10 e) A syntax error Answer: b. Explanation: Since an int parameter is passed to the constructor, the second constructor is executed, which sets numFaces = 10 (since numFaces >= MIN_FACES) and faceValue = 1. TB 40 Lewis/Loftus/Cocking: Chapter 4 Test Bank 20) The instruction Die d = new Die(10, 0); results in a) The Die d having numFaces = 6 and faceValue = 1 b) The Die d having numFaces = 10 and faceValue = 1 c) The Die d having numFaces = 10 and faceValue = 10 d) The Die d having numFaces = 6 and faceValue = 10 e) A syntax error Answer: e. Explanation: The Die class has two constructors, one that receives no parameters and one that receives a single int parameter. The instruction above calls the Die constructor with 2 int parameters. Since no constructor matches this number of parameters exists, a syntax error occurs. For questions 21 - 23, use the following class definition: public class Swapper { private int x; private String y; public int z; public Swapper(int a, String b, int c) { x = a; y = b; z = c; } public String swap( ) { int temp = x; x = z; z = temp; return y; } public String toString( ) { if (x < z) return y; else return "" + x + z; } } 21) If the instruction Swapper s = new Swapper(0, "hello", 0); is executed followed by s.toString( ); what value is returned from s.toString( )? a) "hello" b) "hello00" c) "00" d) "0" e) 0 Answer: c. Explanation: The toString method compares x and z, and if x < y it returns the String y. In this case, x == z, so the else clause is executed, and the String of "" + x + z is returned. This is the String "00". 22) Which of the following criticisms is valid about the Swapper class? a) The instance data x is visible outside of Swapper b) The instance data y is visible outside of Swapper c) The instance data z is visible outside of Swapper d) All 3 instance data are visible outside of Swapper e) None of the methods are visible outside of Swapper Lewis/Loftus/Cocking: Chapter 4 Test Bank TB 41 Answer: c. Explanation: We would expect none of the instance data to be visible outside of the class, so they should all be declared as “private” whereas we would expect the methods that make up the interface to be visible outside of the class, so they should all be declared as “public”. We see that z is declared “public” instead of “private”. 23) If we have Swapper r = new Swapper (5, "no", 10); then r.swap( ); returns which of the following? a) nothing b) "no" c) "no510" d) "510" e) "15" Answer: b. Explanation: The swap method swaps the values of x and z (thus x becomes 10 and z becomes 5) and returns the value of y, which is “no” for r. 24) Consider a method defined with the header: public void foo(int a, int b). Which of the following method calls is legal? a) foo(0, 0.1); b) foo(0 / 1, 2 * 3); c) foo(0); d) foo( ); e) foo(1 + 2, 3 * 0.1); Answer: b. Explanation: The only legal method call is one that passes two int parameters. In the case of answer b, 0 / 1 is an int division (equal to 0) and 2 * 3 is an int multiplication. So this is legal. The answers for a and e contain two parameters, but the second of each is a double. The answers for c and d have the wrong number of parameters. 25) Consider a method defined with the header: public void doublefoo(double x). Which of the following method calls is legal? a) doublefoo(0); b) doublefoo(0.555); c) doublefoo(0.1 + 0.2); d) doublefoo(0.1, 0.2); e) all of the above are legal except for d Answer: e. Explanation: In the case of a, the value 0 (an int) is widened to a double. In the case of c, the addition is performed yielding 0.3 and then doublefoo is called. The parameter list in d is illegal since it contains two double parameters instead of 1. True/False Questions: 1) Java methods can return only primitive types (int, double, boolean, etc). Answer: False. Explanation: Java methods can also return objects, such as a String. 2) Formal parameters are those that appear in the method call and actual parameters are those that appear in the method header. Answer: False. Explanation: The question has the two definitions reversed. Formal parameters are those that appear in the method header, actual parameters are the parameters in the method call (those being passed to the method). 3) All Java classes must contain a main method which is the first method executed when the Java class is called upon. Answer: False. Explanation: Only the driver program requires a main method. The driver program is the one that is first executed in any Java program (except for Applets), but it may call upon other classes as needed, and these other classes do not need main methods. 4) Java methods can return more than one item if they are modified with the reserved word continue, as in public continue int foo( ) { … } Answer: False. Explanation: All Java methods return a single item, whether it is a primitive data type an object, or void. The reserved word continue is used to exit the remainder of a loop and test the condition again. 5) The following method header definition will result in a syntax error: public void aMethod( ); Answer: True. Explanation: The reason for the syntax error is because it ends with a “;” symbol. It instead needs to be followed by { } with 0 or more instructions inside of the brackets. An abstract method will end with a “;” but this header does not define an abstract method. 6) A method defined in a class can access the class’ instance data without needing to pass them as parameters or declare them as local variables. Answer: True. Explanation: The instance data are globally available to all of the class’ methods and therefore the methods do not need to receive them as parameters or declare them locally. If variables of the same name as instance data were declared locally inside a method then the instance data would be “hidden” in that method because the references would be to the local variables. 7) The interface of a class is based on those data instances and methods that are declared public. Answer: True. Explanation: The interface is how an outside agent interacts with the object. Interaction is only available through those items declared to be public in the class’ definition. 8) Defining formal parameters requires including each parameters type. Answer: True. Explanation: In order for the compiler to check to see if a method call is correct, the compiler needs to know the types for the parameters being passed. Therefore, all formal parameters (those defined in the method header) must include their type. This is one element that makes Java a Strongly Typed language. 9) Every class definition must include a constructor. Answer: False. Explanation: Java allows classes to be defined without constructors, however, there is a default constructor that is used in such a case. 10) While multiple objects of the same class can exist, there is only one version of the class. Answer: True. Explanation: A class is an abstraction, that is, it exists as a definition, but not as a physical instance. Physical instances are created when an object is instantiated using new. Therefore, there can be many objects of type String, but only one String class. 11) A class may contain methods but not variable declarations. Answer: False. A class may contain both methods and variable declarations. 12) A constructor is a method that gets called automatically whenever an object is created, for example with the new operator. Answer: True. The constructor is used to initialize an object and it gets called whenever a new object is created from a particular class. 13) A constructor must have the same name as its class. Answer: True. A constructor is required to have the same name as the class. 14) A constructor must always return an int. Answer: False. In fact, a constructor cannot return anything. It has no return value, not even void. When a constructor is written, no return value should be listed. 15) A class’s instance data are the variables declared in the main method. Answer: False. A class’s instance data are declared in the class but not inside any method. Variables declared in a method are local to that method and can only be used in that method. Furthermore, every class need not have a main method. 16) The methods in a class should always be made public so that those outside the class can use them Answer: False. Methods that need to be available for use outside a class should be made public, but methods that will only be used inside the class should be made private. 17) The body of a method may be empty. Answer: True. The method body may have 0 or more instructions, so it could have 0. An empty method body is simply { } with no statements in between. 18) The return statement must be followed a single variable that contains the value to be returned. Answer: False. The return statement may be following by any expression whose type is the same as the declared return type in the method header. For example, return x*y+6; is a valid return statement. The statement return; is also valid for a method that does not return anything (void). 19) The number and types of the actual parameters must match the number and types of the formal parameters. Answer: True. The names of the corresponding actual and formal parameters may be different but the number and types of the parameters must match. 20) The different versions of an overloaded method are differentiated by their signatures. Answer: True. A method’s signature include the number, types, and order of its parameters. With overloaded methods, the name is the same, but the the methods must differ in their parameters. 21) If a method takes a double as a parameter, you could pass it an int as the actual parameter. Answer: True. Since converting from an int to a double is a widening conversion, it is done automatically, so there would be no error. 22) A method defined without a return statement will cause a compile error. Answer: False. If a method is declared to return void then it doesn’t need a return statement. However, if a method is declared to return a type other than void, then it must have a return statement. 23) The println method on System.out is overloaded. Answer: True. The println method includes versions that take a String, int, double, char, and boolean. 24) Method decomposition is the process of creating overloaded versions of a method that do the same thing, but operate on different data types. Answer: False. Method decomposition is breaking a complicated method into simpler methods to create a more understandable design. 25) An object may be made up of other objects. Answer: True. An aggregate object is an object that has other objects as instance data. Chapter 5: Enhancing Classes Multiple Choice: For questions 1-4, assume x and y are String variables with x = "Hello" and y = null. 1) The result of (x = = y) is a) true b) false c) a syntax error d) a run-time error e) x being set to the value null Answer: b. Explanation: x is a String instantiated to the value "Hello" and y is a String that has not yet been instantiated, so they are not the same String. (x = = y) is a condition, testing to see if x and y are the same String (that is, x and y reference the same item in memory), which they don't, so the result is false. 2) The result of x.length( ) + y.length( ) is a) 0 b) 5 c) 6 d) 10 e) a thrown exception Answer: e. Explanation: The statement y.length( ) results in a thrown NullPointException because it is not possible to pass a message to an object that is not currently instantiated (equal to null). 3) If the operation y = "Hello"; is performed, then the result of (x = = y) is a) true b) false c) x and y becoming aliases d) x being set to the value null e) a run-time error Answer: b. Explanation: While x and y now store the same value, they are not the same String, that is, x and y reference different objects in memory, so the result of the condition (x = = y) is false. 4) If the operation y = x; is performed, then the result of (x = = y) is a) true b) false c) x being set to the value null while y retains the value "Hello" d) y being set to the value null while x retains the value "Hello" e) x being set to y, which it is already since y = x; was already performed Answer: a. Explanation: When y = x; was performed, the two variables are now aliases, that is, they reference the same thing in memory. So, (x = = y) is now true. For questions 5-8, consider a class that stores 2 int values. These values can be assigned int values with the messages set1(x) and set2(x) where x is an int, and these values can be accessed through get1( ) and get2( ). Assume that y and z are two objects of this class. The following instructions are executed: y.set1(5); y.set2(6); z.set1(3); z.set2(y.get1( )); y = z; 5) The statement z.get2( ); will a) return 5 b) return 6 c) return 3 d) return 0 e) cause a run-time error Answer: a. Explanation: The statement y.get1( ) returns the value 5, and therefore the statement z.set2(y.get1( )) sets the second value of z to be 5, so that z.get2( ) returns 5. 6) The statement y.get2( ); will a) return 5 b) return 6 c) return 3 d) return 0 e) cause a run-time error Answer: a. Explanation: The statement y = z; causes y and z to be aliases where y.get2( ); returns the same value as z.get2( );. Since z.set2(y.get1( )); was performed previously, z and y's second value is 5. 7) If the instruction z.set2(y.get1( )); is executed, which of the following is true? a) (y = = z) is still true b) (y.get1( ) = = z.get1( )) but (y.get2( ) != z.get2( )) c) (y.get1( ) = = z.get1( )) and (y.get2( ) = = z.get2( )) but (y != z) d) (y.get1( ) = = z.get2( )) and (y.get2( ) = = z.get1( )) but (y != z) e) the statement causes a run-time error Answer: a. Explanation: Since y=z; was performed previously, y and z are aliases, so that a change to one results in a change to the other. The statement z.set2(y.get1( )); is essentially the same as z.set2(z.get1( )); or y.set2(y.get1( )); and in any case, it sets the second value to equal the first for the object which is referenced by both y and z. 8) If the instructions z.set2(5); and y.set1(10); are performed, which of the following is true? a) (y = = z) is still true b) (y.get1( ) = = z.get1( )) but (y.get2( ) != z.get2( )) c) (y.get1( ) = = z.get1( )) and (y.get2( ) = = z.get2( )) but (y != z) d) (y.get1( ) = = z.get2( )) and (y.get2( ) = = z.get1( )) but (y != z) e) this statement causes a run-time error Answer: a. Explanation: Since y=z; was peformed previously, y and z are aliases meaning that they refer to the same object. The statement z.set2(5); causes a change to the object's second value while y.set1(10); causes a change to the object's first value but neither change the fact that y and z are aliases. 9) Consider the following swap method. If String x = "Hello" and String y = "Goodbye", then swap(x, y); results in which of the following? public void swap(String a, String b) { String temp; temp = a; a = b; b = temp; } a) x is now "Goodbye" and y is now "Hello" b) x is now "Goodbye" and y is still "Goodbye", but (x != y) c) x is still "Hello" and y is now "Hello", but (x != y) d) x and y are now aliases e) x and y remain unchanged Answer: e. Explanation: When x and y are passed to swap, a and x become aliases and b and y become aliases. The statement temp = a sets temp to be an alias of a and x. The statement a = b sets a to be an alias of b and y, but does not alter x or temp. Finally, b = temp sets b to be an alias of temp and y, but does not alter y. Therefore, x and y remain the same. 10) Which of the following methods is a static method? The class in which the method is defined is given in parentheses following the method name. a) equals (String) b) toUpperCase (String) c) sqrt (Math) d) format (DecimalFormat) e) paint (Applet) Answer: c. Explanation: The Math class defines all of its methods to be static. Invoking Math methods is done by using Math rather than a variable of type Math. The other methods above are not static. 11) Static methods cannot a) reference instance data b) reference non-static instance data c) reference other objects d) invoke other static methods e) invoke non-static methods Answer: b. Explanation: A static method is a method that is part of the class itself, not an instantiated object, and therefore the static method is shared among all instantiated objects of the class. Since the static method is shared, it cannot access non-static instance data because all non-static instance data are specific to instantiated objects. A static method can access static instance data because, like the method, the instance data is shared among all objects of the class. A static method can also access parameters passed to it. For questions 12 – 13, use the following class definition: public class StaticExample { private static int x; public StaticExample (int y) { x = y; } public int incr( ) { x++; return x; } } 12) What is the value of z after the third statement executes below? StaticExample a = new StaticExample(5); StaticExample b = new StaticExample(12); int z = a.incr( ); a) 5 b) 6 c) 12 d) 13 e) none, the code is syntactically invalid because a and b are attempting to share an instance data Answer: d. Explanation: Since instance data x is shared between a and b, it is first initialized to 5, it is then changed to 12 when b is instantiated, and then it is incremented to 13 when a.incr( ) is performed. So, incr returns the value 13. 13) If there are 4 objects of type StaticExample, how many different instances of x are there? a) 0 b) 1 c) 3 d) 4 e) There is no way to know since any of the objects might share x, but they do not necessarily share x Answer: b. Explanation: Because x is a static instance data, it is shared among all objects of the StaticExample class, and therefore, since at least one object exists, there is exactly one instance of x. 14) An object that refers to part of itself within its own methods can use which of the following reserved words to denote this relationship? a) inner b) i c) private d) this e) static Answer: d. Explanation: The reserved word this is used so that an object can refer to itself. For instance, if an object has an instance data x, then this.x refers to the object’s value x. While this is not necessary, it can be useful if a local variable or parameter is named the same as an instance data. The reserved word this is also used to refer to the class as a whole, for instance, if the class is going to implement an interface class rather than import an implementation of an interface class. 15) Which of the following interfaces would be used to implement a class that represents a group (or collection) of objects? a) Iterator b) Speaker c) Comparable d) MouseListener e) KeyListener Answer: a. Explanation: Iterator is an abstract class allowing the user to extend a given class that implements Iterator by using the features defined there. These features include being able to store a group of objects and iterate (step) through them. 16) In order to implement Comparable in a class, what method(s) must be defined in that class? a) equals b) compares c) both lessThan and greaterThan d) compareTo e) both compares and equals Answer: d. Explanation: The Comparable class requires the definition of a compareTo method that will compare two objects and determine if one is equal to the other, or if one is less than or greater than the other and respond with a negative int, 0 or a positive int. Since compareTo responds with 0 if the two objects are equal, there is no need to also define an equals method. For questions 17-18, consider a class called ChessPiece. This class has two instance data, String type and int player. The variable type will store “King”, “Queen”, “Bishop”, etc and the int player will store 0 or 1 depending on whose piece it is. We wish to implement Comparable for the ChessPiece class. Assume that, the current ChessPiece is compared to a ChessPiece passed as a parameter. Pieces are ordered as follows: “Pawn” is a lesser piece to a “Knight” and a “Bishop”, “Knight” and “Bishop” are equivalent for this example, both are lesser pieces to a “Rook” which is a lesser piece to a “Queen” which is a lesser piece to a “King.” 17) Which of the following method headers would properly define the method needed to make this class Comparable? a) public boolean comparable(Object cp) b) public int comparable(Object cp) c) public int compareTo(Object cp) d) public int compareTo( ) e) public boolean compareTo(Object cp) Answer: c. Explanation: To implement Comparable, you must implement a method called compareTo which returns an int. Further, since this class will compare this ChessPiece to another, we would except the other ChessPiece to be passed in as a parameter (although compareTo is defined to accept an Object, not a ChessPiece). 18) Which of the following pieces of logic could be used in the method that implements Comparable? Assume that the method is passed Object a, which is really a ChessPiece. Also assume that ChessPiece has a method called returnType which returns the type of the given piece. Only one of these answers has correct logic. a) if (this.type < a.returnType( )) return –1; b) if (this.type = = a.returnType( )) return 0; c) if (this.type.equals(a.returnType( )) return 0; d) if (a.returnType( ).equals(“King”)) return -1; e) if (a.returnType( ).equals(“Pawn”)) return 1; Answer: c. Explanation: If the type of this piece and of a are the same type, then they are considered equal and the method should return 0 to indicate this. Note that this does not cover the case where this piece is a “Knight” and a is a “Bishop”, so additional code would be required for the “equal to” case. The answer in b is not correct because it compares two Strings to see if they are the same String, not the same value. The logic in d and e are incorrect because neither of these takes into account what the current piece is, only what the parameter’s type is. In d, if a is a “King”, it will be greater than this piece if this piece is not a “King”, but will be equal if this piece is a “King” and similarly in e, it does not consider if this piece is a “Pawn” or not. Finally, a would give a syntax error because two Strings cannot be compared using the “<” operator. 19) If s is a String, and s = “no”; is performed, then s a) stores the String “no” b) references the memory location where “no” is stored c) stores the characters ‘n’, ‘o’ d) stores an int value that represents the two characters e) stores the character ‘n’ and a reference to the memory location where the next character, ‘o’ is stored Answer: b. Explanation: Strings are objects and all objects in Java are referenced by the variable declared to be an object. That is, the variable represents the memory location where the object is stored. So, s does not directly store “no” or ‘n’, ‘o’, but instead stores a memory location where “no” is stored. 20) Assume that you are defining a class and you want to implement an ActionListener. You state addActionListener(this); in your class’ constructor. What does this mean? a) The class must import another class which implements ActionListener b) The class must define the method actionPerformed c) The class must define the method ActionListener d) The class must define an inner class called ActionListener e) The class must define the method actionPerformed in an inner class named ActionListener Answer: b. Explanation: Since the ActionListener being implemented is being added in this class (that is what the “this” refers to in addActionListener), then this class must define the abstract methods of the ActionListener class. There is only one abstract method, actionPerformed. The answer in a is not true, if the class that implements ActionListener were being imported (assume that the variable al is an instance of this imported class), then the proper statement would be addActionListener(al);. 21) A Java program can handle an exception in several different ways. Which of the following is not a way that a Java program could handle an exception? a) ignore the exception b) handle the exception where it arose using try and catch statements c) propagate the exception to another method where it can be handled d) throw the exception to a pre-defined Exception class to be handled e) all of the above are ways that a Java program could handle an exception Answer: d. Explanation: A thrown exception is either caught by the current code if the code is contained inside a try statement and the appropriate catch statement is implemented, or else it is propagated to the method that invoked the method that caused the exception and caught there in an appropriate catch statement, or else it continues to be propagated through the methods in the opposite order that those methods were invoked. This process stops however once the main method is reached. If not caught there, the exception causes termination of the program (this would be answer a, the exception was ignored). However, an exception is not thrown to an Exception class. 22) An exception can produce a “call stack trace” which lists a) the active methods in the order that they were invoked b) the active methods in the opposite order that they were invoked TB 52 Lewis/Loftus/Cocking: Chapter 5 Test Bank c) the values of all instance data of the object where the exception was raised d) the values of all instance data of the object where the exception was raised and all local variables and parameters of the method where the exception was raised e) the name of the exception thrown Answer: b. Explanation: The call stack trace provides the names of the methods as stored on the run-time stack. The method names are removed from the stack in the opposite order that they were placed, that is, the earliest method was placed there first, the next method second, and so forth so that the most recently invoked method is the last item on the stack, so it is the first one removed. The stack trace then displays all active methods in the opposite order that they were called (most recent first). 23) In order to have some code throw an exception, you would use which of the following reserved words? a) throw b) throws c) try d) Throwable e) goto Answer: a. Explanation: The reserved word throw is used to throw an exception when the exception is detected, as in: if (score < 0) throw new IllegalTestScoreException(“Input score ” + score + “ is negative”); 24) JOptionPane is a class that provides GUI a) dialog boxes b) buttons c) output fields d) panels and frames e) all of the above Answer: a. Explanation: the JOptionPane class contains three formats of dialog boxes, an input dialog box that prompts the user and inputs String text, a message dialog box that outputs a message, and a confirm box that prompts the user and accepts a Yes or No answer. 25) A listener is an object that a) implements any type of interface b) is used to accept any form of input c) is an inner class to a class that has abstract methods d) waits for some action from the user e) uses the InputStreamReader class Answer: d. Explanation: The listener “listens” for a user action such as a mouse motion, a key entry or an activation of a GUI object (like a button) and then responds appropriately. Listeners allow us to write programs that interact with the user whenever the user performs an operation as opposed to merely seeking input from the user at pre-specified times. Chapter 6: Arrays Multiple Choice Questions: For questions 1-4, assume values is an int array that is currently filled to capacity, with the following values: 1) What is returned by values[3]? a) 9 b) 12 c) 2 d) 6 e) 3 Answer: c. Explanation: Java array indices start at 0, so values[3] is really the fourth array element, which is 2. 2) What is the value of values.length? a) 0 b) 5 c) 6 d) 7 e) 18 Answer: d. Explanation: The length operator for an array returns the size of the array. The above picture shows that that values stores 7 elements and since it is full, the size of values is 7. 3) Which of the following loops would adequately add 1 to each element stored in values? a) for(j=1;j<values.length;j++) values[j]++; b) for(j=0;j<values.length;j++) values[j]++; c) for(j=0;j<=values.length;j++) values[j]++; d) for(j=0;j<values.length–1;j++) values[j]++; e) for(j=1;j<values.length–1;j++) values[j]++; Answer: b. Explanation: The first array element is values[0], so the for-loop must start at 0, not 1. There are values.length elements in the array where the last element is at values.length–1, so the for loop must stop before reaching values.length. This is the case in b. In d, the for loop stops 1 before values.length since “<” is being used to test the condition instead of <=. 4) The statement System.out.println(values[7]); will a) output 7 b) output 18 c) output nothing d) cause an ArrayOutOfBoundsException to be thrown e) cause a syntax error Answer: d. Explanation: The array has 7 values, but these are indexed values[0] to values[6]. Since values[7] is beyond the bounds of the array, values[7] causes an ArrayOutOfBoundsException to be thrown. 5) Which of the following is a legal way to declare and instantiate an array of 10 Strings? a) String s = new String(10); b) String[10] s = new String; c) String[ ] s = new String[10]; d) String s = new String[10]; e) String[ ] s = new String; 9 4 12 2 6 8 18 Answer: c. Explanation: Declaring an array is done by type[ ] variable. Instantiating the array is done by variable = new type[dimension] where dimension is the size of the array. 6) In Java, arrays are a) primitive data types b) objects c) interfaces d) primitive data types if the type stored in the array is a primitive data type and objects if the type stored in the array is an object e) Strings Answer: b. Explanation: In Java, arrays are implemented as objects. The variable is a reference variable to the block of memory that stores the entire array. However, arrays are accessed using the notation name[index] rather than by message passing. 7) The “off-by-one” error associated with arrays arises because a) the first array index is 0 and programmers may start at index 1, or may use a loop that goes one index too far b) the last array index is at length + 1 and loops may only iterate to length, missing one c) the last array element ends at length – 1 and loops may go one too far d) programmers write a loop that goes from 0 to length – 1 whereas the array actually goes from 1 to length e) none of the above, the “off-by-one” error has nothing to do with arrays Answer: a. Explanation: The array is initialized as = new type[x] where x is the size of the array. However, the array has legal indices of 0 to x – 1 and so, programmers are often off-by-one because programmers will write code to try to access indices 1 to x. 8) What does the following code do? Assume list is an array of int values, temp is some previously initialized int value, and c is an int initialized to 0. for(j=0;j<list.length.j++) if(list[j] < temp) c++; a) It finds the smallest value and stores it in temp b) It finds the largest value and stores it in temp c) It counts the number of elements equal to the smallest value in list d) It counts the number of elements in list that are less than temp e) It sorts the values in list to be in ascending order Answer: d. Explanation: The statement if(list[j]<temp) c++; compares each element in list to temp and adds one to c only if the element is less than temp, so it counts the number of elements in list less than temp, storing this result in c. An int array stores the following values. Use the array to answer questions 9 – 12. 9) Which of the following lists of numbers would accurately show the array after the first pass through the Selection Sort algorithm? a) 9, 4, 12, 2, 6, 8, 18 b) 4, 9, 12, 2, 6, 8, 18 c) 2, 4, 12, 9, 6, 8, 18 d) 2, 4, 6, 8, 9, 12, 18 e) 2, 4, 9, 12, 6, 8, 18 Answer: c. Explanation: On each successive pass of Selection Sort, the smallest of the unsorted values is found and swapped with the current array index (where the current index starts at 0 and goes until the second to last position in the array). On the first pass, the smallest element, 2, is swapped with index 0, so 2 and 9 swap places. 9 4 12 2 6 8 18 10) Which of the following lists of numbers would accurately show the array after the second pass of the Selection Sort algorithm? a) 9, 4, 12, 2, 6, 8, 18 b) 2, 4, 9, 6, 12, 8, 18 c) 2, 4, 12, 9, 6, 8, 18 d) 2, 4, 6, 8, 9, 12, 18 e) 2, 4, 12, 6, 8, 9, 18 Answer: c. Explanation: After one pass, the array would be 2, 4, 12, 9, 6, 8, 18. The second pass would look to swap the item in array index 1 (4) with the smallest value after 2 (4). So, 4 would swap with 4 and the array would stay the same as it was after the first pass. 11) Which of the following lists of numbers would accurately show the array after the fourth pass of the Selection Sort algorithm? a) 9, 4, 12, 2, 6, 8, 18 b) 2, 4, 6, 9, 12, 8, 18 c) 2, 4, 6, 8, 9, 12, 18 d) 2, 4, 6, 9, 8, 12, 18 e) 2, 4, 6, 8, 12, 9, 18 Answer: e. Explanation: The array would be sorted as follows: First pass: 2, 4, 12, 9, 6, 8, 18. Second pass: 2, 4, 12, 9, 6, 8, 18. Third pass: 2, 4, 6, 9, 12, 8, 18. Fourth pass: 2, 4, 6, 8, 12, 9, 18. 12) How many passes will it take in all for Selection Sort to sort this array? a) 2 b) 4 c) 5 d) 6 e) 7 Answer: d. Explanation: The Selection Sort uses two for-loops where the outer loop iterates through each array index except for the last one. So it makes a total of n – 1 passes where n is the number of items in the array. Since this array has 7 elements, the outer loop iterates 6 times, or requires 6 passes. You might notice that in fact this array is sorted after only 5 passes, but the Selection Sort algorithm will still make 6 passes (even if the array had been sorted after only 1 pass, it would still make 6 passes!) For questions 13 – 15, assume an int array, candy, stores the number of candy bars sold by a group of children where candy[j] is the number of candy bars sold by child j. Assume there are 12 children in all. 13) What does the following code do? int value1 = Keyboard.readInt( ); int value2 = Keyboard.readInt( ); bars[value1] += value2; a) adds 1 to the number of bars sold by child value1 and child value2 b) adds 1 to the number of bars sold by child value1 c) adds value1 to the number of bars sold by child value2 d) adds value2 to the number of bars sold by child value1 e) inputs a new value for the number of bars sold by both child value1 and child value2 Answer: d. Explanation: bars[value1] is the number of bars sold by child value1, and += value2 adds to this value the amount input for value2. 14) Which of the following code could be used to compute the total number of bars sold by the children? a) for(int j=0; j<12; j++) sum+= candy[j]; b) for(int j=0; j<12; j++) candy[j] = sum; c) for(int j=0; j<12; j++) sum = candy[j]; d) for(int j=0; j<12; j++) sum += [j]; e) for(int j=0; j<12; j++) [j] += sum; Answer: a. Explanation: The code in a iterates through all 12 elements of candy, adding each value to sum. The answer in b sets all 12 elements of candy equal to sum, the answer in c sets sum to be each element of candy, resulting in sum = candy[11] and d and e have syntactically invalid code. TB 62 Lewis/Loftus/Cocking: Chapter 6 Test Bank 15) What does the following method do? public int question15( ) { int value1 = 0; int value2 = 0; for(int j=0; j<12; j++) if(candy[j] > value1) { value1 = candy[j]; value2 = j; } return value2; } a) It returns the total number of candy bars sold b) It returns the total number of children who sold 0 candy bars c) It returns the total number of children who sold more than 0 candy bars d) It returns the number of candy bars sold by the child who sold the most candy bars e) It returns the index of the child who sold the most candy bars Answer: e. Explanation: The loop iterates through all 12 array elements. If a particular value of candy is found to be larger than value1, then this new value is remembered in value1 along with the index of where it was found in value2. As the loop continues, if a new candy value is found to be greater than the current value1, then it is remembered instead, so the loop finds the maximum number of candy bars sold in value1 and the child’s index who sold the most in value2. Since value2 is returned, the code returns the index of the child who sold the most. 16) We compare sorting algorithms by examining a) the number of instructions executed by the sorting algorithm b) the number of instructions in the algorithm itself (its length) c) the types of loops used in the sorting algorithm d) the amount of memory space required by the algorithm e) whether the resulting array is completely sorted or only partially sorted Answer: a. Explanation: Different sorting algorithms require a different number of instructions when executing. The Selection Sort for instance usually requires more instructions than the Insertion Sort. So, we compare sorting algorithms by the number of instructions that each takes to execute to sort the array. We might count the maximum number of instructions that a sorting algorithm will execute in the worst case, or the minimum number in the best case, or count on average the number of instructions executed. If two sorting algorithms require roughly the same number of instructions to sort an array, then we might also examine the amount of memory space required. 17) Both the Insertion Sort and the Selection Sort algorithms have efficiencies on the order of ____ where n is the number of values in the array being sorted. a) n b) n * log n c) n2 d) n3 e) Insertion sort has an efficiency of n and Selection Sort has an efficiency of n 2 Answer: c. Explanation: Both sorting algorithms use two nested loops which both execute approximately n times apiece, giving a complexity of n * n or n2 for both. 18) Consider the array declaration and instantiation: int[ ] arr = new int[5]; Which of the following is true about arr? a) It stores 5 elements with legal indices between 1 and 5 b) It stores 5 elements with legal indices between 0 and 4 c) It stores 4 elements with legal indices between 1 and 4 d) It stores 6 elements with legal indices between 0 and 5 e) It stores 5 elements with legal indices between 0 and 5 Answer: b. Explanation: Arrays are instantiated with an int value representing their size, or the number of elements that they can store. So, arr can store 5 elements. Further, all arrays start at index 0 and go to index size – 1, so arr has legal indices of 0 through 4. 19) If an int array is passed as a parameter to a method, which of the following would adequately define the parameter list for the method header? a) (int[ ]) b) (int a[ ]) c) (int[ ] a) d) (int a) e) (a[ ]) Answer: c. Explanation: The parameter is defined much as the variable is originally declared, as type parameter name. Here, the type is int[ ] and the parameter is a. 20) If int[ ] x = new int[15]; and the statement x[-1] = 0; is executed, then which of the following Exceptions is thrown? a) IndexOutOfBoundsException b) ArrayIndexOutOfBoundsException c) NegativeArraySizeException d) NullPointException e) ArithmeticException Answer: b. Explanation: The array index is out of bounds as the array index can only be between 0 and 14. –1 is an illegal index because it is out of bounds. One might expect the answer to be c, but the NegativeArraySizeException is thrown if an array is being declared with a negative number of elements as in int[ ] x = new int[-5]; 21) Assume that BankAccount is a predefined class and that the declaration BankAccount[ ] firstEmpireBank; has already been performed. Then the following instruction reserves memory space for firstEmpireBank = new BankAccount[1000]; a) a reference variable to the memory that stores all 1000 BankAccount entries b) 1000 reference variables, each of which point to a single BankAccount entry c) a single BankAccount entry d) 1000 BankAccount entries e) 1000 reference variables and 1000 BankAccount entries Answer: b. Explanation: The declaration BankAccount[ ] firstEmpireBank; reserves memory space for firstEmpireBank, which itself is a reference variable that points to the BankAccount[ ] object. The statement firstEmpireBank = new BankAccount[1000]; instantiates the BankAccount[ ] object to be 1000 BankAccount objects. This means that firstEmpireBank[0] and firstEmpireBank[1] and firstEmpireBank[999] are all now legal references, each of which is a reference variable since each references a BankAccount object. So, the statement reserves memory space for 1000 reference variables. Note that none of the 1000 BankAccount objects are yet instantiated, so no memory has been set aside yet for any of the actual BankAccount objects. 22) The following code accomplishes which of the tasks written below? Assume list is an int array that stores positive int values only. foo = 0; for(j=0; j<list.length; j++) if (list[j] > foo) foo = list[j]; a) it stores the smallest value in list (the minimum) in foo b) it stores the largest value in list (the maximum) in foo c) it stores every value in list, one at a time, in foo, until the loop terminates d) it counts the number of elements in list that are greater than foo e) it counts the number of elements in list that are less than foo Answer: b. Explanation: The condition in the if statement tests to see if the current element of list is greater than foo. If so, it replaces foo. The end result is that every element in list is tested and foo stores the largest element up to that point, so eventually, foo will be the largest value in the array list. 23) If x is a char, and values is an int array, then values[x] a) causes a syntax error b) causes an Exception to be thrown c) casts x as an int based on x’s position in the alphabet (for instance, if x is ‘a’ then it uses 0 and if x is ‘z’ then it uses 25) d) casts x as an int based on x’s Unicode value (for instance, if x is ‘a’ then it uses 97 and if x is ‘z’ then it uses 122) e) casts x as an int based on the digit that is stored in x (for instance, if x is ‘3’ it uses 3) but throws an exception if x does not store a digit Answer: d. Explanation: An array index must be an int value, so normally values[x] would cause a syntax error if x were not an int, but the Java compiler will automatically cast x to be an int if it can be cast. Characters are cast as ints by converting the char value to its equivalent Unicode value. So, if x is ‘a’, it is cast as the int 97 instead and so values[x] accesses values[97]. 24) To initialize a String array names to store the three Strings “Huey”, “Duey” and “Louie”, you would do a) String names = {“Huey”, “Duey”, “Louie”}; b) String[ ] names = {“Huey”, “Duey”, “Louie”}; c) String[ ] names = new String{“Huey”, “Duey”, “Louie”}; d) String names[3] = {“Huey”, “Duey”, “Louie”}; e) String names; names[0] = “Huey”; names[1] = “Duey”; names[2] = “Louie”; Answer: b. Explanation: An array does not have to be instantiated with the reserved word new if it is instantiated with the list of values it is to store. So, names = {“Huey”, “Duey”, “Louie”}; will create a String array of 3 elements with the three values already initialized. Of the other answers, a does not specify that names is a String array, c should not have the reserved word new, d should not have [3] after names and omits [ ] after String, and e does not instantiate the array as String[3], and thus , all four of these other answers are syntactically invalid. 25) To declare a two-dimensional int array called threeD, which of the following would you use? a) int[2] twoD; b) int[ , ] twoD; c) int[ ][ ] twoD; d) int [ [ ] ] twoD; e) int[ ] twoD[2]; Answer: c. Explanation: In Java, you can only declare one-dimensional arrays. To create a two-dimensional array, you must declare it as an array of arrays. The proper notation is to declare the type of array using multiple [ ] marks in succession, as in int[ ][ ] for a two-dimensional array.