j

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

if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2; 4) If x is currently 0, a = 5 and b = 5, what will x become after the above statement is executed?

C) 3

30) Which of the following statements are true about Java loops?

C) all three loop statements are functionally equivalent

2) Of the following if statements, which one correctly executes three instructions if the condition is true?

D) if (x < 0) { a = b * 2; y = x; z = a - y; }

21) If x is currently equal to 5, what will the value of x be after the switch statement executes?

D) 11

14) Every Interator

D) has a hasNext( ) method

A for statement is normally used when you do not know how many times the loop should be executed.

F. A for statement is normally used when you do know how many times the loop should be executed.

In Java, it is possible to create an infinite loop out of while and do loops but not for loops.

F. It is true that while and do loops can be infinite loops, but it is also true that Java for loops can be infinite loops. This is not true in some other programming languages where for loops have a set starting and ending point, but Java for loops are far more flexible than most other language's for loops.

A conditional operator is virtually the same as a switch statement.

F. The conditional operator is more like an if-else statement.

A switch statement must have a default clause.

F. The default clause is optional.

For the questions below, assume that boolean done = false, int x = 10, int y = 11, String s = "Help" and String t = "Goodbye". The expression (s.concat(t).length( ) < y) is true. T OR F

False

For the questions below, assume that boolean done = false, int x = 10, int y = 11, String s = "Help" and String t = "Goodbye". The expression (done | | s.compareTo(t) < 0) is true.

False

For the questions below, assume that boolean done = false, int x = 10, int y = 11, String s = "Help" and String t = "Goodbye". The expression (s.concat(t).length( ) < y) is true.

False

If String x = null; then x.length( ); returns the int 0.

False

In order to compare int, float and double variables, you can use <, >, ==, !=, <=, >=, but to compare char, and String variables, you must use compareTo ( ), equals ( ) and-equalsIsIgnoreCase ( )

False

In order to create a constant, you would use the static reserved word.

False

In order to preserve encapsulation of an object we would make the class final.

False

It is not possible to test out any single method or class of a system until the entire system has been developed, and so all testing is postponed until after the implementation phase. Select one: True False

False

Java is a case-sensitive language meaning that Current, current, and CURRENT will all reference the same identifier.

False

T/F: Every class definition must include a constructor.

False

T/F: Formal parameters are those that appear in the method call and actual parameters are those that appear in the method header.

False

T/F: Java methods can return more than one item if they are modified with the reserved word continue, as in public continue int foo( ) { ... }

False

T/F: Java methods can return only primitive types.

False

The expression a || b will be true if either a or b is true, but not if both are true.

False

The mod operate, %, can only be performed on int values and its result is a double.

False

The operators * and + have the same precedence.

False

The word "Public" is a reserved word.

False

Variables should never be static

False

When an int is passed as a parameter, the formal and actual parameters become aliases of each other

False

if first and last are both String variables, then first.equals(last); does the same thing as (first == last)

False

Java methods can return more than one item if they are modified with the reserved word continue, as in public continue int foo() {...}

False, all java methods return a single item

A switch statement must have a default clause

False, default clause is optional

Java can only return primitive types

False, it can return objects such as a string

Assume that boolean done = false, int x = 10, int y = 11, String s = "Help" and String t = "Goodbye". Then the expression (s.concat(t).length() < y)is true

False; Concatenating s and t gives a String that is 11 characters long and 11 < 11 is false.

Assume that boolean done = false, int x = 10, int y = 11, String s = "Help"and String t = "Goodbye". Then the expression (done || s.compareTo(t) < 0) is true.

False; both done is false and s.compareTo(t) < 0 is false since s does not come before t alphabetically, so the entire expression is false.

The idea that program instructions execute in order (linearly) unless otherwise specified through a conditional statement is known as

Flow of control

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

Math.sqrt(Math.abs(x));

If a programmer follows the four phases of program development as intended, which of the four phases should require the least amount of creativity?

Software implementation

c

Sometimes the superclass data fields and methods are not entirely appropriate for the subclass objects; in these cases, you want to ____ the parent class members. a. overload b. overrule c. override d. hide

Assume that the class Bird has a static method fly( ). If b is a Bird, then to invoke fly, you could do Bird.fly( );. Select one: True False

Static methods are invoked through the class and not an object of the class. This is because the static method is shared among all instances. So, Bird.fly( ); will invoke fly. It should be noted that fly can also be invoked through b, so b.fly( ); will also work. The correct answer is 'True'.

The following for loop is an infinite loop: for(int j = 0; j < 1000;) i++;

T This loop initializes j to 0 and compares it to 1000, but does not alter j after each loop iteration. In reality, the loop will terminate with a run-time error eventually once i becomes too large to store in memory, but logically, this is an infinite loop.

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

currentStockVal

The idea that a program instructions execute in order unless otherwise specified through a conditional statement is known as ________.

flow of control

The idea that program instructions execute in order (linearly) unless otherwise specified through a conditional statement is known as

flow of control

45) Write a set of code that outputs all of the int values between 1 and 100 with 5 values per line, and each of those 5 values spaced out equally. Use a single for-loop to solve this problem.

for (int j = 1; j <= 100; j++) { System.out.print(j + "\t"); if (j % 5 == 0) System.out.println( ); }

Write a for loop that prints the odd numbers from 1 to 99 (inclusive)

for (int j = 1; j <=99; j++) { if (j % 2 == 1) { System.out.println (j); } }

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 these

be insightful and explain what the instruction's intention is

If "Swapper r = new Swapper(5, "no", 10);", then "r.swap()" returns what?

"no"

If we have Swapper r = new Swapper (5, "no", 10); then r.swap( ); returns which of the following?

"no"

Use the following class definition: public class StaticExample { private static int x; public StaticExample (int y) { x = y; } public int incr( ) { x++; return x; } } 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( );

13

Convert these binary numbers into the decimal system: 00001110 10000001 10011001 11111110

14, 129, 153, 254

10) 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) statement2 will only execute if condition1 is false and condition2 is false

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? A) (s.charAt(0) = = s.charAt(s.length( ))) B) (s.charAt(1) = = s.charAt(s.length( ))) C) (s.charAt(0) = = s.charAt(s.length( ) - 1)) D) (s.charAt(0) = = s.charAt(s.length( ) + 1)) E) (s.charAt(0) = = s.charAt(last))

(s.charAt(0) = = s.charAt(s.length( ) - 1))

18) You might choose to use a switch statement instead of nested if-else statements if

A) the variable being tested might equal one of only a few int values

13) If a break occurs within the innermost loop of a nested loop that is three levels deep

A) when the break is encountered just the innermost loop is "broken"

23) The statement if (x < 0) y = x; else y = 0; can be rewritten using a conditional operator as

A) y = (x < 0) ? x : 0

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?

(s.charAt(0) == s.charAt(s.length( ) - 1))

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)

(s1.length( ) = = s2.length( ))

Given two String variables, s1 and s2, to determine if they are the same length, which of the following conditions would you use?

(s1.length( ) == s2.length( ))

public int dogYears(int age) { if(age>=0) return age*7; else return 0; } 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

// Precondition: age >= 0

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;

10

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

10

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;

10 times

How many times will the following loop iterate? int x = 10; while (x > 0) { System.out.println(x); x--; }

10 times

How many times will the following loop iterate? int x = 10; while (x > 0) { System.out.println(x); x--; }

10 times

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 time D) 10 times E) 11 times

10 times

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

10,000

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

10,000

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

12,000,000 megabytes

If x is an int where x = 1, what will x be after the following loop terminates? while (x < 100) x *= 2;

128

If x is an int where x = 1, what will x be after the following loop terminates? while (x < 100) x *= 2;

128

If x is an int where x = 1, what will x be after the following loop terminates? while (x<100) x* = 2

128

If x is an int where x = 1, what will x be after the following loop terminates? while (x < 100) x *= 2;

128

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; } } 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( ); 5 6 12 13 none, the code is syntactically invalid because a and b are attempting to share an instance data

13

If x is currently 0, a = 1 and b = -1, what will x become after the above statement is executed? if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2;

5

This paint method will draw several bars (sort of like a bar graph). How many bars will be displayed? public void paintComponent(Graphics page) { int x,y = 200; page.setColor(Color.blue); for(x = 100;x<200;x+=20) page.fillRect(x,y,10,y-x); } A) 4 B) 5 C) 6 D) 10 E) 20

5

if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2; If x is currently 0, a = 1 and b = -1, what will x become after the above statement is executed?

5

if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2; If x is currently 0, a = 1 and b = -1, what will x become after the above statement is executed?

5

if(a>0) if(b<0) x = x + 5; else if(a>5) x = x + 4; else x = x + 3; else x = x + 2; 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

5

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); } This paint method will draw several bars (sort of like a bar graph). How many bars will be displayed?

5

38) How many times will the System.out.println(*); statement execute inside of the following nested for-loops? for (j=0; j<10; j++) for (k=10;k>j;k--) System.out.println("*");

55

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

The original IBM personal computer had 256 KB of RAM. About how many times more RAM does a more modern computer with 2 GB of RAM have?

8192

How many bits are there in 12 KB?

98,304

difference between = and ==

= is used for assignment and == is used to test equality

commands to compare int, float, double, and char variables?

>, <, ==, !=, <=, >=

26) How many times will the following loop iterate? int x = 10; do { System.out.println(x); x--; } while (x > 0);

A) 11 times

22) If x is currently equal to 3, what will the value of x be after the switch statement executes?

A) 12

15) If x is an int where x = 1, what will x be after the following loop terminates? while (x < 100) x *= 2;

A) 128

A listener is an object that

waits for some action from the user

A listener is an object that implements any type of interface is used to accept any form of input is an inner class to a class that has abstract methods waits for some action from the user uses the InputStreamReader class

waits for some action from the user

During program development, software requirements specify

what the task is that the program must perform

During program development, software requirements specify ________.

what the task is that the program must perform

If a break occurs within the innermost loop of a nested loop that is three levels deep

when the break is encountered just the innermost loop is "broken"

when would you use a for loop?

when you know how many times the loop should be executed

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

Of the following if statements, which one correctly executes three instructions if the condition is true?

{ if (x < 0) a = b * 2; y = x; z = a - y; }

Formal parameters are those that appear in the method call and actual parameters are those that appear in the method header.

ANS: F The question has the two definitions reversed. Formal parameters are those that appear in the method header, actual parameters are the parameters in the method call (those being passed to the method).

Java methods can only return primitive types.

ANS: F Java methods can also return objects such as String.

A GUI control sets up an event but it is the programmer who writes the code for the event handler which executes when an event occurs.

ANS: T

Because an Image cannot directly be added to a container, it must be displayed using an ImageView object.

ANS: T

While multiple objects of the same class can exist, in a given program there can only be one version of each class.

ANS: T A class is an abstraction; that is, it exists as a definition, but not as a physical instance. Physical instances are created when an object is instantiated using new. Therefore, there can be many objects of type String, but only one String class.

Regarding the software failure described at the Denver International Airport in the text, it is critical to factor in errors and inefficiencies that alway occur in a complex system.

ANS: T A good system is designed using a well-built systems analysis and design methodology that helps reduce the maintenance portion of the system's lifecycle.

Accessors and mutators provide mechanisms for controlled access to a well-encapsulated class.

ANS: T Accessors provide read access to variables that otherwise would be inaccessible. Mutators provide write access to otherwise inaccessible variables.

A constructor may contain a return statement so long as no value (or expression) is returned.

ANS: T Constructors may contain non-value-returning return statements. Doing so is discouraged, but it is legal.

An object should be encapsulated in order to guard its data and methods from inappropriate access.

ANS: T Encapsulation is the concept that objects should be protected from accidental (or purposeful) misuse

Defining formal parameters requires including each parameter's type.

ANS: T In order for the compiler to check to see if a method call is correct, the compiler needs to know the types for the parameters being passed. Therefore, all formal parameters (those defined in the method header) must include their type. This is one element that makes Java a strongly typed language.

The interface of a class is based on those data instances and methods that are declared public.

ANS: T The interface is how an outside agent interacts with the object. Interaction is only available through those items declared to be public in the class's definition.

Which of the following are true statements about check boxes?

All the above

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

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

true (The "this" reserved word refers to the currently executing object)

An object uses the "this" reserved word to refer to itself. (true or false)

11) A class may contain methods but not variable declarations.

Answer: False. A class may contain both methods and variable declarations.

15) A class's instance data are the variables declared in the main method.

Answer: False. A class's instance data are declared in the class but not inside any method. Variables declared in a method are local to that method and can only be used in that method. Furthermore, every class need not have a main method.

4) Java methods can return more than one item if they are modified with the reserved word continue, as in public continue int foo( ) { ... }

Answer: False. Explanation: All Java methods return a single item, whether it is a primitive data type an object, or void. The reserved word continue is used to exit the remainder of a loop and test the condition again.

9) Every class definition must include a constructor.

Answer: False. Explanation: Java allows classes to be defined without constructors, however, there is a default constructor that is used in such a case.

1) Java methods can return only primitive types (int, double, boolean, etc).

Answer: False. Explanation: Java methods can also return objects, such as a String.

3) All Java classes must contain a main method which is the first method executed when the Java class is called upon.

Answer: False. Explanation: Only the driver program requires a main method. The driver program is the one that is first executed in any Java program (except for Applets), but it may call upon other classes as needed, and these other classes do not need main methods

2) Formal parameters are those that appear in the method call and actual parameters are those that appear in the method header

Answer: False. Explanation: The question has the two definitions reversed. Formal parameters are those that appear in the method header, actual parameters are the parameters in the method call (those being passed to the method).

22) A method defined without a return statement will cause a compile error.

Answer: False. If a method is declared to return void then it doesn't need a return statement. However, if a method is declared to return a type other than void, then it must have a return statement.

14) A constructor must always return an int

Answer: False. In fact, a constructor cannot return anything. It has no return value, not even void. When a constructor is written, no return value should be listed.

24) Method decomposition is the process of creating overloaded versions of a method that do the same thing, but operate on different data types.

Answer: False. Method decomposition is breaking a complicated method into simpler methods to create a more understandable design

16) The methods in a class should always be made public so that those outside the class can use them

Answer: False. Methods that need to be available for use outside a class should be made public, but methods that will only be used inside the class should be made private.

18) The return statement must be followed a single variable that contains the value to be returned.

Answer: False. The return statement may be following by any expression whose type is the same as the declared return type in the method header. For example, return x*y+6; is a valid return statement. The statement return; is also valid for a method that does not return anything (void).

13) A constructor must have the same name as its class.

Answer: True. A constructor is required to have the same name as the class.

20) The different versions of an overloaded method are differentiated by their signatures

Answer: True. A method's signature include the number, types, and order of its parameters. With overloaded methods, the name is the same, but the the methods must differ in their parameters.

25) An object may be made up of other objects

Answer: True. An aggregate object is an object that has other objects as instance data.

10) While multiple objects of the same class can exist, there is only one version of the class

Answer: True. Explanation: A class is an abstraction, that is, it exists as a definition, but not as a physical instance. Physical instances are created when an object is instantiated using new. Therefore, there can be many objects of type String, but only one String class.

8) Defining formal parameters requires including each parameters type

Answer: True. Explanation: In order for the compiler to check to see if a method call is correct, the compiler needs to know the types for the parameters being passed. Therefore, all formal parameters (those defined in the method header) must include their type. This is one element that makes Java a Strongly Typed language.

6) A method defined in a class can access the class' instance data without needing to pass them as parameters or declare them as local variables.

Answer: True. Explanation: The instance data are globally available to all of the class' methods and therefore the methods do not need to receive them as parameters or declare them locally. If variables of the same name as instance data were declared locally inside a method then the instance data would be "hidden" in that method because the references would be to the local variables.

7) The interface of a class is based on those data instances and methods that are declared public.

Answer: True. Explanation: The interface is how an outside agent interacts with the object. Interaction is only available through those items declared to be public in the class' definition.

5) The following method header definition will result in a syntax error: public void aMethod( );

Answer: True. Explanation: The reason for the syntax error is because it ends with a ";" symbol. It instead needs to be followed by { } with 0 or more instructions inside of the brackets. An abstract method will end with a ";" but this header does not define an abstract method.

21) If a method takes a double as a parameter, you could pass it an int as the actual parameter

Answer: True. Since converting from an int to a double is a widening conversion, it is done automatically, so there would be no error.

12) A constructor is a method that gets called automatically whenever an object is created, for example with the new operator.

Answer: True. The constructor is used to initialize an object and it gets called whenever a new object is created from a particular class.

17) The body of a method may be empty.

Answer: True. The method body may have 0 or more instructions, so it could have 0. An empty method body is simply { } with no statements in between.

19) The number and types of the actual parameters must match the number and types of the formal parameters

