C - M - Combo

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

1) A Java program is best classified as a) hardware b) software c) storage d) processor e) input

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.)

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

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.)

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

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.)

27) What is a mutator method? a) A method that modifies a value. b) A method that provides read-only access to a value. c) A method that has the same name, but different parameters, as another method. d) A method that is called when an object is first created. e) A method that does not return a value.

a. (Explanation: A mutator method, from the verb to mutate, or change, is a method that modifies a value.)

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

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.)

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

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.)

11) Of the following list, which one is not true regarding Java as a programming language? 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

b. (Explanation: All languages require translation into machine language. The other statements are all true about Java.)

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

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).)

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

a. (Explanation: 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.)

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

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.)

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

a. (Explanation: If a semicolon is missing where one should be present, the compiler will generate a syntax error.)

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

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.)

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

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.)

17) Which of the following would be a legal Java identifier? a) i b) class c) ilikeclass! d) idon'tlikeclass e) i-like-class

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.)

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

a. (Explanation: 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. )

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"); } }) 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

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 +.)

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

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.)

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; 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

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.)

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; 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

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.)

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

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. )

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

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.)

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

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");)

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; 6) The statement y.get2( ); will a) return 5 b) return 6 c) return 3 d) return 0 e) cause a run-time error

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.)

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

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.)

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

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. )

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

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.)

5) Volatility is a property of a) RAM b) ROM c) disk d) software e) computer networks

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. )

For questions 1-4, assume x and y are String variables with x = "Hello" and y = null. 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

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 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; } }) 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

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.)

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.

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. )

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

b. (Explanation: 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.)

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

b. (Explanation: Determining which classes and objects to use or create is part of the design.)

22) Which of the following is a legal Java identifier? a) 1ForAll b) oneForAll c) one/4/all d) 1_4_all e) 1forall

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. )

19) In the String major = "Computer Science", what is returned by major.charAt(1)? a) 'C' b) 'o' c) 'm' d) "C" e) "Computer"

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'.)

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

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.)

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

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.)

Given the nested if-else structure below, answer questions 8-10. if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2;) 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

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.)

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

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.)

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

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);.)

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

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.)

Consider the following paint method and answer questions 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

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).)

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

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.)

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

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. )

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"); } }) 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"

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.)

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

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". )

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 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

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).)

import java.util.Scanner; public class Questions { public static void main(String[ ] args) { int x, y, z; double average; Scanner scan = new Scanner (System.in); System.out.println("Enter an integer value"); x = scan.nextInt( ); System.out.println("Enter another integer value"); y = scan.nextInt( ); System.out.println("Enter a third integer value"); z = scan.nextInt( ); average = (x + y + z) / 3; System.out.println("The result of my calculation is " + average); } }) 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

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.)

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

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.)

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);

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.)

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

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).)

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; } } 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"

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.)

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"); } }) 3) How many lines of output are provided by this program? a) 1 b) 2 c) 3 d) 4 e) 5

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.)

For questions 1-4, assume x and y are String variables with x = "Hello" and y = 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

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.)

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--;

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.)

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

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.)

Question 26 refers to the following method:) public int dogYears (int age) { if (age >= 0) return age * 7; else return 0; }) 26) What would be an appropriate precondition for the method? a) // Precondition: tells how old your dog is b) // Precondition: age is someone's age c) // Precondition: age >= 0 d) // Precondition: age is an int e) // Precondition: returns age * 7

c. (Explanation: A precondition is a condition that should be true before a method begins executing. That rules out a and e. Choice d is not appropriate because the parameter list already states that age is an int. Choice b doesn't need to be true for the method to work properly. Choice c is the best choice since age should be >= 0 for the results of the method to make sense.)

import java.util.Scanner; public class Questions { public static void main(String[ ] args) { int x, y, z; double average; Scanner scan = new Scanner (System.in); System.out.println("Enter an integer value"); x = scan.nextInt( ); System.out.println("Enter another integer value"); y = scan.nextInt( ); System.out.println("Enter a third integer value"); z = scan.nextInt( ); 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

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.)

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

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.)

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

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.)

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.") 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;

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.)

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

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.)

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

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.)

21) Which of the following would be a good variable name for the current value of a stock? a) curstoval b) theCurrentValueOfThisStockIs c) currentStockVal d) csv e) current

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.)

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

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.)

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);

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.)

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

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.)

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) +, -, *, /

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 -.)

Given the nested if-else structure below, answer questions 8-10. 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

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. )

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"

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".)

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)

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.)

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) 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

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.)

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))

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.)

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

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. )

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

c. (Explanation: 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.)

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

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".)

26) Considering the (incomplete) code below, x is probably while (x.hasNext()) { ... x.next() ... ... } a) a primitive type b) a String c) an iterator d) a random number generator e) a file

c. (Explanation: The while (x.hasNext()) and x.next() are typical of how an iterator is used. Iterators are used to iterate through a collection of items.)

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)

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).)

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);

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.)

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; } } 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

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".)

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

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.)

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);

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.)

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

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.)

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

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.)

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

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.)

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

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.)

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

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. )

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

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.)

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

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.)

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

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.)

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( ));

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.)

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)

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.)

19) How many times will the following loop iterate?) 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

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.)

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

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.)

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

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.)

24) 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

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.)

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

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.)

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 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

d. (Explanation: The problem with this code is that it consists of three if statements followed by one if-else 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.)

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

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.)

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

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.)

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

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.)

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));

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 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 }}) 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; }

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.)

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 }}) 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( ) 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);

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.)

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

d. (Explanation: 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.)

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

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!)

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

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.)

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.

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.

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");) 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");)

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.)

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

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.)

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

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.)

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

e. (Explanation: All information in a computer is stored in binary, that is, using 0s and 1s.)

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

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.)

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

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.)

15) Which character below is not allowed in an identifier? a) $ b) _ c) 0 (zero) d) q e) ^

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.)

Given the nested if-else structure below, answer questions 8-10. if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 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

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.)

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

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.)

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

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. )

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; }) 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

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.)

11) Instance data for a Java class a) are limited to primitive types (e.g., int, double, char) b) are limited to Strings 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

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.)

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

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.)

For questions 1-4, assume x and y are String variables with x = "Hello" and y = null. 2) The result of x.length( ) + y.length( ) is a) 0 b) 5 c) 6 d) 10 e) a thrown exception

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). )

Consider the following paint method and answer questions 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); }) 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

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.)

17) If you want to store into the String name the value "George Bush", you would use 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

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.)

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

e. (Explanation: This is a java utility, and so is found in the java.util package.)

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

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.)

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

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.)

2) 6 bits can be used to represent ___ distinct items or values a) 6 b) 20 c) 24 d) 32 e) 64

e. (Explanation: With n bits, we can represent 2n different values. 26 = 64.)


संबंधित स्टडी सेट्स

A&P 1 Exam 4: Chapter 10, 11, and 12

View Set

N128 Week 3 - Lewis Adaptive Quizzing #1

View Set

Inequality social insurance and redistribution: practice problems

View Set

Chapter 13 - Labor and Birth Processes

View Set