Mid-Term study guide chapter 1 Multiple Choice Questions


Chapter 3: Program Statements



Download 325.47 Kb.
Page2/4
Date31.01.2017
Size325.47 Kb.
#13210
1   2   3   4

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.


Directory: cms -> lib4 -> va01000195 -> centricity -> domain
domain -> Pages 816-820 Truman’s domestic policies after the war—Truman was tasked with reconversion to a peacetime economy and introducing his domestic agenda
domain -> Pioneers of Sports & Entertainment Industries Matching Exercise
domain -> Unit 3: Introduction to Sports & Entertainment Business Principles
domain -> Apush period two key concepts review (1607-1754) This review refers to some examples we did not go over in class – so don’t stress about those!
domain -> The Sound of the Sea Henry Wadsworth Longfellow
domain -> Apush period one key concepts review (1491-1607) This review refers to some examples we did not go over in class – so don’t stress about those!
domain -> The Space Program Notes nasa
domain -> And Then There Were None Name: By Agatha Christie Guided Reading Questions Chapters 1, 2, & 3

Download 325.47 Kb.

Share with your friends:
1   2   3   4




The database is protected by copyright ©ininet.org 2024
send message

    Main page