Answer: True. The names of the corresponding actual and formal parameters may be different but the number and types of the parameters must match.

23) The println method on System.out is overloaded

Answer: True. The println method includes versions that take a String, int, double, char, and boolean.

1) The idea that program instructions execute in order (linearly) unless otherwise specified through a conditional statement is known as

B) flow of control

The do loop differs from the while loop in that a. the while loop will always execute the body of the loop at least once b. the do loop will always execute the body of the loop at least once c. the do loop will continue to loop while the condition in its while statement is false and the while loop will continue to loop while the condition in its while statement is true d. the while loop will continue to loop while the condition in its while statement is false and the do loop will continue to loop while the condition in its while statement is true e. None of these; there is no difference between the two types of loops

B. Because the do loop does not test the condition until after the body of the loop executes, the body will always execute at least one time, but the while loop tests the condition first, and so if the condition is false the first time, the body does not execute even one time.

Write the statement to instantiate a Box object, blueBox, with a length of 6, height of 2, and width of 4. public class Box { double length; double width; double height; Box(double l, double w, double h) { length = l; width = w; height = h; } double volume() { return length * width * height; } }

Box blueBox = new Box (6,4,2);

Which of the following would rotate an Ellipse named lipse 30 degrees counterclockwise? a. lipse.setRotate(30); b. lipse.setRotate(370); c. lipse.setRotate(-30); d. Ellipse.lipse.setRotate(30); e. Ellipse.lipse.setRotate(-10*3);

C

How many times will the System.out.println("*"); statement execute inside of the following nested for loops? for(j = 0; j < 10; j++) for(k = 10; k > j; k--) System.out.println("*"); a. 50 b. 100 c. 55 d. 10 e. 20

C The first iteration of the outer loop has j = 0, so the inner loop iterates from 10 down to 1, or 10 times. The next iteration of the outer loop has j = 1, so the inner loop iterates from 10 down to 2, or 9 times. This continues until the outer loop has j = 9, in which case the inner loop iterates for k = 10 only, or 1 time. Thus, the System.out.println("*"); statement executes a total of 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 55 times.

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)

C) sqrt(Math)

An example of an aggregation relationship is A) parent and child B) animal and dog C) teacher and computer D) phone and fax machine

C) teacher and computer

25) The do loop differs from the while loop in that

C) the do loop will always execute the body of the loop at least once

12) The break statement does which of the following?

D) transfers control out of the current control structure such as a loop or switch statement

Which of the following would not be considered an algorithm? A). recipe B). a computer program C). Pseudocode D). a shopping list E). travel directions

D). a shopping list

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

"Die d = new Die(10);" results in...

Die d having numFaces = 10 and faceValue = 1

Each switch statement must terminate with a break statement.

F. They often do but if the break statement is not present, the flow of control continues into the next case.

5,000 is a valid numeric constant (T/F)

FALSE

A switch statement must have a default clause. T OR F

FALSE

Arrays of characters are immutable (T/F)

FALSE

If x is the String "Hi There", then x.toUpperCase().toLowerCase(); will return the original version of x.

FALSE

Java methods can return more than one item if they are modified with the reserved word continue, as in public continue int foo( ) { ... } (T/F)

FALSE

The main purpose of testing a Java program is to make sure it doesn't generate run-time exceptions (T/F)

FALSE

The mod operator, %, can only be performed on int values and its result is a double.

FALSE

When a program is running, it can change the contents of ROM. (T/F)

FALSE, ROM is the permanent data

In a general-purpose personal computer, the operating system resides in ROM. (T/F)

FALSE, Resides in hard drive

A variable of type boolean will store either a 0 or a 1.

FALSE; A boolean variable can store only one of two values, but these values are the reserved words true and false.

A class's instance data are the variables declared in the main method. (T/F)

FALSE; A class's instance data are declared in the class but NOT inside any method. Variables declared in a method are local to that method and can only be used in that method. Furthermore, every class need not have a main method.

An accessor method provides access to a value and allows the caller to change that value. (T/F)

FALSE; Read-only

When an int is passed as a parameter, the formal and actual parameters become alises of each other. (T/F)

FALSE; This only happens with objects. When an int is passed, the value of the actual parameter is copied into the formal parameter, and any changes made to the formal parameter do not affect the actual parameter.

Formal parameters are those that appear in the method call and actual parameters are those that appear in the method header. (T/F)

FALSE; opposite

A class may contain methods but not variable declarations.

False

A class's instance data are the variables declared in the main method

False

A conditional operator is virtually the same as a switch statement

False

A constructor must always return an int

False

A variable tupe bolean will store either a 0 or 1.

False

All Java classes must contain a main method which is the first method executed when the Java class is called upon.

False

All objects implement Comparable

False

All objects implement Comparable.

False

An accessor method provides access to a value and allows the caller to change that value

False

Any class can implement an interface but no classes can implement ore than a single interface

False

Any class can implement an interface, but no classes can implement more than a single interface.

False

Any class can implement an interface, but no classes can implement more than a single interface. Select one: True False

False

As in the other members of the C family of languages (C, C++, C#), Java interprets a zero value as false and a non-zero value as true.

False

Assume that boolean done = false, int x = 10, int y = 11, String s = "Help" and String t = "Goodbye". Then the expression ( s.concat(t).length ( ) < y) is true.

False

Assume that boolean done = false, int x = 10, int y = 11, String s = "Help" and String t = "Goodbye". Then the expression (done II s.compareTo (t) < 0) is true.

False

Assume x and y are string variables with x = "Hello" and y = null If the operation is y = "Hello" is performed, then the result of (x == y) is

False

Assume x and y are string variables with x = "Hello" and y = null What is the result of (x == y)

False

Assuming name is a String variable, the test if (name != null && name.length()<10) will cause a NullPointerException if name is null

False

Defining formal parameters requires including each parameters type.

False

Every class definition that is used to create objects must include a constructor

False

If classes C1 and C2 both implement an interface Cint, which has a method whichIsIt, and if C1 c = new C1( ); is performed at one point of the program, then a later instruction c.whichIsIt( ); will invoke the whichIsIt method defined in C1.

False

If first and last are both String variables, then first.equals(last); does the same thing as (first = = last).

False

If string x = null; then x.length(); return the int 0

False

If the in variable answer is 5, then after answer %= 8; is executed, answer will be 3.

False

If x is the String "Hi There'" then x.toUpperCase().toLowerCase(); will return the original version of x.

False

In Java, it is possible to create an infinite loop out of while and do loops but not for loops

False

In Java, it is possible to create an infinite loop out of while loops, but not for loops.

False

In Java, selection statements consist of the if and if-else statements.

False

In Java, selection statements consist only of if and if-else statements.

False

In Java, the symbol "=" and "==" are interchangeable.

False

In Java, the symbol "=" and the symbol "==" are used synonymously (interchangeably)

False

In Java, the symbol "=" and the symbol "==" are used synonymously (interchangeably).

False

In Java, the symbol "=" and the symbol "==" are used synonymously (interchangeably). T OR F

False

In a Java program, dividing by 0 is a syntax error.

False

In an interface, the programmer has the choice of providing a method body or not

False

In order to compare int, float and double variables, you can use <, >, ==, !=, <=, >=, but to compare char and String variables, you must use compareTo( ), equals( ) and equalsIgnoreCase( ).

False

Java is a language whose programs do not require translating into machine language before they are executed.

False

Java methods can return only primitive types (int, double, boolean, etc.)

False

Method decomposition is the process of creating overloaded versions of a method that do the same thing, but operate on different data types

False

Regarding the Software Failure: The operators were warned that, although the Therac-25 had many safety precautions, it might be possible to accidentally overdose a patient.

False

Since double and int is a narrowing conversion, there is no way to convert a double to an int.

False

Software design is the first step in program development.

False

T/F: All Java classes must contain a main method which is the first method executed when the Java class is called upon.

False

The third portion of a for loop, the increment portion, must increment or decedent a variable.

False

When comparing any primitive type of variable, == should always be used to test to see if two values are equal.

False

When reading an unknown amount of input from the user, a for loop would be the best choice.

False

^ is allowed in an identifier

False

false (The statement first.equals(last); compares the two Strings referenced by first and last to see if the Strings store the same character, while (first = = last) determines if first and last reference the same String, that is, are aliases)

If first and last are both String variables, then first.equals(last); does the same thing as (first = = last). (true or false)

If x is an int where x = 0, 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 these - this is an infinite loop

None of these - this is an infinite loop

What does the following code do? Assume list is an arraylist of Integer values, temp is some previously initialized int value, and c is an int initialized to 0. for(j = 0; j<list.size(); j++) if(list.get(j)<temp) c++; A) It finds the smallest value and stores it in temp B) It finds the largest value and stores it in temp C) It counts the number of elements equal to the smallest value in list D) It counts the number of elements in list that are less than temp E) It sorts the values in list to be in ascending order

It counts the number of elements in list that are less than temp

Assume an integer arraylist, candy, stores the number of candy bars sold by a group of children where candy.get(j) is the number of candy bars sold by child j. Which of the following code could be used to compute the total number of bars sold by the children? A) Option 1 for(int j = 0; j<candy.size();j++) sum+=candy.get(j); B) Option 2 for(int j = 0; j<candy.size();j++) candy.get(j) = sum; C) Option 3 for(int j = 0; j<candy.size();j++) sum=candy.get(j); D) Option 4 for(int j = 0; j<candy.size();j++) sum+=get(j); E) Option 5 for(int j = 0; j<candy.size();j++) .get(j) += sum;

Option 1 for(int j = 0; j<candy.size();j++) sum+=candy.get(j);

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) Option 1 if(x>0) x++; else x--; B) Option 2 if(x>0) x++; else if(x<0) x--; C) Option 3 if(x>0) x++; if(x<0) x--; else x = 0; D) Option 4 if(x==0) x = 0; else x++; x--; E) Option 5 x++; x--;

Option 2 if(x>0) x++; else if(x<0) x--;

The Coin class 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. 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) Option 1 c.flip(); if(c.isHeads().equals(guess)) System.out.println("User is correct"): B) Option 2 if(c.flip().equals(guess)) System.out.println("User is correct"): C) Option 3 if(c.isHeads().equals(guess)) System.out.println("User is correct"): D) Option 4 c.flip(); if(c.toString().equals(guess)) System.out.println("User is correct"): E) Option 5 c.flip().toString(); if(c.isHeads().equals(guess)) System.out.println("User is correct"):

Option 4 c.flip(); if(c.toString().equals(guess)) System.out.println("User is correct"):

Use the following class definition public class Student { private String name; private String major; private double gpa; private int hours; ... } A method that might be desired in the student class 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) Option 1 public int updateHours() { return hours; } B) Option 2 public void updateHours() { hours++; } C) Option 3 public updateHours(int moreHours) { hours += moreHours; } D) Option 4 public void updateHours(int moreHours) { hours += moreHours; } E) Option 5 public int updateHours(int moreHours) { return hours + moreHours; }

Option 4 public void updateHours(int moreHours) { hours += moreHours; }

The statement { } is a legal block. T OR F

TRUE A block consists of "{", followed by 0 or more Java statements, followed by "}". So it is acceptable to have no statements between the brackets. Situations where this is necessary occur in Java, particularly when implementing methods of abstract classes, something you will study later. The correct answer is 'True'.

In which phase of program development would you expect the programmer to determine the classes and objects needed?

Software design

In which phase of program development would you expect the programmer(s) to determine the classes and objects needed?

Software design

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

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

Wrapper classes in Java allow you to create objects representing primitive data.

TRUE; Every primitive type has a corresponding wrapper class. For example, the Integer class wraps the int type.

A method defined in a class can access the class' instance data without needing to pass them as parameters or declare them as local variables. (T/F)

TRUE; The instance data is globally available to all of the class' methods

With an enumerated type, the programmer defines the possible values of the type.

TRUE; enum, lists out, or enumerates, all possible values of a variable of that type.

An operating system is considered software. (T/F)

TRUE; operating system is considered the computer's main software

What does an import statement do?

Tells the compiler where to find the library class

A unique aspect of Java that allows code compiled on one machine to be executed on a machine of a different hardware platform is Java's byte code.

True

All information is stored in the computer using binary numbers.

True

An if statement may or may have an else clause, but an else clause must be part of an if statement.

True

An if statement may or may not have an else clause, but an else clause must be part of an if statement.

True

An object may be made up of other objects

True

Any for loop can be written as a while loop.

True

As in the other members of the C family of languages (C, C++, C#), Java interprets a zero value as false and a non-zero value as true.

True

Assume that boolean done = false, int x = 10, int y = 11, String s = "Help" and String t = "Goodbye". Then the expression (!done && x <= y) is true.

True

Assume that the class Bird has a static method fly( ). If b is a Bird, then to invoke fly, you could do Bird.fly( );.

True

Assume x and y are string variables with x = "Hello" and y = null If the operation y = x is performed, then the result of (x == y) is

True

Because an Image cannot directly be added to a container, it must be displayed using an ImageView object.

True

Control in a switch statement jumps to the first matching case.

True

Defining formal parameters requires including each parameters types.

True

For the questions below, assume that boolean done = false, int x = 10, int y = 11, String s = "Help" and String t = "Goodbye". The expression (!done && x <= y) is true.

True

Forgetting a semicolon will cause a syntax error

True

Formal parameters are those that appear in the method call and actual parameters are those that appear in the method header

True

If String a = "ABCD" and String b = "abcd" then a.equals(b); returns false but a.equalsIgnoreCase(b); returns true.

True

If String name = "George W. Bush"; then the instruction name.length(); will return 14.

True

If the Bar class has a static method named foo which takes no parameters, then it may be called the statement: Bar.foo();

True

If you create an ArrayList without specifying the type of element, the ArrayList will store Object references which means you can put any type of object in the list.

True

If you want to use classes from a package other than java.lang, you must import them.

True

In Java, if and if-else are selection statements.

True

Java is a strongly typed language which means every variable has a single type associated with it throughout its existence in the program, and the variable can only store values of the type.

True

ROM, RAM, a hard disk, and a CD all store data in binary format

True

Several variables can reference the same object.

True

T/F: A method defined in a class can access the class' instance data without needing to pass them as parameters or declare them as local variables.

True

T/F: Defining formal parameters requires including each parameters type.

True

T/F: The following method header definition will result in a syntax error: public void aMethod( );

True

T/F: The interface of a class is based on those data instances and methods that are declared public.

True

T/F: While multiple objects of the same class can exist, there is only one version of the class.

True

The = = operator performs differently depending on whether the variables being compared are primitives types or objects.

True

The == operator performs differently depending on whether the variables compared are primitives types or object

True

The body of a method may be empty

True

The different versions of an overloaded method are differentiated by their signatures

True

The expression 'z' < 'a' is true.

True

The following loop is syntactically valid: for(int j = 0; j < 1000; j++) j--;

True

The interface of a class is based on those data instances and methods that are declared public.

True

The number of types of the actual parameters must match the number of types of the formal parameters

True

The println method on System.out is overloaded

True

The statement if (a >= b) a++; else b--; will do the same thing as the statement if (a < b) b--; else a++;.

True

The statement { } is a legal block.

True

The statement: if (a >= b) a++; else b--; will do the same thing as the statement: if (a <b) b--; else a++;.

True

The term "test case" is used to express a set of inputs (or user actions) and the expected outputs to be used in testing out software.

True

Unlike the String class where you must pass a message to an object (instance) of a class, as in x.length(), in order to use the Math class, you pass messages directly to the class name, as in Math.abs().

True

Unlike the String class where you must pass a message to an object (instance) of the class, as in x.length( ), in order to use the Math class, you pass messages directly to the class name, as in Math.abs( ) or Math.sqrt( ).

True

When an object is passed as a parameter, the formal and actual parameters become aliases of each other

True

While multiple objects of the same class can exist, in a given program there can only be one version of each class.

True

While multiple objects of the same class can exist, there is only one version of the class.

True

Wrapper classes in Java allow you to create objects representing primitive data.

True

defining formal parameters requires including each parameters type

True

t is possible to convert any type of loop (while, do, for) into any of the other two Java loops.

True

the statement {} is a legal block

True

The following method header definition will result in a syntax error: public void aMethod()

True, the method needs to be followed by {} containing 0 or more instructions

Assume that boolean done = false, int x = 10, and int y = 11. Then the expression (!done && x <= y) is true

True; Since done is false, !done is true. Since 10 < 11, x <= y is true. Therefore, the entire expression is true.

The following for loop is an infinite loop:: for(int j = 0; j < 1000;) i++;

True; keeps repeating because it never changes j, only i

Use the following class definition public class Student { private String name; private String major; private String gpa; private int hours; private Student(String newName, String newMajor, double newGPA, int newHours { name newName; major = newMajor; gpa = newGPA; hours = newHours; } } 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);

Student s1 = new Student("Jane Doe", "Computer Science", 3.333, 33);

What could be used to instantiate a new Student s1?

Student s1 = new Student("Jane Doe", "Computer Science", 3.333, 33);

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

Student s1 = new Student("Jane Doe", "Computer Science", 3.333, 33);

"Due d = new Die(10, 0);" results in...

Syntax error

It is possible to convert any type of loop (while, do, for) into any other.

T. All loop statements have equivalent expressive power.

The following loop is syntacitcally valid: for(int j = 0; j < 1000; j++) j--;

T. The Java compiler does not care that you are incrementing j in the loop but decrementing j in the loop body. Logically, this loop makes no sense because j will continuously be incremented and decremented so that it never reaches 1000, but there is nothing wrong with the loop syntactically.

Control in a switch statement jumos to the first matching case.

T. The switch expression is evaluated and control jumps to the first matching case, then continues from there.

A chess game can be represented in a Java program by an object? (T/F)

TRUE

A class's constructor can call that class's methods. (T/F)

TRUE

ALL of an interface's methods must be defined in a subclass (T/F)

TRUE

All information is stored in the computer using binary numbers (T/F)

TRUE

An abstract class can have constructors, while an interface cannot. (T/F)

TRUE

An abstract class may have private methods, while all methods in an interface are public. (T/F)

TRUE

An object may be made up of other objects. (T/F)

TRUE

At run time, int values are represented in the computer memory in the binary number system (T/F)

TRUE

Division of an integer value by zero in a Java program will cause a run-time ArithmeticException

TRUE

Hello.class, a Java class file obtained by compiling Hello.java under a Windows operating system can be executed on a Mac computer (T/F)

TRUE

If String a = "ABCD" and String b = "abcd" then a.equals(b); returns false but a.equalsIgnoreCase(b); returns true.

TRUE

If a, b and c are int variables with a = 5, b = 7, c = 12, then the statement int z = (a * b - c) / a; will result in z equal to 4.

TRUE

If the return type of a method is a class, the method returns a reference to an object of that class. (T/F)

TRUE

In Java, every variable has a single type associated with it throughout its existence in the program, and the variable can only store values of that type.

TRUE

In an interface all methods must be abstract. (T/F)

TRUE

The following method header definition will result in a syntax error: public void aMethod( ); (T/F)

TRUE

The size of an int variable in Java is four bytes, the same under any operating system and computer model. (T/F)

TRUE

The statement if (a >= b) a++; else b--; will do the same thing as the statement if (a < b) b--; else a++;. (T/F)

TRUE

When a program is running, it can read files located on the hard disk. (T/F)

TRUE

While multiple objects of the same class can exist, there is only one version of the class. (T/F)

TRUE

b

You use the keyword ____ to achieve inheritance in Java. a. inherit b. extends c. super d. public

If x is currently 0, a = 0 and b = -5, what will x become after the above statement is executed? if (a > 0) ________if (b < 0) ________x = x + 5; ________else ________if (a > 5) _____________x = x + 4; _____________else _____________x = x + 3; else ________x = x + 2; a) 0 b) 2 c) 3 d) 4 e) 5

b) 2

10) If x is currently 0, a = 1 and b = -1, what will x become after the above statement is executed?

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

24) This paint method will draw several bars (sort of like a bar graph). How many bars will be displayed? 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); } a) 4 b) 5 c) 6 d) 10 e) 20

b) 5

24) This paint method will draw several bars (sort of like a bar graph). How many bars will be displayed?

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

2) In which phase of program development would you expect the programmer(s) to determine the classes and objects needed?

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

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) if (x > 0) x++; else if (x < 0) x--;

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?

b) if (x > 0) x++; else if (x < 0) 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 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? a) (s.charAt(0) == s.charAt(s.length( ))) b) (s.charAt(1) == s.charAt(s.length( ))) c) (s.charAt(0) == s.charAt(s.length( ) - 1)) d) (s.charAt(0) == s.charAt(s.length( ) + 1)) e) (s.charAt(0) == s.charAt(last))

c) (s.charAt(0) == s.charAt(s.length( ) - 1))

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?

c) (s.charAt(0) == s.charAt(s.length( ) - 1)) 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.

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

c) 10,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.

If x is currently 0, a = 5 and b = 5, what will x become after the above statement is executed? if (a > 0) ________if (b < 0) ________x = x + 5; ________else ________if (a > 5) _____________x = x + 4; _____________else _____________x = x + 3; else ________x = x + 2; a) 0 b) 2 c) 3 d) 4 e) 5

c) 3

8) If x is currently 0, a = 5 and b = 5, what will x become after the above statement is executed?

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

Assume values is an Integer arraylist that is currently filled with the following values. 9 -- 4 -- 12 -- 2 -- 6 -- 8 -- 18 The statement System.out.printlnt(values.get(7)); will A) output 7 B) output 18 C) output nothing D) cause an ArrayOutOfBoundsException to be thrown E) cause a syntax error

cause an ArrayOutOfBoundsException to be thrown

Inheritance through an extended (derived) class supports which of the following concepts?

code reuse

A constructor must always return an int.

false

A method defined without a return statement will cause a compile error.

false

All Java classes must contain a main method which is the first method executed when the Java class is called upon.

false

Assume x and y are String variables with x = "Hello" and y = null. 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

false

Assume x and y are String variables with x = "Hello" and y = null. 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

false

Every class definition must include a constructor.

false

Formal parameters are those that appear in the method call and actual parameters are those that appear in the method header.

false

If the operation y = "Hello"; is performed, then the result of (x = = y) is true false x and y becoming aliases x being set to the value null a run-time error

false

Java methods can return more than one item if they are modified with the reserved word continue, as in public continue int foo( ) { ... }

false

Java methods can return only primitive types (int, double, boolean, etc)

false

Method decomposition is the process of creating overloaded versions of a method that does the same thing but operate on different data types.

false

The methods in a class should always be made public so that those outside the class can use them

false

The return statement must be followed a single variable that contains the value to be returned

false

In order to implement Comparable in a class, what method(s) must be defined in that class?

compareTo

In order to implement Comparable in a class, what method(s) must be defined in that class? equals compares both lessThan and greaterThan compareTo both compares and equals

compareTo

commands to compare string variables

compareTo(), equals(), equalsIgnoreCase()

A class may contain methods but not variable declarations.

false, can do both

A class's instance data are the variables declared in the main method.

false, declared in class

In order to create a constant, you would use which of the following Java reserved words?

final

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) consequentialiatinism E) flow of control

flow of control

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

foo(0 / 1, 2 * 3);

Consider a method defined with the header: "public void foo(int a, int b)". Which of the following method calls is legal?

foo(0/1, 2*3);

Write a set of code that outputs all of the int values between 1 and 100 with 5 values per line, and each of those 5 values spaced out equally. Use a single for-loop to solve this problem.

for(int j = 1; j <= 100; j++) { System.out.print(j + "\t"); if (j % 5 == 0) System.out.println( ); }

what three loops are interchangeable?

for, do, while

what do mutators and accessors do?

get into encapsulated classes

instance data

globally available to all of the classes' methods and therefore the methods do not need to receive them as parameters or declare them locally

Every Interator

has a hasNext( ) method

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.

if (this.type.equals(a.returnType( )) return 0;

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. if (this.type < a.returnType( )) return -1; if (this.type = = a.returnType( )) return 0; if (this.type.equals(a.returnType( )) return 0; if (a.returnType( ).equals("King")) return -1; if (a.returnType( ).equals("Pawn")) return 1;

if (this.type.equals(a.returnType( )) return 0;

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

if (x < 0) { a = b * 2; y = x; z = a - y; }

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

if (x < 0) { a = b * 2; y = x; z = a - y; }

46) The following code has a syntax error immediately before the word else. What is the error and why does it arise? Fix the code so that this statement is a legal if-else statement. if (x < 0) ; x++; else x--;

if (x < 0) x++; else x--;

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

if (x > 0) x++; else if (x < 0) x--;

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? if (x > 0) x++; else x--; if (x > 0) x++; else if (x < 0) x--; if (x > 0) x++; if (x < 0) x--; else x = 0; if (x == 0) x = 0; else x++; x--; x++; x--;

if (x > 0) x++; else if (x < 0) x--;

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?

if (x > 0) x++; if (x < 0) x--; else x = 0;

Selection statements

if, if-else, switch

what is a conditional operator?

if-else statement

what happens when variables that are declared locally have the same name as instance data?

instance data will be "hidden"

Write a code fragment that reads 10 integer values from the user and prints the highest value entered. You must use an appropriate looping construct.

int count = 0; System.out.println("Enter number " + count); int highest = scan.nextInt(); count ++; while(count <= 10){ System.out.println("Enter number" + count); int input = scan.nextInt(); if (input > hightest){ highest = input } count++; } System.out.println("Highest Int: " + highest);

Write code that inputs a set of int values and computes its average. Ask the user first how many int values will be input. Make sure that your code cannot produce a division by zero error. Assume that Scanner has been imported and the variable scan is declared properly.

int numberOfValues, j, current, sum = 0; System.out.println ("Enter the number of ints you will be inputting"); numberOfValues = scan.nextInt( ); for (j = 0; j < numberOfValues; j++) { System.out.println("Enter your next int value"); current = scan.nextInt( ); sum += current; } if (numberOfValues != 0) double average = sum / numberOfValues; else { System.out.println("Cannot compute the average of 0 values"); }

40) Write some code that inputs a set of int values and computes its average. Ask the user first how many int values will be input. Make sure that your code cannot produce a division by zero error. Assume that cs1.Keyboard has been imported.

int numberOfValues, j, current, sum = 0; System.out.println("Enter the number of ints you will be inputting"); numberOfValues = Keyboard.readInt( ); for (j = 0; j < numberOfValues; j++) { System.out.println("Enter your next int value"); current = Keyboard.readInt( ); sum += current; } if (numberOfValues != 0) double average = sum / numberOfValues; else System.out.println("Cannot compute the average of 0 values");

Write a statement that declares and initializes an array 'sample' of 10 integers?

int[] sample = new int[10];

Abstract methods are used when defining

interface classes

If a method does not have a return statement, then

it must be a void method

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

it must be a void method

If a method does not have a return statement, then...

it must be a void method

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

it prints s out backwards

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

it prints s out backwards

Question about int j = s length

it prints s out backwards

What output is produced by the following code frament? int limit = 100, num1 = 15, num2 = 40; if (limit <= limit) { if (num1 == num2) System.out.println ("lemon"); System.out.println ("lime"); } System.out.println ("grape");

lime grape

A variable whose scope is restricted to the method where it was declared is known as a(n)

local variable

The relationship between a class and an object is best described as...

objects are instances of class

The relationship between a class and an object is best described as

objects are instances of classes

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

objects are instances of classes

The activities of the development cycle are generally thought to

overlap

The idea that an object can exist separate from the executing program that creates it is called

persistence

d

You can use the keyword _______ within a method in a child class to access an overridden method in a parent class. a. sub b. this c. protected d. super

Instance data for a Java class may be

primitive types or object

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

local variable

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?

m2

When executing a program, the processor reads each program instruction from __________

main memory

Write a method called average that accepts two integer parameters and returns their average as a floating point value.

public double average (int num1, int num2) { return (num1 + num2) / 2.0; }

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." Which of the following method headers would properly define the method needed to make this class Comparable? public boolean comparable(Object cp) public int comparable(Object cp) public int compareTo(Object cp) public int compareTo( ) public boolean compareTo(Object cp)

public int compareTo(Object cp)

For the questions below, 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." Which of the following method headers would properly define the method needed to make this class Comparable?

public int compareTo(Object cp)

Write a method called sum100 that returns the sum of the integers from 1 to 100 inclusive. (you must use an appropriate looping construct).

public int sum100() { int sum = 0; for (int count = 1; count <= 100; count++) sum += count; return sum; }

Write a method called sumRange that accepts two integer parameters that represent a range. Issue an error message and return 0 if the second parameter is less than the first. Otherwise, the method should return the sum of the integers in that range (inclusive).

public int sumRange (int start, int end) { int sum = 0; if (end < start) System.out.println ("ERROR: Invalid Range"); else for (int num = start; num <= end; num++) sum += num; return sum; }

Create an interface called Visible that includes two methods: makeVisible and makeInvisible. Both methods should take no parameters and should return a boolean result.

public interface Visible { public void makeVisible(); public void makeInvisible(); }

A method that updates the Student's number of credit hours by receiving a number of credit hours and ad these to the Student's current hours is defined as...

public void updateHours(int moreHours) { hours += moreHours; }

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

public void updateHours(int moreHours) { hours += moreHours; }

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) (s1.length( ) == s2.length( ))

The size of each rectangle (bar) public void paintComponent(Graphics page) { int x,y = 200; page.setColor(Color.blue); for(x = 100;x<200;x+=20) page.fillRect(x,y,10,y-x); } 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

decreases in height while staying the same width

Static methods cannot

reference non-static instance data

Static methods cannot reference instance data reference non-static instance data reference other objects invoke other static methods invoke non-static methods

reference non-static instance data

If s is a String, and s = "no"; is performed, then s

references the memory location where "no" is stored

If s is a String, and s = "no"; is performed, then s stores the String "no" references the memory location where "no" is stored stores the characters 'n', 'o' stores an int value that represents the two characters stores the character 'n' and a reference to the memory location where the next character, 'o' is stored

references the memory location where "no" is stored

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

references the memory location where "no" is stored

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); y.set1(3); z.set2(y.get1()); y=z The statement y.get2(); will A) return 5 B) return 6 C) return 3 D) return 0 E) cause a run-time error

return 5

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; The statement y.get2( ); will

return 5

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; The statement z.get2( ); will

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

return 5

The statement y.get2( ); will return 5 return 6 return 3 return 0 cause a run-time error

return 5

public class Student { ... } A 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);

s1 = getClassRank( );

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

s1.getClassRank( );

A method that will compute and return the student's class rank is defined as...

s1.getClassRank();

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); } The size of each rectangle (bar)

decreases in height while staying the same width

what happens if there is no constructor?

default constructor will be used

JOptionPane is a class that provides GUI

dialog boxes

JOptionPane is a class that provides GUI dialog boxes buttons output fields panels and frames all of the above

dialog boxes

which java class requires a main method?

driver program

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

may be primitive types or objects

An example of passing a message to a String where the message has a String parameter occurs in what?

equals

An example of passing a message to a String where the message has a String parameter occurs in which of the following messages?

equals

Instance data for a Java class _________.

may be primitive types or objects

Instance data for a Java class...

may be primitive types or objects

An example of passing a message to a String where the message has a String parameter occurs in which of the following methods? (length, substring, equals, toUpperCase, or none)

equals

Having multiple class methods of the same name where each method has a different number of or type of parameters is known as

method overloading

Having multiple class methods of the same name where each method has a different number of or type of parameters is known as

method overloading

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

method overloading

Having multiple class methods of the same name where each method has a different number of or type of parameters is known as...

method overloading

Having multiple class methods of the same name where each method has a different number of or type of parameters is knows as _________.

method overloading

The behavior of an object is defined by the object's

methods

The behavior of an object is defined by the object's ____

methods

The behavior of an object is defined by the object's _______.

methods

The behaviour of an object is defined by the object's...

methods

A method that modifies a value is a _________.

mutator method

What reserved words in Java is used to create an instance of a class?

new

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

new

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

new

If you want to set numDots to a random number between 1 and 6, what line of code do you need?

numDots = (int)(6 * Math.random()) + 1;

If "Swapper s = new Swapper(0, "hello", 0);" is followed by "s.toString();", what value is returned from "s.toString()"?

"00"

If the instruction Swapper s = new Swapper(0, "hello", 0); is executed followed by s.toString( ); what value is returned from s.toString( )?

"00"

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); y.set1(3); z.set2(y.get1()); y=z 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

(y = = z) is still true

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; If the instruction z.set2(y.get1( )); is executed, which of the following is true?

(y = = z) is still true

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; If the instructions z.set2(5); and y.set1(10); are performed, which of the following is true?

(y = = z) is still true

If the instruction z.set2(y.get1( )); is executed, which of the following is true? (y = = z) is still true (y.get1( ) = = z.get1( )) but (y.get2( ) != z.get2( )) (y.get1( ) = = z.get1( )) and (y.get2( ) = = z.get2( )) but (y != z) (y.get1( ) = = z.get2( )) and (y.get2( ) = = z.get1( )) but (y != z) the statement causes a run-time error

(y = = z) is still true

If the instructions z.set2(5); and y.set1(10); are performed, which of the following is true? (y = = z) is still true (y.get1( ) = = z.get1( )) but (y.get2( ) != z.get2( )) (y.get1( ) = = z.get1( )) and (y.get2( ) = = z.get2( )) but (y != z) (y.get1( ) = = z.get2( )) and (y.get2( ) = = z.get1( )) but (y != z) this statement causes a run-time error

(y = = z) is still true

34) String s1 is said to overlap String s2 if all of the characters in s1 also appear in s2. Write a set of code that will set the boolean variable overlap to true if s1 overlaps s2 and false otherwise. Assume both s1 and s2 have already been input.

) boolean overlap = true; // assume the two Strings will overlap int j = 0; while (overlap && j < s1.length( )) { boolean found = false; // search in s2 for character at position j in s1 int k = 0; while (!found && k < s2.length( )) // if found, set found to true if (s2.charAt(k) == s1.charAt(j)) found = true; else k++; // otherwise go on to next character in s2 if (!found) overlap = false; // if a full pass is made through s2 and a character not j++; // found then set overlaps to false, otherwise continue }

39) Write a "query-controlled" loop that will continue to input int values from the user, adding each to the int value sum, and then ask if the user has another value to input, until the user says that there are no more values. Assume that cs1.Keyboard has been imported.

) int x, sum = 0; String query; do { System.out.println("Enter an int value to be summed"); x = Keyboard.readInt( ); sum += x; System.out.println("Do you have any more ints to input? (Yes or No) "); query = Keyboard.readString( ); } while (query.equalsIgnoreCase("Yes"))

41) A data verification loop is a loop that asks the user to input a value within a restricted range repeatedly until the user has input a value within the requested range. Write a data verification loop that that inputs an int value x within the range 0 and 100. Assume cs1.Keyboard has been imported.

) int x; do { System.out.println("Enter an int value between 0 and 100"); x = Keyboard.readInt( ); } while (x >= 0 && x <= 100);

37) Show the output that would occur from the following code, including proper spacing. for (j = 0; j < 5; j++) { for (k = 0; k < 5; k++) if (j!=k) System.out.print(' '); else System.out.print('*'); System.out.println( );

) * * * * * The outer loop iterates from 0 to 4, and for each iteration, the inner loop also iterates from 0 to 4. For iteration of the inner loop, if j and k are not the same, a blank is output, otherwise an *. So, if j = 0 and k = 2, then two blanks are output before an *, followed by two more blanks. At the end of each iteration of the inner loop, the cursor is returned to start a new line

For questions 1-4, assume x and y are String variables with x = "Hello" and y = null. *The result of (x = = y) is true false a syntax error a run-time error x being set to the value null

** false

X-- AND X++

- 1 OR + 1

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

-20

If there are 4 objects of type StaticExample, how many different instances of x are there? 0 1 3 4 There is no way to know since any of the objects might share x, but they do not necessarily share x

1

int num = 1, max = 20; while (num < max) { System.out.println (num); num += 4; }

1 5 9 13 17

Assume values is an Integer arraylist that is currently filled with the following values. 9 -- 4 -- 12 -- 2 -- 6 -- 8 -- 18 What is returned by values.get(3) A) 9 B) 12 C) 2 D) 6 E) 3

2

If x is currently 0, a = 0 and b = -5, what will x become after the above statement is executed? if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2;

2

if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2; If x is currently 0, a = 0 and b = -5, what will x become after the above statement is executed?

2

if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2; If x is currently 0, a = 0 and b = -5, what will x become after the above statement is executed?

2

if(a>0) if(b<0) x = x + 5; else if(a>5) x = x + 4; else x = x + 3; else x = x + 2; 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

2

int num = 1, max = 20; while (num < max) { if (num%2 ==0) System.out.println (num); num++; }

2 4 6 8 10 12 14 16 18

If x is currently 0, a = 5 and b = 5, what will x become after the above statement is executed? if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2;

3

if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2; If x is currently 0, a = 5 and b = 5, what will x become after the above statement is executed?

3

if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2; If x is currently 0, a = 5 and b = 5, what will x become after the above statement is executed?

3

A colour 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 these, it is not possible to represent a color image

3 values denoting the shade of red, green and blue in the image

A color image is broken down into individual pixels, each of which is represented by _________.

3 values denoting the shade of red, green, and blue in the image

How many times will the System.out.println(*); statement execute inside of the following nested for-loops? for(j=0; j<10; j++) for(k=10;k>j;k--) System.out.println("*");

55. The first iteration of the outer loop has j = 0, so the inner loop iterates from 10 down to 1, or 10 times. The next iteration of the outer loop has j = 1, so the inner loop iterates from 10 down to 2, or 9 times. This continues until the outer loop has j = 9, in which case the inner loop iterates for k =10 only, or 1 time. Thus, the System.out.println statement executes a total of 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 55 times.

How many passes will Selection Sort run for to sort a 7-element array?

6 passes, even if it's sorted beforehand it'll still go through it

44) The following for-loop is odd in that the loop increment value changes during iterations of the loop. Determine the number of times the loop iterates and the final value of j after the loop terminates. int k = 0; for (j = 0; j < 20; j += k) k++;

6 times with j = 21. Explanation: The first iteration has j = 0, k is then incremented in the loop body to 1 and j is incremented after the loop body executes to be j + k = 0 + 1 = 1. For the second iteration, k is incremented to 2 and j is incremented to j + k = 1 + 2 = 3. For the third iteration, k is incremented to 3 and j is incremented to 3 + 3 = 6. For the fourth iteration, k is incremented to 4 and j is incremented to 6 + 4 = 10. For the fifth iteration, k is incremented to 5 and j is incremented to 10 + 5 = 15. For the sixth iteration, k is incremented to 6 and j is incremented to 15 + 6 = 21. Now, since (j < 20) is no longer true, the loop terminates.

The following for-loop is odd in that the loop increment value changes during iterations of the loop. Determine the number of times the loop iterates and the final value of j after the loop terminates. int k = 0; for (j = 0; j < 20; j += k) { k++; }

6 times with j = 21. The first iteration has j = 0, k is then incremented in the loop body to 1 and j is incremented after the loop body executes to be j + k = 0 + 1 = 1. For the second iteration, k is incremented to 2 and j is incremented to j + k = 1 + 2 = 3. For the third iteration, k is incremented to 3 and j is incremented to 3 + 3 = 6. For the fourth iteration, k is incremented to 4 and j is incremented to 6 + 4 = 10. For the fifth iteration, k is incremented to 5 and j is incremented to 10 + 5 = 15. For the sixth iteration, k is incremented to 6 and j is incremented to 15 + 6 = 21. Now, since (j < 20) is no longer true, the loop terminates.

6 bits can be used to represent _______ distinct items or values.

64

If x is an int where x = 0, what will x be after the following loop terminates? while (x < 100) x *= 2;

64

Assume values is an Integer arraylist that is currently filled with the following values. 9 -- 4 -- 12 -- 2 -- 6 -- 8 -- 18 What is the value of values.size() A) 0 B) 5 C) 6 D) 7 E) 18

7

Which of the following statements are true about Java loops? a. All three loop types are functionally equivalent. b. while loops and do loops are essentially the same, but while loops always execute at least once. c. If you know the number of times that a loop is to be performed, the best type of loop to use is a while loop. d. Loops may be replaced by an appropriate combination of if-else and switch statements. e. None of these

A In Java, as in most languages, the looping statements are all essentially equivalent (and almost interchangeable). Their principal difference(s) relate to when the controlling condition is evaluated and whether there is syntax for incrementation/update.

If a break occurs within the innermost loop of a nested loop that is three levels deep, a. just the innermost loop will be "broken" b. all loops are "broken" and execution continues from after the end of the loop c. all but the outermost loops are "broken" and execution continues from the next iteration of the outermost loop d. a syntax error is generated unless there are break or continue statements at each loop level e. None of these are true

A The innermost loop is broken, and execution continues from just after the end of that loop.

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 first character e. It yields a run-time error because there is no character at s.charAt(j-1) for j = 0

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

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

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

true (if not, a syntax error will occur)

A class that implements an interface must implement every method in the interface. (true or false)

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

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

What is a mutator method?

A method that modifies a value

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

A method that modifies a value.

The instruction Die d = new Die(10, 0); results in

A syntax error

Java field

A variable inside a class

Which of the following statements are true about Java loops? Select one: a. all three loop statements are functionally equivalent Correct b. while loops and do loops are essentially the same; but while loops always execute at least once c. if you know the number of times that a loop is to be performed, the best loop statement to use is a while loop d. loops may be replaced by an appropriate combination of if-else and switch statements e. none of these

A) ALL LOOPS ARE EQUIVALENT

Every Interator

A) has a hasNext( ) method

20) A continue statement switch (x) { case 3 : x += 1; case 4 : x += 2; case 5 : x += 3; case 6 : x++; case 7 : x += 2; case 8 : x--; case 9 : x++ }

A) may be used within any Java loop statement

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) most problems are too complex to be solved as a single, large activity

How can the following statement be rewritten using a conditional operator? if(x <0) y = x; else y = 0; a. y = (x < 0) ? x : 0; b. x = (x < 0) ? y : 0; c. (x < 0) ? y = x : y = 0; d. y = (x < 0); e. y = if(x < 0) x : 0;

A. The conditional operator of Java tests a condition, (x < 0) in this case, and if true, returns the value after the ? (x in this case) and if false, returns the value after the : (0) in this case). The original if statement is to assign y to x if (x < 0) and 0 otherwise. This will be accomplished by assigning y to be x or 0 based on (x < 0), as shown in A. In B, x is assigned the value of y or 0 which is backward. In C, the conditional operator is syntactically invalid. In D, y would be set to either true or false depending on (x < 0), and the statement in E is syntactically invalid.

7. What is the value of z after the following statements are executed? double x = 2.5, y = 4.0; int z = (int) x + y; a. 6 c. 6.5 b. 6.0 d. 7

ANS: A

What happens if you declare a class constructor to have a void return type? a. You will most likely receive a syntax error. b. The program will compile with a warning but you'll get a run-time error. c. There is nothing wrong with declaring a constructor with a void return type. d. The class's default constructor will be used instead of the one you're declaring. e. None of these

ANS: A It is a syntax violation to declare a constructor with any type, even void, so you'll receive a syntax error.

A class's 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

ANS: A 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.

The expressions that are passed to a method in an invocation are called a. actual parameters b. formal parameters c. formal arguments d. formals e. Any of these

ANS: A The formals (formal parameters, formal arguments) are those given in a method's header, where it is declared. The actual parameters (actuals, actual arguments) are the expressions that actually are transmitted to a method in an invocation.

1. What is the output of the following code? String username = "Tom"; int userAge = 22; System.out.print(userAge); System.out.print("\nis "); System.out.print(username); System.out.println("'s age."); a. 22 is Tom's age. b. 22 is Tom's age. c. 22 \nis Tom's age. d. 22 \n is Tom's age.

ANS: B

12. What is the value of i after the following statement is executed? int i = '2' + '3'; a. 5 b. 101 c. will not compile d. none of these

ANS: B

13. What is the value of i after the following statement is executed? int j = 2 + 'a'; a. 2 b. 99 c. will not compile d. none of these

ANS: B

14. What will be the output of the following code? char ch = 'a'; System.out.print(++ch); a. a b. b c. will not compile d. none of these

ANS: B

15. What is the value of the cityState string after this statement is executed? String cityState = "Milwaukee"; cityState = cityState + "," + "Wisconsin"; a. Milwaukee","Wisconsin c. MilwaukeeWisconsin b. Milwaukee,Wisconsin d. Wisconsin

ANS: B

2. What is the output of the following code? String username = "Tom"; int userAge = 22; System.out.println(userAge + "\nis " + username + "'s age."); a. 22 is Tom's age. b. 22 is Tom's age. c. 22 \nis Tom's age. d. 22 \n is Tom's age.

ANS: B

3. What is the result of the following expression? 10 + 5 * 3 - 20 a. -5 b. 5 c. 25 d. -50

ANS: B

5. What is the result of the following expression? 25.0 / 4 + 4 * 10 % 3 a. 19 b. 7.25 c. 3 d. 7

ANS: B

6. What is the output of the following code? int a=5, b=2, c=10; c = c + a * b - 5; a. -45 c. 25 b. 15 d. None of the above

ANS: B

Consider a Rational class designed to represent rational numbers as a pair of ints, along with methods reduce (to reduce the rational to simplest form), gcd (to find the greatest common divisor of two ints), as well as methods for addition, subtraction, multiplication, and division. Why should the reduce and gcd methods be declared to be private? a. because they will never be used b. because they will only be called from methods inside Rational c. because they will only be called from the constructor of Rational d. because they do not use any of the Rational instance data e. This is incorrect; they should be declared as public

ANS: B 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.

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 cannot 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, float, or String method

ANS: B 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).

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

ANS: 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.

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

ANS: B 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.

Given the method defined here, which of the following method calls is legal? public void foo(int a, int b) a. foo(0, 0.1); b. foo(0/1, 2*3); c. foo(0); d. foo(); e. foo(1+2, 3*0.1);

ANS: B The only legal method call is one that passes twoint 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.

Visibility modifiers include a. public, private b. public, private, protected c. public, private, protected, final d. public, protected, final, static e. public, private, protected, static

ANS: B public, private, protected control the visibility of variables and methods. final controls whether a variable, method, or class can be further changed or overridden; it does not control visibility. static controls whether a variable or method is associated with instances of a class or the class itself.

10. What will be displayed as a result of executing the following code? int x = 5, y = 20; x += 32; y /= 4; System.out.println("x = " + x + ", y = " + y); a. x = 32, y = 4 b. x = 9, y = 52 c. x = 37, y = 5 d. x = 160, y = 80

ANS: C

8. Which statement is equivalent to the following statement? total = total + tax; a. total = tax++; c. total += tax; b. total = ++tax; d. total =+ tax;

ANS: C

9. Which statement is equivalent to the following statement? tax = tax + 1; a. tax++; c. Both a and b b. tax += 1; d. None of these

ANS: C

Which of the following is not a kind of object that is used to create a graphical user interface in JavaFX? a. control b. event c. image d. event handler e. All of these are objects used to create a GUI in JavaFX

ANS: C An image is not a kind of object used to create a GUI even though it is an object. It can only be displayed with an ImageView JavaFX node.

To define a class that will represent a car, which of the following definition is most appropriate? a. private class car b. public class car c. public class Car d. public class CAR. e. private class Car

ANS: C 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.

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

ANS: C 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.

An example of passing a message to a String where the message has a String parameter would occur in which of the following messages? a. length b. substring c. equals d. toUpperCase e. None of these; it is not possible to pass a String as a parameter to a String

ANS: C 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.

11. What will be the value of z as a result of executing the following code? int x = 5, y = 28; float z; z = (y / x); a. 5.60 b. 5.6 c. 3.0 d. 5.0

ANS: D

16. What is the value of the cityState string after these statements are executed? String cityState = "Milwaukee"; cityState = cityState + ","; cityState = "Wisconsin"; a. Milwaukee, Wisconsin c. MilwaukeeWisconsin b. Milwaukee,Wisconsin d. Wisconsin

ANS: D

4. What is the result of the following expression? 25 / 4 + 4 * 10 % 3 a. 19 b. 7.25 c. 3 d. 7

ANS: D

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 these preserve encapsulation

ANS: D 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 used to control inheritance and has nothing to do with encapsulation.

The behavior of an object is defined by the object's a. instance data b. constructor c. visibility modifiers d. methods e. All of these

ANS: D 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 combined dictate the behavior. The visibility modifiers do impact the object's performance indirectly.

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 (can use either) d. import e. new

ANS: E

The software failure at the Denver International Airport's baggage handling system is a good example of a. how a large system can be obsolete by the time it is developed b. how designers sometimes have too much faith in the technology they are using c. how failures are often a result of multiple variables caused by a system as a whole in actual operation d. how the use of a centralized computer is unrealistic in today's distributed processing e. All of these

ANS: E All of these are good examples of why software fails.

Given the method defined here, which of the following method calls is legal? public void doublefoo(double x) a. doublefoo(0); b. doublefoo(0.555); c. doublefoo(0.1 + 0.2); d. foo(0.1, 0.2); e. all except D are legal

ANS: E 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.

Instance data for a Java class a. are limited to primitive types 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

ANS: E 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.

In a UML diagram for a class a. classes are represented as rectangles b. there may be a section containing the name of the class c. there may be a section containing the attributes of the class d. there may be a section containing the methods of the class e. All of these

ANS: E Those four attributes correctly describe a UML representation of a class.

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

ANS: E 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.

Java methods can return more than one item if they are modified with the reserved word continue, as in public continue int foo() {...}

ANS: F All Java methods return a single item, whether it is a primitive data type an object, or void. The reserved word continue is used to exit the remainder of a loop and test the condition again.

Every class definition must include a constructor.

ANS: F Java allows classes to be defined without constructors. However, there is a default constructor that is used in such a case.

All Java classes must contain a main method which is the first method executed when the Java class is called on.

ANS: F Only the driver program requires a main method. The driver program is the one that is first executed in any Java program (except for Applets), but it may call upon other classes as needed, and these other classes do not need main methods.

The following method header definition will result in a syntax error: public void aMethod();

ANS: T The reason for the syntax error is because it ends with a ; symbol. It instead needs to be followed by {} with 0 or more instructions inside of the brackets. An abstract method will end with a ; but this header does not define an abstract method.

A method defined in a class can access the class's instance data without needing to pass them as parameters or declare them as local variables.

ANS: T The instance data are globally available to all of the class's methods and therefore the methods do not need to receive them as parameters or declare them locally. If variables of the same name as instance data were declared locally inside a method then the instance data would be "hidden" in that method because the references would be to the local variables.

16) We compare sorting algorithms by examining a) the number of instructions executed by the sorting algorithm b) the number of instructions in the algorithm itself (its length) c) the types of loops used in the sorting algorithm d) the amount of memory space required by the algorithm e) whether the resulting array is completely sorted or only partially sorted

Answer: a. Explanation: Different sorting algorithms require a different number of instructions when executing. The Selection Sort for instance usually requires more instructions than the Insertion Sort. So, we compare sorting algorithms by the number of instructions that each takes to execute to sort the array. We might count the maximum number of instructions that a sorting algorithm will execute in the worst case, or the minimum number in the best case, or count on average the number of instructions executed. If two sorting algorithms require roughly the same number of instructions to sort an array, then we might also examine the amount of memory space required.

15) Which of the following interfaces would be used to implement a class that represents a group (or collection) of objects? a) Iterator b) Speaker c) Comparable d) MouseListener e) KeyListener

Answer: a. Explanation: Iterator is an abstract class allowing the user to extend a given class that implements Iterator by using the features defined there. These features include being able to store a group of objects and iterate (step) through them.

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

Answer: a. Explanation: Since y=z; was peformed previously, y and z are aliases meaning that they refer to the same object. The statement z.set2(5); causes a change to the object's second value while y.set1(10); causes a change to the object's first value but neither change the fact that y and z are aliases.

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

Answer: a. Explanation: Since y=z; was performed previously, y and z are aliases, so that a change to one results in a change to the other. The statement z.set2(y.get1( )); is essentially the same as z.set2(z.get1( )); or y.set2(y.get1( )); and in any case, it sets the second value to equal the first for the object which is referenced by both y and z.

7) The "off-by-one" error associated with arrays arises because a) the first array index is 0 and programmers may start at index 1, or may use a loop that goes one index too far b) the last array index is at length + 1 and loops may only iterate to length, missing one c) the last array element ends at length - 1 and loops may go one too far d) programmers write a loop that goes from 0 to length - 1 whereas the array actually goes from 1 to length e) none of the above, the "off-by-one" error has nothing to do with arrays

Answer: a. Explanation: The array is initialized as = new type[x] where x is the size of the array. However, the array has legal indices of 0 to x - 1 and so, programmers are often off-by-one because programmers will write code to try to access indices 1 to x.

For questions 13 - 15, assume an int array, candy, stores the number of candy bars sold by a group of children where candy[j] is the number of candy bars sold by child j. Assume there are 12 children in all. 14) Which of the following code could be used to compute the total number of bars sold by the children? a) for(int j=0; j<12; j++) sum+= candy[j]; b) for(int j=0; j<12; j++) candy[j] = sum; c) for(int j=0; j<12; j++) sum = candy[j]; d) for(int j=0; j<12; j++) sum += [j]; e) for(int j=0; j<12; j++) [j] += sum;

Answer: a. Explanation: The code in a iterates through all 12 elements of candy, adding each value to sum. The answer in b sets all 12 elements of candy equal to sum, the answer in c sets sum to be each element of candy, resulting in sum = candy[11] and d and e have syntactically invalid code.

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.

5) A class' constructor usually defines a) how an object is initialized b) how an object is interfaced c) thenumberofinstancedataintheclass d) thenumberofmethodsintheclass 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.

23) In order to have some code throw an exception, you would use which of the following reserved words? a) throw b) throws c) try d) Throwable e) goto

Answer: a. Explanation: The reserved word throw is used to throw an exception when the exception is detected, as in: if (score < 0) throw new IllegalTestScoreException("Input score " + score + " is negative");

2) To define a class that will represent a car, which of the following definitions is most appropriate? a) privateclasscar b) publicclasscar c) publicclassCar d) publicclassCAR e) privateclassCar

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.

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

Answer: a. Explanation: The statement y = z; causes y and z to be aliases where y.get2( ); returns the same value as z.get2( );. Since z.set2(y.get1( )); was performed previously, z and y's second value is 5.

For questions 5-8, consider a class that stores 2 int values. These values can be assigned int values with the messages set1(x) and set2(x) where x is an int, and these values can be accessed through get1( ) and get2( ). Assume that y and z are two objects of this class. The following instructions are executed: y.set1(5); y.set2(6); z.set1(3); z.set2(y.get1( )); y = z; 5) The statement z.get2( ); will a) return 5 b) return 6 c) return 3 d) return 0 e) cause a run-time error

Answer: a. Explanation: The statement y.get1( ) returns the value 5, and therefore the statement z.set2(y.get1( )) sets the second value of z to be 5, so that z.get2( ) returns 5.

4) If the operation y = x; is performed, then the result of (x = = y) is a) true b) false c) x being set to the value null while y retains the value "Hello" d) y being set to the value null while x retains the value "Hello" e) x being set to y, which it is already since y = x; was already performed

Answer: a. Explanation: When y = x; was performed, the two variables are now aliases, that is, they reference the same thing in memory. So, (x = = y) is now true.

24) JOptionPane is a class that provides GUI a) dialog boxes b) buttons c) output fields d) panels and frames e) all of the above

Answer: a. Explanation: the JOptionPane class contains three formats of dialog boxes, an input dialog box that prompts the user and inputs String text, a message dialog box that outputs a message, and a confirm box that prompts the user and accepts a Yes or No answer.

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.

11) Static methods cannot a) reference instance data b) reference non-static instance data c) reference other objects d) invoke other static methods e) invoke non-static methods

Answer: b. Explanation: A static method is a method that is part of the class itself, not an instantiated object, and therefore the static method is shared among all instantiated objects of the class. Since the static method is shared, it cannot access non-static instance data because all non-static instance data are specific to instantiated objects. A static method can access static instance data because, like the method, the instance data is shared among all objects of the class. A static method can also access parameters passed to it.

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.

9) In the Rational class, defined in chapter 4, the methods reduce and gcd are declared to be private. Why? a) Becausetheywillneverbeused 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.

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

24) To initialize a String array names to store the three Strings "Huey", "Duey" and "Louie", you would do a) String names = {"Huey", "Duey", "Louie"}; b) String[ ] names = {"Huey", "Duey", "Louie"}; c) String[ ] names = new String{"Huey", "Duey", "Louie"}; d) String names[3] = {"Huey", "Duey", "Louie"}; e) String names; names[0] = "Huey"; names[1] = "Duey"; names[2] = "Louie";

Answer: b. Explanation: An array does not have to be instantiated with the reserved word new if it is instantiated with the list of values it is to store. So, names = {"Huey", "Duey", "Louie"}; will create a String array of 3 elements with the three values already initialized. Of the other answers, a does not specify that names is a String array, c should not have the reserved word new, d should not have [3] after names and omits [ ] after String, and e does not instantiate the array as String[3], and thus , all four of these other answers are syntactically invalid.

18) Consider the array declaration and instantiation: int[ ] arr = new int[5]; Which of the following is true about arr? a) It stores 5 elements with legal indices between 1 and 5 b) It stores 5 elements with legal indices between 0 and 4 c) It stores 4 elements with legal indices between 1 and 4 d) It stores 6 elements with legal indices between 0 and 5 e) It stores 5 elements with legal indices between 0 and 5

Answer: b. Explanation: Arrays are instantiated with an int value representing their size, or the number of elements that they can store. So, arr can store 5 elements. Further, all arrays start at index 0 and go to index size - 1, so arr has legal indices of 0 through 4.

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

Answer: b. Explanation: Because x is a static instance data, it is shared among all objects of the StaticExample class, and therefore, since at least one object exists, there is exactly one instance of x.

6) In Java, arrays are a) primitive data types b) objects c) interfaces d) primitive data types if the type stored in the array is a primitive data type and objects if the type stored in the array is an object e) Strings

Answer: b. Explanation: In Java, arrays are implemented as objects. The variable is a reference variable to the block of memory that stores the entire array. However, arrays are accessed using the notation name[index] rather than by message passing.

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

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

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

20) Assume that you are defining a class and you want to implement an ActionListener. You state addActionListener(this); in your class' constructor. What does this mean? a) The class must import another class which implements ActionListener b) The class must define the method actionPerformed c) The class must define the method ActionListener d) The class must define an inner class called ActionListener e) The class must define the method actionPerformed in an inner class named ActionListener

Answer: b. Explanation: Since the ActionListener being implemented is being added in this class (that is what the "this" refers to in addActionListener), then this class must define the abstract methods of the ActionListener class. There is only one abstract method, actionPerformed. The answer in a is not true, if the class that implements ActionListener were being imported (assume that the variable al is an instance of this imported class), then the proper statement would be addActionListener(al);.

19) If s is a String, and s = "no"; is performed, then s a) stores the String "no" b) references the memory location where "no" is stored c) stores the characters 'n', 'o' d) stores an int value that represents the two characters e) stores the character 'n' and a reference to the memory location where the next character, 'o' is stored

Answer: b. Explanation: Strings are objects and all objects in Java are referenced by the variable declared to be an object. That is, the variable represents the memory location where the object is stored. So, s does not directly store "no" or 'n', 'o', but instead stores a memory location where "no" is stored.

20) If int[ ] x = new int[15]; and the statement x[-1] = 0; is executed, then which of the following Exceptions is thrown? a) IndexOutOfBoundsException b) ArrayIndexOutOfBoundsException c) NegativeArraySizeException d) NullPointException e) ArithmeticException

Answer: b. Explanation: The array index is out of bounds as the array index can only be between 0 and 14. -1 is an illegal index because it is out of bounds. One might expect the answer to be c, but the NegativeArraySizeException is thrown if an array is being declared with a negative number of elements as in int[ ] x = new int[-5];

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

Answer: b. Explanation: The call stack trace provides the names of the methods as stored on the run-time stack. The method names are removed from the stack in the opposite order that they were placed, that is, the earliest method was placed there first, the next method second, and so forth so that the most recently invoked method is the last item on the stack, so it is the first one removed. The stack trace then displays all active methods in the opposite order that they were called (most recent first).

5) Which of the following is a legal way to declare and instantiate an array of 10 Strings? a) String s = new String(10); b) String[10] s = new String; c) String[ ] s = new String[10]; d) String s = new String[10]; e) String[ ] s = new String; 9 4 12 2 6 8 18

Answer: c. Explanation: Declaring an array is done by type[ ] variable. Instantiating the array is done by variable = new type[dimension] where dimension is the size of the array.

22) The following code accomplishes which of the tasks written below? Assume list is an int array that stores positive int values only. foo = 0; for(j=0; j<list.length; j++) if (list[j] > foo) foo = list[j]; a) it stores the smallest value in list (the minimum) in foo b) it stores the largest value in list (the maximum) in foo c) it stores every value in list, one at a time, in foo, until the loop terminates d) it counts the number of elements in list that are greater than foo e) it counts the number of elements in list that are less than foo

Answer: b. Explanation: The condition in the if statement tests to see if the current element of list is greater than foo. If so, it replaces foo. The end result is that every element in list is tested and foo stores the largest element up to that point, so eventually, foo will be the largest value in the array list.

21) Assume that BankAccount is a predefined class and that the declaration BankAccount[ ] firstEmpireBank; has already been performed. Then the following instruction reserves memory space for firstEmpireBank = new BankAccount[1000]; a) a reference variable to the memory that stores all 1000 BankAccount entries b) 1000 reference variables, each of which point to a single BankAccount entry c) a single BankAccount entry d) 1000 BankAccount entries e) 1000 reference variables and 1000 BankAccount entries

Answer: b. Explanation: The declaration BankAccount[ ] firstEmpireBank; reserves memory space for firstEmpireBank, which itself is a reference variable that points to the BankAccount[ ] object. The statement firstEmpireBank = new BankAccount[1000]; instantiates the BankAccount[ ] object to be 1000 BankAccount objects. This means that firstEmpireBank[0] and firstEmpireBank[1] and firstEmpireBank[999] are all now legal references, each of which is a reference variable since each references a BankAccount object. So, the statement reserves memory space for 1000 reference variables. Note that none of the 1000 BankAccount objects are yet instantiated, so no memory has been set aside yet for any of the actual BankAccount objects.

For questions 1-4, assume values is an int array that is currently filled to capacity, with the following values: 3) Which of the following loops would adequately add 1 to each element stored in values? a) for(j=1;j<values.length;j++) values[j]++; b) for(j=0;j<values.length;j++) values[j]++; c) for(j=0;j<=values.length;j++) values[j]++; d) for(j=0;j<values.length-1;j++) values[j]++; e) for(j=1;j<values.length-1;j++) values[j]++;

Answer: b. Explanation: The first array element is values[0], so the for-loop must start at 0, not 1. There are values.length elements in the array where the last element is at values.length-1, so the for loop must stop before reaching values.length. This is the case in b. In d, the for loop stops 1 before values.length since "<" is being used to test the condition instead of <=.

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.

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

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.

3) If the operation y = "Hello"; is performed, then the result of (x = = y) is a) true b) false c) x and y becoming aliases d) x being set to the value null e) a run-time error

Answer: b. Explanation: While x and y now store the same value, they are not the same String, that is, x and y reference different objects in memory, so the result of the condition (x = = y) is false.

For questions 1-4, assume x and y are String variables with x = "Hello" and y = null. 1) The result of (x = = y) is a) true b) false c) a syntax error d) a run-time error e) x being set to the value null

Answer: b. Explanation: x is a String instantiated to the value "Hello" and y is a String that has not yet been instantiated, so they are not the same String. (x = = y) is a condition, testing to see if x and y are the same String (that is, x and y reference the same item in memory), which they don't, so the result is false.

10) Which of the following lists of numbers would accurately show the array after the second pass of the Selection Sort algorithm? a) 9, 4, 12, 2, 6, 8, 18 b) 2, 4, 9, 6, 12, 8, 18 c) 2, 4, 12, 9, 6, 8, 18 d) 2, 4, 6, 8, 9, 12, 18 e) 2, 4, 12, 6, 8, 9, 18

Answer: c. Explanation: After one pass, the array would be 2, 4, 12, 9, 6, 8, 18. The second pass would look to swap the item in array index 1 (4) with the smallest value after 2 (4). So, 4 would swap with 4 and the array would stay the same as it was after the first pass.

17) Both the Insertion Sort and the Selection Sort algorithms have efficiencies on the order of ____ where n is the number of values in the array being sorted. a) n b) n * log n c) n2 d) n3 e) Insertion sort has an efficiency of n and Selection Sort has an efficiency of n2

Answer: c. Explanation: Both sorting algorithms use two nested loops which both execute approximately n times apiece, giving a complexity of n * n or n2 for both.

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.

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;

Answer: c. Explanation: If the type of this piece and of a are the same type, then they are considered equal and the method should return 0 to indicate this. Note that this does not cover the case where this piece is a "Knight" and a is a "Bishop", so additional code would be required for the "equal to" case. The answer in b is not correct because it compares two Strings to see if they are the same String, not the same value. The logic in d and e are incorrect because neither of these takes into account what the current piece is, only what the parameter's type is. In d, if a is a "King", it will be greater than this piece if this piece is not a "King", but will be equal if this piece is a "King" and similarly in e, it does not consider if this piece is a "Pawn" or not. Finally, a would give a syntax error because two Strings cannot be compared using the "<" operator.

25) To declare a two-dimensional int array called threeD, which of the following would you use? a) int[2] twoD; b) int[ , ] twoD; c) int[ ][ ] twoD; d) int [ [ ] ] twoD; e) int[ ] twoD[2];

Answer: c. Explanation: In Java, you can only declare one-dimensional arrays. To create a two-dimensional array, you must declare it as an array of arrays. The proper notation is to declare the type of array using multiple [ ] marks in succession, as in int[ ][ ] for a two-dimensional array.

For questions 1-4, assume values is an int array that is currently filled to capacity, with the following values: 1) What is returned by values[3]? a) 9 b) 12 c) 2 d) 6 e) 3

Answer: c. Explanation: Java array indices start at 0, so values[3] is really the fourth array element, which is 2.

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) Which of the following lists of numbers would accurately show the array after the first pass through the Selection Sort algorithm? a) 9, 4, 12, 2, 6, 8, 18 b) 4, 9, 12, 2, 6, 8, 18 c) 2, 4, 12, 9, 6, 8, 18 d) 2, 4, 6, 8, 9, 12, 18 e) 2, 4, 9, 12, 6, 8, 18

Answer: c. Explanation: On each successive pass of Selection Sort, the smallest of the unsorted values is found and swapped with the current array index (where the current index starts at 0 and goes until the second to last position in the array). On the first pass, the smallest element, 2, is swapped with index 0, so 2 and 9 swap places. 9 4 12 2 6 8 18

10) Which of the following methods is a static method? The class in which the method is defined is given in parentheses following the method name. a) equals (String) b) toUpperCase (String) c) sqrt (Math) d) format (DecimalFormat) e) paint (Applet)

Answer: c. Explanation: The Math class defines all of its methods to be static. Invoking Math methods is done by using Math rather than a variable of type Math. The other methods above are not static

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

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

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.

19) If an int array is passed as a parameter to a method, which of the following would adequately define the parameter list for the method header? a) (int[ ]) b) (int a[ ]) c) (int[ ] a) d) (int a) e) (a[ ])

Answer: c. Explanation: The parameter is defined much as the variable is originally declared, as type parameter name. Here, the type is int[ ] and the parameter is a.

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

For questions 17-18, consider a class called ChessPiece. This class has two instance data, String type and int player. The variable type will store "King", "Queen", "Bishop", etc and the int player will store 0 or 1 depending on whose piece it is. We wish to implement Comparable for the ChessPiece class. Assume that, the current ChessPiece is compared to a ChessPiece passed as a parameter. Pieces are ordered as follows: "Pawn" is a lesser piece to a "Knight" and a "Bishop", "Knight" and "Bishop" are equivalent for this example, both are lesser pieces to a "Rook" which is a lesser piece to a "Queen" which is a lesser piece to a "King." 17) Which of the following method headers would properly define the method needed to make this class Comparable? a) public boolean comparable(Object cp) b) public int comparable(Object cp) c) public int compareTo(Object cp) d) public int compareTo( ) e) public boolean compareTo(Object cp)

Answer: c. Explanation: To implement Comparable, you must implement a method called compareTo which returns an int. Further, since this class will compare this ChessPiece to another, we would except the other ChessPiece to be passed in as a parameter (although compareTo is defined to accept an Object, not a ChessPiece).

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.

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

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

21) A Java program can handle an exception in several different ways. Which of the following is not a way that a Java program could handle an exception? a) ignore the exception b) handle the exception where it arose using try and catch statements c) propagate the exception to another method where it can be handled d) throw the exception to a pre-defined Exception class to be handled e) all of the above are ways that a Java program could handle an exception

Answer: d. Explanation: A thrown exception is either caught by the current code if the code is contained inside a try statement and the appropriate catch statement is implemented, or else it is propagated to the method that invoked the method that caused the exception and caught there in an appropriate catch statement, or else it continues to be propagated through the methods in the opposite order that those methods were invoked. This process stops however once the main method is reached. If not caught there, the exception causes termination of the program (this would be answer a, the exception was ignored). However, an exception is not thrown to an Exception class.

23) If x is a char, and values is an int array, then values[x] a) causes a syntax error b) causes an Exception to be thrown c) casts x as an int based on x's position in the alphabet (for instance, if x is 'a' then it uses 0 and if x is 'z' then it uses 25) d) casts x as an int based on x's Unicode value (for instance, if x is 'a' then it uses 97 and if x is 'z' then it uses 122) e) casts x as an int based on the digit that is stored in x (for instance, if x is '3' it uses 3) but throws an exception if x does not store a digit

Answer: d. Explanation: An array index must be an int value, so normally values[x] would cause a syntax error if x were not an int, but the Java compiler will automatically cast x to be an int if it can be cast. Characters are cast as ints by converting the char value to its equivalent Unicode value. So, if x is 'a', it is cast as the int 97 instead and so values[x] accesses values[97].

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.

3) In order to preserve encapsulation of an object, we would do all of the following except for which one? a) Maketheinstancedataprivate b) Definethemethodsintheclasstoaccessandmanipulatetheinstancedata c) Makethemethodsoftheclasspublic d) Maketheclassfinal 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.

11) Which of the following lists of numbers would accurately show the array after the fourth pass of the Selection Sort algorithm? a) 9, 4, 12, 2, 6, 8, 18 b) 2, 4, 6, 9, 12, 8, 18 c) 2, 4, 6, 8, 9, 12, 18 d) 2, 4, 6, 9, 8, 12, 18 e) 2, 4, 6, 8, 12, 9, 18

Answer: e. Explanation: The array would be sorted as follows: First pass: 2, 4, 12, 9, 6, 8, 18. Second pass: 2, 4, 12, 9, 6, 8, 18. Third pass: 2, 4, 6, 9, 12, 8, 18. Fourth pass: 2, 4, 6, 8, 12, 9, 18.

For questions 12 - 13, use the following class definition: public class StaticExample { private static int x; public StaticExample (int y) { x = y; } public int incr( ) { x++; return x; } } 12) What is the value of z after the third statement executes below? StaticExample a = new StaticExample(5); StaticExample b = new StaticExample(12); int z = a.incr( ); a) 5 b) 6 c) 12 d) 13 e) none, the code is syntactically invalid because a and b are attempting to share an instance data

Answer: d. Explanation: Since instance data x is shared between a and b, it is first initialized to 5, it is then changed to 12 when b is instantiated, and then it is incremented to 13 when a.incr( ) is performed. So, incr returns the value 13.

16) In order to implement Comparable in a class, what method(s) must be defined in that class? a) equals b) compares c) both lessThan and greaterThan d) compareTo e) both compares and equals

Answer: d. Explanation: The Comparable class requires the definition of a compareTo method that will compare two objects and determine if one is equal to the other, or if one is less than or greater than the other and respond with a negative int, 0 or a positive int. Since compareTo responds with 0 if the two objects are equal, there is no need to also define an equals method.

12) How many passes will it take in all for Selection Sort to sort this array? a) 2 b) 4 c) 5 d) 6 e) 7

Answer: d. Explanation: The Selection Sort uses two for-loops where the outer loop iterates through each array index except for the last one. So it makes a total of n - 1 passes where n is the number of items in the array. Since this array has 7 elements, the outer loop iterates 6 times, or requires 6 passes. You might notice that in fact this array is sorted after only 5 passes, but the Selection Sort algorithm will still make 6 passes (even if the array had been sorted after only 1 pass, it would still make 6 passes!)

For questions 1-4, assume values is an int array that is currently filled to capacity, with the following values: 4) The statement System.out.println(values[7]); will a) output 7 b) output 18 c) output nothing d) cause an ArrayOutOfBoundsException to be thrown e) cause a syntax error

Answer: d. Explanation: The array has 7 values, but these are indexed values[0] to values[6]. Since values[7] is beyond the bounds of the array, values[7] causes an ArrayOutOfBoundsException to be thrown.

For questions 1-4, assume values is an int array that is currently filled to capacity, with the following values: 2) What is the value of values.length? a) 0 b) 5 c) 6 d) 7 e) 18

Answer: d. Explanation: The length operator for an array returns the size of the array. The above picture shows that that values stores 7 elements and since it is full, the size of values is 7.

25) A listener is an object that a) implements any type of interface b) is used to accept any form of input c) is an inner class to a class that has abstract methods d) waits for some action from the user e) uses the InputStreamReader class

Answer: d. Explanation: The listener "listens" for a user action such as a mouse motion, a key entry or an activation of a GUI object (like a button) and then responds appropriately. Listeners allow us to write programs that interact with the user whenever the user performs an operation as opposed to merely seeking input from the user at pre-specified times.

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.

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.

14) An object that refers to part of itself within its own methods can use which of the following reserved words to denote this relationship? a) inner b) i c) private d) this e) static

Answer: d. Explanation: The reserved word this is used so that an object can refer to itself. For instance, if an object has an instance data x, then this.x refers to the object's value x. While this is not necessary, it can be useful if a local variable or parameter is named the same as an instance data. The reserved word this is also used to refer to the class as a whole, for instance, if the class is going to implement an interface class rather than import an implementation of an interface class.

8) What does the following code do? Assume list is an array of int values, temp is some previously initialized int value, and c is an int initialized to 0. for(j=0;j<list.length.j++) if(list[j] < temp) c++; a) It finds the smallest value and stores it in temp b) It finds the largest value and stores it in temp c) It counts the number of elements equal to the smallest value in list d) It counts the number of elements in list that are less than temp e) It sorts the values in list to be in ascending order

Answer: d. Explanation: The statement if(list[j]<temp) c++; compares each element in list to temp and adds one to c only if the element is less than temp, so it counts the number of elements in list less than temp, storing this result in c. An int array stores the following values. Use the array to answer questions 9 - 12.

. 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

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

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

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

For questions 13 - 15, assume an int array, candy, stores the number of candy bars sold by a group of children where candy[j] is the number of candy bars sold by child j. Assume there are 12 children in all. 13) What does the following code do? int value1 = Keyboard.readInt( ); int value2 = Keyboard.readInt( ); bars[value1] += value2; a) adds 1 to the number of bars sold by child value1 and child value2 b) adds 1 to the number of bars sold by child value1 c) adds value1 to the number of bars sold by child value2 d) adds value2 to the number of bars sold by child value1 e) inputs a new value for the number of bars sold by both child value1 and child value2

Answer: d. Explanation: bars[value1] is the number of bars sold by child value1, and += value2 adds to this value the amount input for value2.

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.

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 6-8. 7) 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("Useriscorrect"); c) if(c.isHeads().equals(guess))System.out.println("Useriscorrect"); 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.

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.

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

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.

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

For questions 13 - 15, assume an int array, candy, stores the number of candy bars sold by a group of children where candy[j] is the number of candy bars sold by child j. Assume there are 12 children in all. 15) What does the following method do? public int question15( ) { int value1 = 0; int value2 = 0; for(int j=0; j<12; j++) if(candy[j] > value1) { value1 = candy[j]; value2 = j; } return value2; } a) It returns the total number of candy bars sold b) It returns the total number of children who sold 0 candy bars c) It returns the total number of children who sold more than 0 candy bars d) It returns the number of candy bars sold by the child who sold the most candy bars e) It returns the index of the child who sold the most candy bars

Answer: e. Explanation: The loop iterates through all 12 array elements. If a particular value of candy is found to be larger than value1, then this new value is remembered in value1 along with the index of where it was found in value2. As the loop continues, if a new candy value is found to be greater than the current value1, then it is remembered instead, so the loop finds the maximum number of candy bars sold in value1 and the child's index who sold the most in value2. Since value2 is returned, the code returns the index of the child who sold the most.

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.

2) The result of x.length( ) + y.length( ) is a) 0 b) 5 c) 6 d) 10 e) a thrown exception

Answer: e. Explanation: The statement y.length( ) results in a thrown NullPointException because it is not possible to pass a message to an object that is not currently instantiated (equal to null).

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.

9) Consider the following swap method. If String x = "Hello" and String y = "Goodbye", then swap(x, y); results in which of the following? public void swap(String a, String b) { String temp; temp = a; a = b; b = temp; } a) x is now "Goodbye" and y is now "Hello" b) x is now "Goodbye" and y is still "Goodbye", but (x != y) c) x is still "Hello" and y is now "Hello", but (x != y) d) x and y are now aliases e) x and y remain unchanged

Answer: e. Explanation: When x and y are passed to swap, a and x become aliases and b and y become aliases. The statement temp = a sets temp to be an alias of a and x. The statement a = b sets a to be an alias of b and y, but does not alter x or temp. Finally, b = temp sets b to be an alias of temp and y, but does not alter y. Therefore, x and y remain the same.

false (Classes can implement any number of interfaces, 0, 1, or more)

Any class can implement an interface, but no classes can implement more than a single interface (true or false)

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 these would work

Any of these would work

false (Only variable that are object references can be null, which indicate that they do not refer to any object. Variables of primitive types such as int and double cannot be assigned null)

Any variable can take on the value null to indicate that it has no value (true or false)

false (Only variable that are object references can be null, which indicate that they do not refer to any object. Variables of primitive types such as int and double cannot be assigned null)

Any variable can take on the value null to indicate that it has no value. (true or false)

True (Static methods are invoked through the class and not an object of the class. This is because the static method is shared among all instances. So, Bird.fly( ); will invoke fly. It should be noted that fly can also be invoked through b, so b.fly( ); will also work)

Assume that the class Bird has a static method fly( ). If b is a Bird, then to invoke fly, you could do Bird.fly( );.

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

Assume x and y are String variables with x = "Hello" and y = null. 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

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

Assume x and y are String variables with x = "Hello" and y = null. 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

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

Assume x and y are String variables with x = "Hello" and y = null. The result of x.length( ) + y.length( ) is a) 0 b) 5 c) 6 d) 10 e) a thrown exception

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

Assume x and y are String variables with x = "Hello" and y = null.ssume x and y are String variables with x = "Hello" and y = null. 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

false (If name is null, the && will short-circuit and name.length() will not be evaluated. (Otherwise, name.length() would cause an exception if name was null.)

Assuming name is a String variable, the test if (name != null && name.length() < 10) will cause a NullPointerException if name is null. (true or false)

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

B) if (x > 0) x++; else if (x < 0) x--;

if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2; 5) If x is currently 0, a = 0 and b = -5, what will x become after the above statement is executed?

B) 2

7) Consider the following code that will assign a letter grade of 'A', 'B', 'C', 'D', or 'F' depending on a student's test score

B) This code will work correctly only if grade < 70

You might choose to use a switch statement instead of nested if-else statements if a. the variable being tested might equal one of several hundred integer values b. the variable being tested might equal one of a few integer values c. there are two or more integer variables being tested, each one of which could be one of several hundred values d. there are two or more integer variables being tested, each one of which could be one of a few values e. None of these; you would never choose a switch statement instead of nested if-else statements under any circumstances.

B. The switch statement can only be used if there is a single variable being tested and it is an integer type (an int or a char in Java). Further, because you have to enumerate each possible value being tested, the switch statement only makes sense if the number of values being tested is a small number.

What does the break statement do? a. It ends a program. b. It transfers control out of the current control structure such as a loop or switch statement. c. It ends the current line of output, returning the cursor. d. It denotes the end of a switch statement. e. It indicates the end of a line when using System.out.print.

B. This is the exit statement that allows the programmer to exit a control structure from inside of that control structure.

If classes C1 and C2 both implement an interface Cint, which has a method whichIsIt, and if C1 c = new C1( ); is performed at one point of the program, then a later instruction c.whichIsIt( ); will invoke the whichIsIt method defined in C1.

Because C1 and C2 implement the same interface, they both implement whichIsIt. The variable c is known as a polymorphic variable, meaning that it can change from being an C1 to a C2. So, the message c.whichIsIt( ); may invoke C1's whichIsIt or C2's whichIsIt. There is no way to tell until run-time. The correct answer is 'True'.

In the Rational class, defined in chapter 4, the methods reduce and gcd are declared to be private. Why?

Because they will only be called from methods inside of Rational

Use the following partial class definitions public class Rational { private int num; private int den; private void reduce() { ... } private int ged(int n) { ... } } Why are the methods reduce and ged declared to be private 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

Because they will only be called from methods inside of Rational

29) What will the following code do? Assume s is a String, x is an int initialized to 10, page is a Graphics object, and this is part of a paint method for an applet. boolean isVowel = false; String vowels = "aeiou"; for (int j = 0; j < s.length( ); j++) { for (int k = 0; k < 5; k++) if (s.charAt(j) == vowels.charAt(k)) isVowel = true; if (isVowel) page.drawString(""+s.charAt(j), 10, 15*x++); else page.drawString(""+s.charAt(j), 110, 15*x++); isVowel = false; }

C) The String s is printed down the applet in two columns with vowels appearing in the left column and all other characters in the right column

17) How many times will the following loop iterate? int x = 10; while (x > 0) { System.out.println(x); x--; }

C) 10 times

A continue statement a. may be used within a while or a do-while loop but not a for loop b. is identical to a break statement within Java loops c. may be used within any Java loop statement d. may be used within a for loop but not within a while or a do-while loop e. None of these

C. Altough use of continue statements should be avoided if possible, they may be used within any of Java's three types of loops.

In the following example, x is an int: switch (x) { case 3 : x += 1; case 4 : x += 2; case 5 : x += 3; case 6 : x++; case 7 : x += 2; case 8 : x--; case 9 : x++ } If x is equal to 5, what will the value of x be after the switch statement executes? a. 8 b. 6 c. 11 d. 5 e. 10

C. Since there are no break statements, the flow falls through any cases following the one that is true. The first case to be true is 5 since x is 5 prior to the switch statement. This changes x to 8, then to 9, then to 11, then to 10, and then finally back to 11

How many times will the following nested loop structure execute the innermost statement (x++;)? for(int j = 0; j < 100; j++) for(int k = 100; k > 0; k--) x++; a. 100 b. 200 c. 10,000 d. 20,100 e. 1,000,000

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.

All objects implement Comparable. Select one: True False

Comparable is an interface, and the class must define the compareTo method and explicitly state that it implements Comparable to be considered an implementation of Comparable. Most classes do not implement Comparable. The correct answer is 'False'.

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

Conditions 2, 3 and 4 are all true, Condition 1 is not

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

Conditions 2, 3 and 4 are all true, Condition 1 is not

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

Conditions 2, 3 and 4 are all true, Condition 1 is not

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

Conditions 2, 3 and 4 are all true, Condition 1 is not

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

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

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

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

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

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

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

Once we have implemented a 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 need revising at a later date because of new specifications d. the solution may need revising at a later date because of new programming features e. all of the above

E

if (a > 0) if (b < 0) x = x + 5; else if (a > 5) x = x + 4; else x = x + 3; else x = x + 2; 6) If x is currently 0, a = 1 and b = -1, what will x become after the above statement is executed?

E) 5

In the following example, x is an int: switch (x) { case 3 : x += 1; case 4 : x += 2; case 5 : x += 3; case 6 : x++; case 7 : x += 2; case 8 : x--; case 9 : x++ } If x is equal to 3, what will the value of x be after the switch statement executes? a. 5 b. 6 c. 11 d. 10 e. 12

E Since there are no break statements, the flow falls through any cases following the one that is true. The first case to be true is 3 since x is 3 prior to the switch statement. This changes x to 4, then to 6, then to 9, then to 10, then to 12, then to 11, and then finally back to 12.

If x is an int where x = 0, what will x be after the following loop terminates? while (x < 100) x *= 2; A) 2 B) 128 C) 64 D) 100 E) none of the above, this is an infinite loop

E) none of the above, this is an infinite loop

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

E) 10

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

E) 10,000

In order to preserve encapsulation of an object, we would NOT do what?

Make the class final

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

E) Conditions 2, 3 and 4 are all true, Condition 1 is not

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

E) The condition short circuits and the assignment statement is not executed

27) Given that s is a String, what does the following loop do?

E) it prints s out backwards

19) If a switch statement is written that contains no break statements whatsoever

E) none of the above

16) If x is an int where x = 0, what will x be after the following loop terminates? while (x < 100) x *= 2

E) none of the above, this is an infinite loop

If a switch statement contains no break statements at all, a. a syntax error will occur b. each of the case clauses will be executed every time the switch statement is encountered c. this is equivalent to having the switch statement always take the default clause, if one is present d. this is not a syntax error but nothing within the switch statement will ever be executed e. None of these

E. Although writing such a switch statement is unusual, it is entirely legal. The normal rules for the switch statement execution apply. The matching case clause being executed after the switch statement is evaluated and, following that, all subsequent clauses are executed, in order, since there are no break statements to terminate execution.

How many times will the following loop iterate? int x = 10; do { System.out.println(x); x--; } while(x > 0); a. 0 times b. 1 time c. 9 times d. 10 times e. 11 times

E. The variable x starts at 10. Each pass through the loop, x is decremented and the loop finally exits once x is no longer greater than 0, which in this case means once x becomes 0. So the loop body executes for x = 10, x = 9, x = 8, and so forth down to x = 0. This is 11 times.

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;

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.

T/F 12. Any variable can take on teh calue null to indicate that it has no value.

F

T/F 13. Assuming name is a String variable, the test if (name != null && name.length() < 10) will cause a NullPointerExcpetion if name is null

F

T/F 14. The statements String a = "hi"; String b = a + ""; cause a and b to be aliases of each other

F

T/F 16. When an int is passed as a parameter, teh formal and actual parameters become aliases of each other

F

T/F 17. Variables should never be static

F

T/F 19. When a program attempts to divide by 0, a NullPointerExcpetion occurs.

F

T/F 20. Exceptions may only be thrown by the Java runtime system

F

T/F 21. To throw a NullPointerException the programmer could use the following statement: throw NullPointerException;

F

T/F 22. In an interface, the programmer has the choice of providing a method body or not

F

T/F 24. A class representing a car might implement the List interface

F

T/F 3. If first and last are both String variables, then first.equals(last); does the same thing as (first==last)

F

T/F 4. If String x = null; then x.length( ); returns the int 0

F

T/F 6. If an exception is thrown and is not caught anywhere in the program, then the program terminates

F

T/F 8. Any class can implement an interface, but no classes can implement more than a single interface

F

T/F 9. All objects implement Comparable

F

false (Since x is null, the instruction x.length( ); tries to pass the length( ) message to no object. This cannot occur and so a NullPointerException is thrown)

If String x = null; then x.length( ); returns the int 0. (true or false)

true (Exceptions are events of interest or are run-time situations that cannot be handled normally without an exception handler. An exception is caught by an associated exception handler. If the exception is thrown but not handled, then the program must terminate)

If an exception is thrown and is not caught anywhere in the program, then the program terminates. (true or false)

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

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

true (Static methods are called using the class name; no object need be created)

If the Bar class has a static method named foo which takes no parameters, then it may be called with the statement. Bar.foo(); (true or false)

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

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

Difference between importing a class and extending a class

Imported class: You can only use code as intended, can't change it. Extended class: You can modify it

False (The arrow goes from the child to the parent class)

In a UML diagram, an inheritance relationship is indicated with an arrow that points from the base class to the derived class (true or false)

False (All the methods in an interface are abstract, so none of them may have method bodies)

In an interface, the programmer has the choice of providing a method body or not. (true or false)

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

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

In Java, it is possible to create an infinite loop out of while and do loops, but not for-loops.

It is true that while and do loops can be infinite loops, but it is also true that Java for-loops can be infinite loops. This is not true in many other programming languages where for-loops have a set starting and ending point, but Java for-loops are far more flexible than most other language's for-loops. The correct answer is 'False'.

Which of the following interfaces would be used to implement a class that represents a group (or collection) of objects?

Iterator

Which of the following interfaces would be used to implement a class that represents a group (or collection) of objects? Iterator Speaker Comparable MouseListener KeyListener

Iterator

A variable whose scope is restricted to the method where it was declared is known as a _________.

Local variable

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

Make the class final

Volatility is a property of A) RAM B) ROM C) disk D) software E) computer networks

RAM

Volatility is a property of ________.

RAM

The ability to directly obtain a stored item by referencing its address is known as _________.

Random access

Write a code fragment that reads and prints integer values entered by a user until a particular sentinel value (stored in SENTINEL) is entered. Do not print the sentinel value. You need to declare variables, etc.

Scanner scan = new Scanner (System.in); System.out.println ("Enter some integers (" + SENTINEL + " to quit):"); number = scan.nextInt(); while number (!= SENTINEL) { System.out.println (number); number = scan.nextInt(); }

Write a for loop that only takes positive integers

Scanner scan = new Scanner; int num; System.out.println ("Please enter a positive integer"); int num = scan.nextInt(); while (num!= -1000) if (num > 0) { System.out.println ("Good,"); else { System.out.println ("Please enter a positive int."); }

true (when variables reference the same object, they are known as aliases. As an example, consider the following code. In it, x, y and z all reference the same String (they do not just equal the same value, they are all the same String) and so they are all aliases of each other. String x = "hi"; String y = x; String z = y;)

Several variables can reference the same object (true or false)

32) Explain what is meant by short circuiting and provide an example of short circuiting a condition with && and provide an example of short circuiting a condition with | |.

Short circuiting is when a boolean expression does not have to be completely evaluated because the final answer is determined with just a partial evaluation. This can occur in an expression with && if one part of the expression evaluates to false, and in an expression with | | if one part of the expression evaluates to true. Examples (x != 0) && (sum / x > 100) can be short circuited if x != 0 is false, preventing a division by zero error. (a.equals("yes") | | a.equals("no")) can be short circuited if a is equal to "yes" so that the computer does not waste time in testing a.equals("no").

If you want to output the text "hi there", including the quote marks, what line of code do you need?

System.out.println("\"hi there\"");

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.

System.out.println("\"hi there\"");

A loop can be used in a GUI to draw concentric circles.

T

T/F 1. Several variables can reference the same object

T

T/F 10. An object uses the "this" reserved word to refer to itself

T

T/F 11. The add method is used to add components to a JPanel

T

T/F 15. When an object is passed as a parameter, the formal and actual parameters become aliases of each other

T

T/F 18. If the Bar class has a static method named foo which takes no parameters, then it may be called with the statement Bar.foo();

T

T/F 2. The == operator performs differently depending on whether the variables being compared are primitives types or objects

T

T/F 23. A class that implements an interface must implement every method in the interface

T

T/F 25. When designing a class to represent an object, you need to think about the object's state and behavior

T

T/F 5. Assume that teh class Bird has a static method fly( ). If b is a Bird, then to invoke fly, you could do Bird.fly( );

T

T/F 7. To implement the ActionListener interface, you must implement the method actionPerformed

T

true (If two objects are being compared using = =, then the comparison returns true if the two objects are aliases (the same object). But if two primitive data types are being compared, then the comparison returns true if the two variables store the same value)

The = = operator performs differently depending on whether the variables being compared are primitives types or objects. (true or false)

The Die class is defined as follows: class Die { final private int MIN_FACES = 4; private int numFaces = MIN_FACES; private int faceValue = 0; public Die() { numFaces =6; faceValue=2; } { if(faces<MIN_FACES) numFaces = 6; else numFaces = faces; faceValue = 1; } } 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

The Die d having numFaces = 10 and faceValue = 1

public Die( ) public Die(int faces) { { numFaces = 6; if(faces < MIN_FACES) numFaces = 6; faceValue = 1; else numFaces = faces; } faceValue = 1; } *The instruction Die d = new Die(10); results in*

The Die d having numFaces = 10 and faceValue = 1

Unlike the String class where you must pass a message to an object (instance) of the class, as in x.length( ), in order to use the Math class, you pass messages directly to the class name, as in Math.abs( ) or Math.sqrt( ).

The Math class uses methods known as static methods (or class methods) which are invoked by passing a message directly to the class name itself rather than to an object of the class. The correct answer is 'True'.

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? The class must import another class which implements ActionListener The class must define the method actionPerformed The class must define the method ActionListener The class must define an inner class called ActionListener The class must define the method actionPerformed in an inner class named ActionListener

The class must define the method actionPerformed

Assume that you are defining a class and you want to implement an ActionListener. You state addActionListener( new MyListener() ); 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 MyListener D) The class must define an inner class called ActionListener E) The class must define the method actionPerformed in an inner class named MyListener

The class must define the method actionPerformed in an inner class named MyListener

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; -The condition short circuits and the assignment statement is not executed -The condition short circuits and the assignment statement is executed without problem -The condition does not short circuit causing a division by zero error -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 -The condition will not compile because it uses improper syntax

The condition short circuits and the assignment statement is not executed

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

The condition short circuits and the assignment statement is not executed

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;

The condition short circuits and the assignment statement is not executed

42) Describe a situation where you should use a do loop and a situation where you should use a while loop

The do loop is used if you want to execute the loop body at least one time. This is useful for data verification (asking the user for a value, and only if the user has entered an improper value does your code repeat and try again). A while loop does not necessarily execute if the loop condition is not initially true. This might be useful if you want to control entrance to a loop such as only trying to sum up a list of values if the user actually has values to sum up.

33) The following code has a syntax error immediately before the word else. What is the error and why does it arise? Fix the code so that this statement is a legal if-else statement. if (x < 0) ; x++; else x--;

The error is "else without if" and it arises because of the ";" after the condition but before x++. The Java compiler determines that the if clause is in fact ; (no statement) and that x++; is a statement that follows the if statement. Therefore, since x++; is not part of the if statement, the "else" is felt to be an else without an if, and that is why the error has arise. The statement should be if (x < 0) x++; else x--;

The following code has a syntax error immediately before the word else. What is the error and why does it arise? Fix the code so that this statement is a legal if-else statement. if (x < 0) ; x++; else x--;

The error is "else without if" and it arises because of the ";" after the condition but before x++. The Java compiler determines that the if clause is in fact ; (no statement) and that x++; is a statement that follows the if statement. Therefore, since x++; is not part of the if statement, the "else" is felt to be an else without an if, and that is why the error has arise. The statement should be if (x < 0) x++; else x--;

Which of the following criticisms is valid about the Swapper class?

The instance data z is visible outside of Swapper

What happens when a return statement inside a for loop is executed?

The program immediately quits the current method.

false (The string concatenation operator (+) creates a new String and assigns it to b, so a and b are not aliases, they simply contain the same characters. (a + "" is adding the empty string to a, so b gets assigned "hi".)

The statements String a = "hi"; String b = a + ""; cause a and b to be aliases of each other. (true or false)

Control in a switch statement jumps to the first matching case.

The switch expression is evaluated and control jumps to the first matching case, then continues from there. The correct answer is 'True'.

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

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

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

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

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

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

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

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

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

This code will work correctly only if grade < 70

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

This code will work correctly only if grade < 70

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

This code will work correctly only if grade < 70

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

This code will work correctly only if grade < 70

When comparing any primitive type of variable, == should always be used to test to see if two values are equal. T OR F

This is true of int, short, byte, long, char and boolean, but not of double or float variables. If two double variables, x and y, are being tested, (x == y) is true only if they are exactly equal to the last decimal point. It is common instead to compare these two values but allow for a small difference in value. For instance, if THETA = 0.000001, we might test x and y by (x - y <= THETA) instead of (x == y) to get a better idea of if they are close enough to be considered equal. The correct answer is 'False'.

A GUI control sets up an event, but it is the programmer who writes the code for the event handler, which executes when an event occurs.

True

A class that implements an interface must implement every method in the interface

True

A constructor is a method that gets called automatically whenever an object is created, for example with the new operator

True

A constructor must have the same name as its class

True

A method defined in a class can access the class' instance data without needing to pass them as parameters or declare them as local variables.

True

A method defined in a class can access the class's instance data without needing to pass them as parameters or declare them as local variables

True

36) Given the following tax table information, write Java code to assign the double taxRate appropriately given the double pay. Select the selection statement (if, if-else, switch) that makes the most sense. If pay is more than 100,000, tax rate is 40% If pay is more than 60,000 and less than or equal to 100,000, tax rate is 30% If pay is more than 30,000 and less than or equal to 60,000, tax rate is 20% If pay is more than 15,000 and less than or equal to 30,000, tax rate is 10% If pay is more than 5,000 and less than or equal to 15,000, tax rate is 5% If pay is less than or equal to 5,000, tax rate is 0%

Use a nested if-else structure as it requires the least amount of code. A switch statement is not possible because pay is a double and the switch statement can only be used for integral types. if (pay > 100000) taxRate = 0.40; else if (pay > 60000) taxRate = 0.30; else if (pay > 30000) taxRate = 0.20; else if (pay > 15000) taxRate = 0.10; else if (pay > 5000) taxRate = 0.05; else taxRate = 0.0;

Given the following tax table information, write Java code to assign the double taxRate appropriately given the double pay. If pay is more than 100,000, tax rate is 40% If pay is more than 60,000 and less than or equal to 100,000, tax rate is 30% If pay is more than 30,000 and less than or equal to 60,000, tax rate is 20% If pay is more than 15,000 and less than or equal to 30,000, tax rate is 10% If pay is more than 5,000 and less than or equal to 15,000, tax rate is 5% If pay is less than or equal to 5,000, tax rate is 0%

Use a nested if-else structure as it requires the least amount of code. A switch statement is not possible because pay is a double and the switch statement can only be used for integral types. if (pay > 100000) taxRate = 0.40; else if (pay > 60000) taxRate = 0.30; else if (pay > 30000) taxRate = 0.20; else if (pay > 15000) taxRate = 0.10; else if (pay > 5000) taxRate = 0.05; else taxRate = 0.0;

b

Usually, the subclass constructor only needs to initialize the ____ that are specific to the subclass. a. objects b. variables c. methods d. constructors

false (An ArithmeticException occurs)

When a program attempts to divide by 0, a NullPointerException occurs. (true or false)

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

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

false (That only happens with objects. When an int is passed, the value of the actual parameter is copied into the formal parameter, and any changes made to the formal parameter do not affect the actual parameter)

When an int is passed as a parameter, the formal and actual parameters become alises of each other (true or false)

true (Since a variable that is an object stores a reference to the object, the actual and formal parameters refer to the same object and thus are aliases)

When an object is passed as a parameter, the formal and actual parameters become aliases of each other (true or false)

true (Since a variable that is an object stores a reference to the object, the actual and formal parameters refer to the same object and thus are aliases)

When an object is passed as a parameter, the formal and actual parameters become aliases of each other. (true or false)

true (Both state (represented by instance variables) and behavior (represented by methods) should be considered when designing a class)

When designing a class to represent an object, you need to think about the object's state and behavior. (true or false)

a

When you create a class and do not provide a(n) ____, Java automatically supplies you with a default one. a. constructor b. argument c. header d. name

b

When you create a class by making it inherit from another class, the new class automatically contains the data fields and _____ of the original class. a. fonts b. methods c. class names d. arrays

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

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)

a

Which of the following statements will create a class named Red that is based on the class Color? a. public class Red extends Color b. public Red class extends Color c. public Color class expands Red d. public extend Red class Color

c

Which statement correctly declares a sedan object of the Car class? a. sedan Car = new sedan(); b. sedan Car = new sedan(); c. Car sedan = new Car(); d. new sedan() = Student;

a

____ is a mechanism that enables one class to acquire all the behaviors and attributes of another class. a. Inheritance b. Polymorphism c. Encapsulation d. Override

A truth table shows, for the various true or false values of boolean variables, what the result of a boolean condition is. Fill in the following truth table. Assume that a, b and c are boolean variables. a b c ! (a && b) | | ! (a && c) false false false false false true false true false false true true true false false true false true true true false true true true

a b c ! (a && b) | | ! (a && c) false false false true false false true true false true false true false true true true true false false true true false true true true true false true true true true false

The result of x.length( ) + y.length( ) is 0 5 6 10 a thrown exception

a thrown exception

A truth table shows, for the various true or false values of boolean variables, what the result of a boolean condition is. Fill in the following truth table. Assume that a, b and c are boolean variables. a b c a && (!b | | c) false false false false false true false true false false true true true false false true false true true true false true true true

a b c a && (!b | | c) false false false false false false true false false true false false false true true false true false false true true false true true true true false false true true true true

Which of the following would not be considered an algorithm? a recipe a computer program pseudocode a shopping list travel directions

a shopping list

Which of the following would not be considered an algorithm? A) a recipe B) a computer program C) assembly instructions D) a shopping list E) travel idirections

a shopping list

Forgetting a semicolon will cause 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 syntax error

The Die class is defined as follows: class Die { final private int MIN_FACES = 4; private int numFaces = MIN_FACES; private int faceValue = 0; public Die() { numFaces =6; faceValue=2; } { if(faces<MIN_FACES) numFaces = 6; else numFaces = faces; faceValue = 1; } } 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

a syntax error

Assume x and y are String variables with x = "Hello" and y = null. The result of x.length( ) + y.length( ) is A) 0 B) 5 C) 6 D) 10 E) a thrown exception

a thrown exception

Assume x and y are string variables with x = "Hello" and y = null The result f x.length() + y.length is

a thrown exception

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) The condition short circuits and the assignment statement is not executed

12) Assume that count is 0, total is 20 and max is 1. The following statement will do which of the following?

a) The condition short circuits and the assignment statement is not executed. 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 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.

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

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) it prints s out backwards

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

17. What do each of the following expressions evaluate to given the declaration: int a = 4, b = 3, n = 4; String ans = "Y"; a. 1 <= 1 b. 1 < 1 c. false == (1 < 1) d. true == (1 < 1) e. (a+b) < 2*a f. (n > 2) && (n < 6) g. (n > 2) || (n == 6) h. !(n < 6) (False) i. (ans = = "Y") || (ans = = "y") j. (ans = = "Y") && (ans = = "y") k. (n = = 2) && (n= =7) || (ans = = "Y") l. (n = = 2) && ((n= =7) || (ans = ="Y"))

a. 1 <= 1 (True) b. 1 < 1 (False) c. false == (1 < 1) (True) d. true == (1 < 1) (False) e. (a+b) < 2*a (True) f. (n > 2) && (n < 6) (True) g. (n > 2) || (n == 6) (True) h. !(n < 6) (False) i. (ans = = "Y") || (ans = = "y") (True) j. (ans = = "Y") && (ans = = "y") (False) k. (n = = 2) && (n= =7) || (ans = = "Y") (True) l. (n = = 2) && ((n= =7) || (ans = ="Y")) (False)

Assume an integer arraylist, candy, stores the number of candy bars sold by a group of children where candy.get(j) is the number of candy bars sold by child j. What does the following code do? int value1 = scan.nextInt(); int value2 = scan.nextInt(); candy.set(value1, candy.get(value1) += value2); A) adds 1 to the number of bars sold by child value1 and child value2 B) adds 1 to the number of bars sold by child value1 C) adds value1 to the number of bars sold by child value2 D) adds value2 to the number of bars sold by child value1 E) inputs a new value for the number of bars sold by both child value1 and child value2

adds value2 to the number of bars sold by child value1

*Considering the (incomplete) code below, x is probably while (x.hasNext()) { ... x.next() ... ... }

an iterator

int num = 87, max = 25; if (num > max * 2) System.out.println ("apple"); System.out.println ("orange"); System.out.println ("pear");

apple orange pear

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;

b) statement2 will only execute if condition1 is false and condition2 is false 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.

1) During program development, software requirements specify

b) what the task is that the program must perform 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).

Static methods cannot Select one: 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. reference non-static instance data

The do loop differs from the while loop in that Select one: a. the while loop will always execute the body of the loop at least once b. the do loop will always execute the body of the loop at least once Correct c. the do loop will continue to loop while condition in the while statement is false and the while loop will continue to loop while the condition in the while statement is true d. the while loop will continue to loop while condition in the while statement is false and the do loop will continue to loop while the condition in the while statement is true e. none of these, there is absolutely no difference between the two types of loops

b. the do loop will always execute the body of the loop at least once Correct

You might choose to use a switch statement instead of nested if-else statements if Select one: a. the variable being tested might equal one of several hundred int values b. the variable being tested might equal one of only a few int values c. there are two or more int variables being tested, each of which could be one of several hundred values d. there are two or more int variables being tested, each of which could be one of only a few values e. none of these, you would never choose to use a switch statement in place of nested if-else statements under any circumstance Incorrect

b. the variable being tested might equal one of only a few int values

During program development, software requirements specify Select one: 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 these

b. what the task is that the program must perform

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?

c) Software implementation 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.

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

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

c) statement2 will only execute if condition1 is true and condition2 is false

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)10,000

The goal of testing is to Select one: a. ensure that the software has no errors b. find syntax errors c. find logical and run-time errors d. evaluate how well the software meets the original requirements e. give out-of-work programmers something to do

c. find logical and run-time errors

For the questions below, 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." 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. Select one: 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. if (this.type.equals(a.returnType( )) return 0;

For the questions below, 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." Which of the following method headers would properly define the method needed to make this class Comparable? Select one: 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. public int compareTo(Object cp)

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. Select one: a. equals (String) b. toUpperCase (String) c. sqrt (Math) d. format (DecimalFormat) e. paint (Applet)

c. sqrt (Math)

An example of an aggregation relationship is Select one: a. parent and child b. animal and dog c. teacher and computer d. phone and fax machine e. all of these

c. teacher and computer

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

c.flip( ); if(c.toString( ).equals(guess)) System.out.println("User is correct");

20) Given two String variables, s1 and s2, to determine if they are the same length, which of the following conditions would you use?

d) (s1.length( ) == s2.length( )) 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.

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

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

19) How many times will the following loop iterate? int x = 10; while (x > 0) { System.out.println(x); x--; }

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

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

16) If x is an int where x = 1, what will x be after the following loop terminates? while (x < 100)

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

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) Conditions 2, 3 and 4 are all true, Condition 1 is not

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

d) Conditions 2, 3 and 4 are all true, Condition 1 is not 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.

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) This code will work correctly only if grade < 70

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

d) This code will work correctly only if grade < 70 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.

3) Which of the following would not be considered an algorithm?

d) a shopping list 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.

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) if (x < 0) { a = b * 2; y = x; z = a - y; }

6) Of the following if statements, which one correctly executes three instructions if the condition is true?

d) if (x < 0) { a = b * 2; y = x; z = a - y; } 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.

In order to implement Comparable in a class, what method(s) must be defined in that class? Select one: a. equals b. compares c. both lessThan and greaterThan d. compareTo e. both compares and equals

d. compareTo

In order to create a constant, you would use which of the following Java reserved words? Select one: a. private b. static c. int d. final e. class

d. final

An object that refers to part of itself within its own methods can use which of the following reserved words to denote this relationship? Select one: a. inner b. i c. private d. this e. static

d. this

If x is currently 0, a = 1 and b = -1, what will x become after the above statement is executed? if (a > 0) ________if (b < 0) ________x = x + 5; ________else ________if (a > 5) _____________x = x + 4; _____________else _____________x = x + 3; else ________x = x + 2; a) 0 b) 2 c) 3 d) 4 e) 5

e) 5

10) If x is currently 0, a = 1 and b = -1, what will x become after the above statement is executed?

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.

If x is an int where x = 0, 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

e) None of the above, this is an infinite loop

17) If x is an int where x = 0, what will x be after the following loop terminates? while (x < 100) x *= 2;

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

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) all of the above are legal except for d

The size of each rectangle (bar) 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); } 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) decreases in height while staying the same width

25) The size of each rectangle (bar)

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.

5) The idea that program instructions execute in order (linearly) unless otherwise specified through a conditional statement is known as

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.

Having multiple class methods of the same name where each method has a different number of or type of parameters is known as Select one: a. encapsulation b. information hiding c. tokenizing d. importing e. method overloading

e. method overloading

A class' constructor usually defines...

how an object is initialised

A class constructor usually defines ________.

how an object is initialized

A class' constructor usually defines

how an object is initialized

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

how an object is initialized

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;

For an If Else

if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else if (score < 60) grade = F;

31) Rewrite the following set of if statements using a nested if-else structure. if (score >= 90) grade = 'A'; if (score >= 80 && score < 90) grade = 'B'; if (score >= 70 && score < 80) grade = 'C'; if (score >= 60 && score < 70) grade = 'D'; if (score < 60) grade = 'F';

if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'F';

Rewrite the following set of if statements using a nested if-else structure. if (score >= 90) grade = 'A'; if (score >= 80 && score < 90) grade = 'B'; if (score >= 70 && score < 80) grade = 'C'; if (score >= 60 && score < 70) grade = 'D'; if (score < 60) grade = 'F';

if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'F';

Write a method called multiConcat that takes a String and an integer as parameters. Return a String that consists of the string parameter concatentated with itself count times, where count is the integer parameter. For example if the parameter values are "hi" and 4, then return value is "hihihihi". Return the original string if the integer parameter is less than 2.

public String multiConcat (String string, int count) {

Write a code fragment that prints the characters stored in a String object called str backwards.

public String reverse { String result = "Hello"; for (int place = text.length()-1; place >= 0; place--) result += text.charAt(place); return result; }

Write a method called evenlyDivisible that accepts two integer parameters and returns true if the first parameter is evenly divisible by the second, or vice versa, and false otherwise. Return false if either parameter is zero.

public boolean evenlyDivisible (int num1, int num2) { boolean result = false; if (num1 != 0 && num2 != 0) if (num1 % num2 ==0 || num2 % num1 ==0) result = true; return result; }

Define a class that will represent a car.

public class Car

To define a class that will represent a car, which of the following definitions is most appropriate? A) private car class B) public car class C) public class Car D) public class CAR E) private class Car

public class Car

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

public class Car

A java program is best classified as ________.

software

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.

sqrt (Math)

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. equals (String) toUpperCase (String) sqrt (Math) format (DecimalFormat) paint (Applet)

sqrt (Math)

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 (Character) C) sqrt (Math) D) format (DecimalFormat) E) paintComponent (JFrame)

sqrt (Math)

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;

statement2 will only execute if condition1 is false and condition2 is false

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;

statement2 will only execute if condition1 is false and condition2 is false

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;

statement2 will only execute if condition1 is false and condition2 is false

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

statement2 will only execute if condition1 is false, it does not matter what condition2 is

35) Rewrite the following nested if-else statement as an equivalent switch statement. if (letter == 'A' | | letter == 'a') System.out.println("Excellent"); else if (letter == 'B' | | letter == 'b') System.out.println("You can do better"); else if (letter == 'C' | | letter == 'c') System.out.println("Try harder"); else if (letter == 'D' | | letter == 'd') System.out.println("Try much harder"); else System.out.println("Try another major! ");

switch (letter) { case 'A', 'a' : System.out.println("Excellent"); break; case 'B', 'b' : System.out.println("You can do better"); break; case 'C', 'c' : System.out.println("Try harder"); break; case 'D', 'd' : System.out.println("Try much harder"); break; default : System.out.println("Try another major! "); }

An exception can produce a "call stack trace" which lists the active methods in the order that they were invoked the active methods in the opposite order that they were invoked the values of all instance data of the object where the exception was raised 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 the name of the exception thrown

the active methods in the opposite order that they were invoked

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; A) the number of Heads flipped out of 1000 flips B) the number of Heads flipped in a row out of 1000 flips C) the percentage of heads flipped out of 1000 flips D) the percentage of times neither Heads nor Tails were flipped out of 1000 flips E) nothing at all

the percentage of heads flipped out of 1000 flips

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;

the percentage of heads flipped out of 1000 flips

An object that refers to part of itself within its own methods can use which of the following reserved words to denote this relationship?

this

An object that refers to part of itself within its own methods can use which of the following reserved words to denote this relationship? inner i private this static

this

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) self C) private D) this E) static

this

If x is an int where x = 0, what will x be after the following loop terminates? while (x < 100) x *= 2;

this is an infinite loop

In order to have some code throw an exception, you would use which of the following reserved words? throw throws try Throwable goto

throw

In order to have some code throw an exception, you would use which of the following reserved words? A) throw B) pitch C) try D) Throwable E) goto

throw

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?

throw the exception to a pre-defined Exception class to be handled

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? ignore the exception handle the exception where it arose using try and catch statements propagate the exception to another method where it can be handled throw the exception to a pre-defined Exception class to be handled all of the above are ways that a Java program could handle an exception

throw the exception to a pre-defined Exception class to be handled

what is the reserved word continue used for?

to exit the remainder of a loop and test the condition again

The break statement does which of the following?

transfers control out of the current control structure such as a loop or switch statement

A constructor is a method that gets called automatically whenever an object is created, for example with the new operator.

true

A constructor must have the same name as its class.

true

A method defined in a class can access the class' instance data without needing to pass them as parameters or declare them as local variables.

true

An object may be made up of other objects.

true

Assume x and y are String variables with x = "Hello" and y = null. 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

true

Defining formal parameters requires including each parameters type.

true

If a method takes a double as a parameter, you could pass it an int as the actual parameter.

true

If the operation y = x; is performed, then the result of (x = = y) is true false x being set to the value null while y retains the value "Hello" y being set to the value null while x retains the value "Hello" x being set to y, which it is already since y = x; was already performed

true

The body of a method may be empty.

true

The different versions of an overloaded method are differentiated by their signatures.

true

The following method header definition will result in a syntax error: public void aMethod( );

true

The interface of a class is based on those data instances and methods that are declared public.

true

The number and types of the actual parameters must match the number and types of the formal parameters.

true

The println method on System.out is overloaded.

true

While multiple objects of the same class can exist, there is only one version of the class.

true

In order to have a code test some possibly offending code, you would use which of the following reserved words? A) throw B) attempt C) try D) Test E)Exception

try

If x is an int and y is a double, all of the following are legal except which assignment statement? A) y = x; B) x = y; C) y = (double) x; D) x = (int) y; E) All of these are legal

x = y;

Consider the following swap method. If Sting 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; }

x and y remain unchanged

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; } x is now "Goodbye" and y is now "Hello" x is now "Goodbye" and y is still "Goodbye", but (x != y) x is still "Hello" and y is now "Hello", but (x != y) x and y are now aliases x and y remain unchanged

x and y remain unchanged

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

x.charAt(x.length( )-1);

43) Rewrite the following if-else statement using a conditional operator. if (x > y) z = x; else z = y;

z = (x > y) ? x : y;

What value will z have if we execute the following assignment statement? double z = 5 / 10;

z will equal 0.0; 5/10 is executed first which becomes 0 because it's an integer, which is then made a double 0.0


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

Research C10 research study (done)

View Set

Corporate finance summer Ch. 8,13,14

View Set

NH Drivers Notes Chapter 13.1: Vehicle Malfunctions

View Set

LARE - Section 1 Practice Questions

View Set

Suicide Awareness and Prevention

View Set

Business Law II - Chapters 18 & 19

View Set

Exam 2: Tracheostomy & Trach Care (NCLEX)

View Set

Practice Quiz Modifier Placement

View Set

Lymphatic (Ch22) "Clicker Questions"

View Set