aaaa

Réussis tes devoirs et examens dès maintenant avec 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

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

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

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

D) 10 times

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

D) 11

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

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

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

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

14) Every Interator

D) has a hasNext( ) method

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

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.

A class may contain methods but not variable declarations.

False

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

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

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

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

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? We should only use classes from the library. There is no need to defined others.

False

TRUE or FALSE: Both of the following if statements perform the same operation. if (calls == 20) rate *= 0.5; if (calls = 20) rate *= 0.5;

False

TRUE or FALSE: The following if/else statements cause the same output to display. A) if (x > y) cout << "x is the greater.\n"; else cout << "x is not the greater.\n"; B) if (y <= x) cout << "x is not the greater.\n"; else cout << "x is the greater.\n";

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

True or False - A switch statement must have a default clause.

False

True or False - All objects implement Comparable.

False

True or False - Any class can implement an interface, but no classes can implement more than a single interface.

False

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

False

True or False - In Java, the symbol "=" and the symbol "==" are used synonymously (interchangeably).

False

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

False

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

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

T or F: Within a given java project, there can be multiple classes with the same name

False because in a particular java project, only one class can exist with a given name.

T or F: There can be multiple objects created from the same class

False. In a particular java project, only one class can exist with a given name

T/F All Java classes must contain a main method

False. Only the tester programs conatin the main method. The tester class calls on the other classes as needed.

T/F? The state of an object is represented by its methods.

False. The state of an object is represented by its instance data.

The goal of testing is to ____________.

Find logical and run-time errors

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

Flow of control

Instance data for a Java class

May be primitive types or objects

The calling function has the choices of what?

Specifying a value other than the default for any default parameter.

Global variable are what by default?

Static Variables

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.

What happens if you do not specify the value of a default parameter?

The default value is used for that parameter.

All of the default parameters must be what?

The rightmost parameters of the function.

What is wrong with the following while loop statement? double j = 1.0; while (j < 5.0) { j = j + 0.1; System.out.print(j); }

The while loop is correct

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

flow of control

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

flow of control

Write a code fragment that prints the characters stored in a String object called str backwards.

for (int i = str.length(); i > 0; i--) System.out.print(str.charAt(i-1));

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

Write an if statement that multiplies payRate by 1.5 if hours is greater than 40.

if (hours > 40) payRate *= 1.5;

Which of the following is a possible output from invoking Math.random()? 323.4, 0.5, 34, 1.0, 0.0, 0.234

0.5, 0.0, 0.234

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

_____ is the reserved word used to create an instance of a class (also known as instantiating an object)

"new"

What must you do to use a standard functions?

1. Know the name of the header file that contains the function's specification. 2. Include the header file in the program. 3. Know the name and type of the function, and know the number and types of the parameters.

How many times will the string "Here" be printed? count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 <= 20) { System.out.println ("Here"); count2++; } count1++; }

20

public class Box { double length; double width; double height; public Box(double l, double w, double h) { length = l; width = w; height = h; } public double volume( ) { return length * width * height; } } Write a statement to output the volume of the blue box. (a) System.out.println("Volume of the blue box is: " + blueBox.volume()); (b) System.out.println("Volume of the blue box is: " + blueBox.vol()); (c) System.out.println("Volume of the blue box is: " + blackBox.volume());

(a) System.out.println("Volume of the blue box is: " + blueBox.volume());

Rewrite the following conditional expressions using if-else statements. a. score = (x > 10) ? 3 * scale : 4 * scale; b. tax = (income > 10000) ? income * 0.2 : income * 0.17 + 1000; c. System.out.println((number % 3 == 0) ? i : j);

(a) if (x > 10) score = 3 * scale; else score = 4 * scale; (b) if (income > 10000) tax = income * 0.2; else tax = income * 0.17 + 1000; (c) if (number % 3 == 0) System.out.println(i); else System.out.println(j);

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

(c)Box blueBox = new Box (8,6,4);

Write conditional expression that returns -1 or 1 randomly.

(int)(Math.random() * 2) == 0 ? -1 : 1;

a. How do you generate a random integer i such that 0 <= i < 20 ? b. How do you generate a random integer i such that 10 <= i < 20 c. How do you generate a random integer i such that 10 <= i <= 50 d. Write an expression that returns 0 or 1 randomly.

(int)(Math.random() * 20); 10 + (int)(Math.random() * 10); 10 + (int)(Math.random() * 40); (int)(Math.random() * 2);

(a) Write a Boolean expression that evaluates to true if a number stored in variable num is between 1 and 100. (b) Write a Boolean expression that evaluates to true if a number stored in variable num is between 1 and 100 or the number is negative.

(num > 1) && (num < 100) (num > 1) && (num < 100) || num < 0

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

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

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

Answer the following questions with a yes or no. A) If it is true that x > y and it is also true that x < z, does that mean y < z is true? B) If it is true that x >= y and it is also true that z == x, does that mean that z == y is true? C) If it is true that x != y and it is also true that x != z, does that mean that z != y is true?

A) yes B) no C) no

Rewrite the following if/else statements as conditional expressions: A) if (x > y) z = 1; else z = 20; B) if (temp > 45) population = base * 10; else population = base * 2; C) if (hours > 40) wages *= 1.5; else wages *= 1; D) if (result >= 0) cout << "The result is positive\n"; else cout << "The result is negative.\n";

A) z = x > y ? 1 : 20; B) population = temp > 45 ? base * 10 : base * 2; C) wages *= hours > 40 ? 1.5 : 1; D) cout << (result >= 0 ? "The result is positive\n" : "The result is negative.\n");

What value will z have if we execute the following assignment statement? float z = 5 / 10;

A) z will equal 0.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, what conditions could you use to determine if they are the same length

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

Assuming that x is 1, show the result of the following Boolean expressions. (true) && (3 > 4) !(x > 0) && (x > 0) (x > 0) || (x < 0) (x != 0) || (x == 0) (x >= 0) || (x < 0) (x != 1) == !(x == 1)

(true) && (3 > 4) is false !(x > 0) && (x > 0) is false (x > 0) || (x < 0) is true (x != 0) || (x == 0) is true (x >= 0) || (x < 0) is true (x != 1) == !(x == 1) is true

(a) Write a Boolean expression for |x - 5| < 4.5. (b) Write a Boolean expression for |x - 5| > 4.5.

(x -5) < 4.5 && (x - 5) > -4.5 (x - 5) > 4.5 || (x - 5) < -4.5

Suppose, when you run the following program, you enter the input 2 3 6 from the console. What is the output? public class Test { public static void main(String[] args) { java.util.Scanner input = new java.util.Scanner(System.in); double x = input.nextDouble(); double y = input.nextDouble(); double z = input.nextDouble(); System.out.println("(x < y && y < z) is " + (x < y && y < z)); System.out.println("(x < y || y < z) is " + (x < y || y < z)); System.out.println("!(x < y) is " + !(x < y)); System.out.println("(x + y < z) is " + (x + y < z)); System.out.println("(x + y > z) is " + (x + y > z));

(x < y && y < z) is true (x < y || y < z) is true !(x < y) is false (x + y < z) is true (x + y > z) is false

What will the following program display? #include <iostream> using namespace std; int main () { int a = 0, b = 2, x = 4, y = 0; cout << (a == b) << endl; cout << (a != y) << endl; cout << (b <= x) << endl; cout << (y > a) << endl; return 0; }

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

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

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 inter most statement (x++) how many times

10000

What will the following code display? int funny = 7, serious = 15; funny = serious % 2; if (funny != 1) { funny = 0; serious = 0; } else if (funny == 2) { funny = 10; serious = 10; } else { funny = 1; serious = 1; } cout << funny << "" << serious << endl;

11

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

if x is an int where x=1, what will x be after the following loop terminates

128

int x; x = (5 <= 3 && 'A' < 'F') ? 3 : 4 Based on the code above, what is the value of x?

4

Given the nested if-else structure below: 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 = 1 and b = -1, what will x become after the above statement is executed?

5

if x is currently 0, a=1 and b=-1, what will x become after the above statement is executed

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

this paint method will draw several bars. 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

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 would you describe the relationship between objects and classes

9. Objects are instance of classes. A particular object created from a class has its own set of instance data (variables), that's why the expression "objects are instances of classes" is used

How many bits are there in 12 KB?

98,304

list six relational operators.

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

Which of the following is a relational operator? ! = && ==

==

If you want to output a double so that at least 1 digit appears to the left side of the decimal point and exactly 1 digit appears to the right side of the decimal point, which pattern would you give a DecimalFormat variable when you instantiate it?

A) "0.0"

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

What is output with the statement System.out.println(x+y); if x and y are int values where x=10 and y=5?

A) 15

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

Write a Boolean expression that evaluates to true if weight is greater than 50 pounds and height is greater than 60 inches.

weight > 50 && height > 60

Write a Boolean expression that evaluates to true if either weight is greater than 50 pounds or height is greater than 60 inches, but not both

weight > 50 ^ height > 60

Write a Boolean expression that evaluates to true if weight is greater than 50 pounds or height is greater than 60 inches.

weight > 50 || height > 60

postcondition

what must be true upon when a method finishes executing

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"

What is x after the following if-else statement is executed? Use a switch statement to rewrite it and draw the flowchart for the new switch statement. int x = 1, a = 3; if (a == 1) x += 5; else if (a == 2) x += 10; else if (a == 3) x += 16; else if (a == 4) x += 34;

x = 17 int x =1, a = 3; switch(a) { case 1: x +=5; break; case 2: x+= 10; break; case 3: x+= 16; break; case 4: x+= 34; }

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

instance

An object of a class.

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

B) flow of control

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?

B) m2

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

B) objects are instances of classes

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

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, width of 4, and height of 2.

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

How should stream variables be passed into a function.

By reference`

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

Given the following switch statement where x is an int, answer the questions below 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++ } 4) If x is currently equal to 5, what will the value of x be after the switch statement executes?

C) 11

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.

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

C) 3

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

A cast is required in which of the following situations?

D) storing a float in an int

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 return the last character of the String x?

D) x.charAt(x.length( )-1);

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.

If you want to store into the String name the value "George Bush", you would do which statement?

E) Any of the above would work

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

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.

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

FALSE

(boolean done = false, int x = 10, int y = 11, String s = "Help" and String t = "Goodbye".) True or False - The expression (s.concat(t).length( ) < y) is true.

False

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

False

A constructor must always return an int

False

A constructor must always return an int. (T/F)

False

A dialog box is a device which accepts voice commands.

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

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. (T/F)

False

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

False

Each case in a switch statement must terminate with a break statement.

False

Every class definition must include a constructor.

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. T OR F

False

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

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 loops, but not for loops.

False

In Java, selection statements consist of the 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). 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 more than one item(T/F)

False

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

False

Java methods can return only primitive types (int, double, float, char, boolean, etc). (T/F)

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

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

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

False

if x is an int where x=0, what will x be after the following loop terminates

N/A infinte loop

Is the nesting of function definitions allowed in C++?

No

Can the following conversions involving casting be allowed? Write a test program to verify it. boolean b = true; i = (int)b; int i = 1; boolean b = (boolean)i;

No. Boolean values cannot be cast to other types.

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

None of these, this is an infinite loop.

What does a function prototype do?

It announces the function type and number of parameters in the function.

A return statement without any value can be used where? If it it used in this place what usually happens?

It can be used in a void function. If it is used the function usually exits early.

If a method has a void return type, what does that mean?

It does not contain a return statement, or nothing is returned

What is a call to a void function?

It is a stand alone statement.

What is an automatic variable?

It is a variable for which memory is allocated on function entry and deallocated on function exit.

What is a static variable?

It is a variable for which memory remains allocated throughout the execution of the program.

What is a function prototype? What does it end with?

It is the function is the function heading without the body of the function. It ends in a semicolon.

The scope of a function name is the same as what?

It is the same as the scope of an identifier declared outside of any block.

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

Determining which classes & objects to use or create is part of the ______ phase.

Software Design

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

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

Consider the following outline of a nested if else structure which has more if clauses than else clauses. Determine the result

Statement Z will only execute if condition 1 and condition 2 false.

What is an algorithm and give an example?

Step by step description of how to do something Recipe

What will the following program display? #include <iostream> using namespace std; int main() { int funny = 7, serious = 15; funny = serious * 2; switch (funny) { case 0 : cout << "That is funny.\n"; break; case 30: cout << "That is serious.\n"; break; case 32: cout << "That is seriously funny.\n"; break; default: cout << funny << endl; } return 0; }

That is serious.

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

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

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

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

True

Defining formal parameters requires including each parameters type (T/F)

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

Formal parameters are those that appear in the method header and actual parameters are those that appear in the method call. (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 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 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

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

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 There can be multiple objects created from the same class.

True

T/F? An operation on an object can change the state of an object.

True

T/F? The current state of an object can affect the result of an operation on that object.

True

TRUE or FALSE: Both of the following if statements perform the same operation. if (sales > 10000) commissionRate = 0.15; if (sales > 10000) commissionRate = 0.15;

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

True or False - All three loop statements are functionally equivalent.

True

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

True

True or False - The statement { } is a legal block.

True

True or False - 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

True or False: 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

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

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

Assume the variables a = 2, b = 4, and c = 6. Indicate by circling the T or F if each of the following conditions is true or false: a == 4 || b > 2 6 <= c && a > 3 1 != b && c != 3 a >= -1 || a <= b !(a > 2)

True False True True True

Examine the method header definition below, will it result in a syntax error: public void aMethod( );

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

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

True. Aggregated object is another object that has other objects as instance data.

T or F: 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).

True. newGradeLevel below is the formal parameter while 10 is the actual parameter. public void setGradeLevel(String newGradeLevel) { gradeLevel= newGradeLevel; }

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.

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

What can appear when using function prototypes?

User defined functions.

Are you allowed to have default parameters in C++?

Yes

Can a function be overloaded in C++?

Yes

Even if the function has no parameters what needs to happen.

You still need the empty parenthesis in both the function heading and function call.

To call a void function what do you you use?

You use the function name together with the actual parameters in a stand-alone statement.

Examine the method header definition below, will it result in a syntax error: public void aMethod();

Yes there is a 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.

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.

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.

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.

An example of passing a message to a string where the message has a string parameter occurs in which of the following messages? length substring equals toUpperCase none

equals length & toUpperCase do not have parameters. substring has two int parameters. 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.

What data types are required for a switch variable? If the keyword break is not used after a case is processed, what is the next statement to be executed? Can you convert a switch statement to an equivalent if statement, or vice versa? What are the advantages of using a switch statement?

char, byte, short, int String the next case is processed if the keyword break is not used after a case. you can convert a switch statement to an equivalent if statement. you can't always convert an if statement to a switch statement. Switch statement are simpler to read. The compiled code for the switch statement is also more efficient than its corresponding if statement.

what has no memory space for data

class

The color of the line drawn by the Graphics drawLine() method is:

color of Graphics object used to draw the line

encapsulation

combining data fields and methods in a class

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

compareTo

Assume that count is 0, total is 20 and max is 1. What will the following statement do?

condition short circuits and the assignment is not executed

Assume that x and y are int variable with x=5 , y=3 and a and d are char variable with a='a' and d='A'. Determine which of the following conditions are true

conditions 2,3, and 4 are true

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

Evaluate the following expressions: 2 * 2 - 3 > 2 && 4 - 2 > 5 2 * 2 - 3 > 2 || 4 - 2 > 5

false false

The following truth table shows various combinations of the values true and false connected by a logical operator. Complete the table by indicating if the result of such a combination is TRUE or FALSE. Logical Expression Result (true or false) true && false true && true false && true false && false true || false true || true false || true false || false !true !false

false true false false true true true false false true

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

final

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

flow of control

Consider a method defined with the header: public void foo (int a, int b) -Which of the following methods is legal? foo(0,0.1); foo(0/1,2*3); foo(0); foo(); foo(1+2,3*0.1);

fo(0/1,2*3); The only legal method call is the one that passes 2 int parameters.

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 is a function heading?

functionType functionName (formal parameter list)

What is the general syntax of a user-defined function?

functionType functionName {formal parameter list} { statements }

An object should be encapsulated, _____. An object should be self- _____. The _____ of an object should only be modified by that object. We should make it difficult for code outside of a class to "reach in" and _____. An object should be encapsulated from _____. It should interact with other parts of the program only though the _____ that define the _____. These methods define the _____ between that object and the program that uses it.

guarding its data from inappropriate access; governing; instance data; change the value of a variable that is declared inside that class; the rest of the system; specific set of methods; services that the object provides; interface.

Every Iterator

has a hasNext( ) method

method overloading

having multiple class methods w/ the same name but different parameters

What is the output of the following code if number is 14, 15, or 30? (a) if (number % 2 == 0) System.out.println (number + " is even"); if (number % 5 == 0) System.out.println (number + " is multiple of 5"); (b) if (number % 2 == 0) System.out.println (number + " is even"); else if (number % 5 == 0) System.out.println (number + " is multiple of 5");

number 14 (a)14 is even (b)14 is even number is 15 (a)15 is multiple of 5 (b)15 is multiple of 5 number is 30 (a) 30 is even 30 is a multiple of 5 (b) 30 is even

An _____ has behaviors. It is defined by _____, which is defined by the _____. _____ can be executed on or by a particular _____. _____ may modify the state of it. It's operations are defined by _____.

object; the operations associated with that object; class; Objects; object; Behaviors; methods declared within a class.

Write an if statement that prints the message "The number is not valid" if the variable speed is outside the range 0 through 200.

if (speed < 0 || speed > 200) cout << "The number is not valid.";

Write an if statement that prints the message "The number is valid" if the variable speed is within the range 0 through 200.

if (speed >= 0 && speed <= 200) cout << "The number is valid.";

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

Write an if statement that performs the following logic: if the variable x is equal to 20, then assign 0 to the variable y .

if (x == 20) y = 0;

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

Write an if/else statement that assigns 1 to x if y is equal to 100. Otherwise it should assign 0 to x.

if (y == 100) x = 1; else x = 0;

Write an if statement that assigns 1 to x if y is greater than 0.

if (y > 0) x = 1;

What is the output of the code in (a) and (b) if number is 30? What if number is 35? (a) if (number % 2 == 0) System.out.println(number + " is even."); System.out.println(number + " is odd."); (b) if (number % 2 == 0) System.out.println(number + " is even."); else System.out.println(number + " is odd.");

if number is 30 (a) 30 is even 30 is odd (b) 30 is even if number is 35 (a) 35 is odd (b) 35 is odd

what has its own data space

objects

what should be declared with private visibility

instance variables

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

given that s is a string what does the following loop do

is prints out variables backwards

what happens if a method does not have a return statement?

it is a void method, automatically returns to the calling 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

Question about int j = s length

it prints s out backwards

What is wrong with the following while loop statement? int j; while( j < 5 ) { j = j + 1; System.out.print(j); }

j is never assigned an initial value outside the loop

What is wrong with the following while loop statement? int j = 0; while (j < 5 ) { System.out.print(j); } Answer choices: - The ( ) should not be there -j is never incremented inside the loop, and so the loop is infinite -the { and }should never be used except to begin and end the main method -the = should be == -the while loop is correct

j is never incremented inside the loop, so the loop is infinite

What is wrong with the following for loop statement? for (int j = -1; j <= 5.1; j+=0.1) System.out.println(j);

j should be of type double

when x=0

leave x alone

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

variable declared in method is..

local to that method

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

local variable

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

local variable

what should be encapsulated

objects

A setter (mutator) method

places a value on the information

Consider a method defined with the header: public void herMethod(double x). Is the following method call legal: herMethod(0.1+0.2);

Yes, the method call is legal because the method call performs the addition that yields a double value. This double value is then passed to the method header that accepts a double parameter.

What must happen in order to call a functions?

You have to use its name together with the actual parameter list.

If a formal parameter need to change the value of an actual parameter, what must you do?

You must declare this formal parameter as a reference parameter in the function heading.

Consider a sequence of method invocations as follows: main calls m1, m1 calls m2, m2 calls m3, & then m2 calls m4, m3 calls m5. If m4 has just terminated, what method will resume execution?

m2.

To preserve encapsulation of an object, do not _____.

make the class final.

Instance data for a Java class

may be primitive types or objects

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

Create a method called random50 that returns a random integer in the range of 1 to 50 (inclusive)

public int random%() { Random gen= new Random(); int randomNum = gen.nextInt(50)+1; return randomNum; }

Create a method called random50 that returns a random integer in the range of 1 to 50 (inclusive)

public int random50( ) { Random gen=new Random(); int randomNum=gen.nextInt(50)+1; return randomNum; }

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

what happens to the size of each rectangle

decrease in height while staying the same width

A getter (accessor) method

reads the information

Given a string a which is assumed to have at least one character in it what condition would you use to determine if the first character of the string is the same as the last character

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

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

objects method

defines the behavior of an object

Which kind of loop is a posttest loop? (i.e. The condition is tested at the end of the loop)

do while loop

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 knows as _________.

method overloading

A _____ such as getFaceValue is called an _____ because it provides _____ to a particular value. Often, these method names have the form _____, where _____ is the value to which it _____. Sometimes referred to as _____.

method; accessor method; read- only access; getX; X; provides access; "getter";

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

methods

The behavior of an object is defined by the objects _____.

methods

A method that modifies a value is a _________.

mutator method

Which of the following reserved words in Java is used to create an instance of a class?

new

what reserved word in Java is used to create an instance of a class?

new

which reserved word in java is used to create an instance of a class

new

instance data

new memory space is reserved for that variable every time an instance of the class that is created. each Die object has its own faceValue variable with it own data space.

syntax to instantiate a new object

new object()

What is wrong logically with following code

no logical errors be 2nd x<=10 and 3rd x<=6 not needed

when x<0

subtract one from x

What are the two types of formal parameters?

value parameters and reference parameters.

What does the heading of a void function start with?

void

the expression a || b

F

the programmer creates pseudocode during the implementation

F

the third portion of a for loop the increment portion

F

What does the C++ system provide you?

The standard (predfined) functions.

Which of the following is not a logical operator? || != ! &&

!=

In a UML diagram for a class

E) all of the above

The statement {} is a legal block

T

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

X-- AND X++

- 1 OR + 1

The following code is used in a bookstore program to determine how many discount coupons a customer gets. Complete the table that appears after the program. int numBooks, numCoupons; cout << "How many books are being purchased? "; cin >> numBooks; if (numBooks < 1) numCoupons = 0; else if (numBooks < 3) numCoupons = 1; else if (numBooks < 5) numCoupons = 2; else numCoupons = 3; cout << "The number of coupons to give is " << numCoupons << endl; If the customer purchases this many books |This many coupons are given. 1 3 4 5 10

1 1 2 2 3 3

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

1 5 9 13 17

Given the nested if-else structure below: 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 x is currently 0, a=0 and b=-5, what will x become after the above statement is executed

2

What is the output of the following Java code? int x = 55; int y = 5; switch (x % 7) { case 0: case 1: y++; case 2: case 3: y = y + 2; case 4: break; case 5: case 6: y = y - 3; } println(y);

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

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

What will the following program display? #include <iostream> using namespace std; int main() { const int UPPER = 8, LOWER = 2; int num1, num2, num3 = 12, num4 = 3; num1 = num3 < num4 ? UPPER : LOWER; num2 = num4 > UPPER ? num3 : LOWER; cout << num1 << " " << num2 << endl; return 0; }

2 2

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

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 x is currently 0, a =5 and b=5, what will become after the above statement is executed

3

int x = 3, y; if (x > 5) y = 1; else if (x < 5) { if (x < 3) y = 2; else y = 3; } else y = 4; Based on the code above, what is the value of y?

3

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

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.

What is the output from the following segment of code? int sum = 0; int j = 1; do { sum = sum + j; j = j + 1; }while (j<=5); System.out.print(sum);

6, 15, 10, 4, or none of these

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

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.

Which of the following represents a class and which represents a object: Camery, Car Nick, Male Rapper, G-Easy

A class is a blueprint for common object (think of a category), while an object is an entity that you can manipulate (with methods) Class: Car Object: Camery Class: Male Object: Nick Class:Rapper Object: G-Easy

What does a value parameter receive?

A copy of its corresponding actual parameters.

Functions are said to have different formal parameters if both functions have?

A different number of formal parameters and if the formal parameters are the same, then the data type of the formal parameters, in the order you list them, must differ in at least one position.

What is a void function?

A function that doesn't have a value.

A function can have more than one what? What happens when this occurs?

A return statement. When it executed all remaining statements are skipped and the function exits.

A constant value cannot be passed to what?

A reference parameter.

When you include the & after the data type of a formal parameter, what does the formal parameter become.

A reference parameter.

What is void in C++?

A reserved word.

The corresponding actual parameter of a reference parameter must be what?

A variable

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

Indicate whether each of the following relational expressions is true or false. Refer to the ASCII table in Appendix Bif necessary. A) "Bill" == "BILL" B) "Bill" < "BILL" C) "Bill" < "Bob" D) "189" > "23" E) "189" > "Bill" F) "Mary" < "MaryEllen" G) "MaryEllen" < "Mary Ellen"

A) False B) False C) False D) True E) False F) False G) False

Indicate whether the following statements about relational expressions are correct or incorrect. A) x <= y is the same as y > x. B) x != y is the same as y >= x. C) x >= is the same as y <= x.

A) Incorrect B) Incorrect C) Correct

Assuming x is 5, y is 6, and z is 8, indicate by circling the T or F whether each of the following relational expressions is true or false: A) x ==5 B) 7 <= (x + 2) C) z < 4 D) (2 + x) != y E) z != 4 F) x >=9 G) x <= (y * 2)

A) T, B) T, C) F, D) T, E) T, F) F, G) T

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

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

Indicate whether each of the following relational expressions is true or false. Refer to the ASCII table in Appendix Bif necessary. A) 'a' < 'z' B) 'a' == 'A' C) '5' < '7' D) 'a' < 'A' E) '1' == 1 F) '1' == 49

A) True B) False C) True D) False E) False F) True

Every Interator

A) has a hasNext( ) method

The following statements use conditional expressions. Rewrite each with an if/ else statement. A) j = k > 90 ? 57 : 12; B) factor = x >= 10 ? y * 22 : y * 35; C) total += count == 1 ? sales : count * sales; D) cout << (((num % 2) == 0) ? "Even \ n" : "Odd\n");

A) if (k > 90) j = 57; else j = 12; B) if (x >= 10) factor = y * 22; else factor = y * 35; C) if (count == 1) total += sales; else total += count * sales; D) if (num % 2) cout << "Odd\n"; else cout << "Even\n";

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

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

The word println is a(n)

A) method

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.

A. What is a Java Virtual Machine? Explain its role. Answer: A Java Virtual Machine (JVM) is a software interpreter that executes Java bytecode. Since bytecode is a low-level representation of a program, but not tied to any particular hardware architecture, any computer with a JVM can execute Java code, no matter what machine it was compiled on. That makes Java architecture-neutral, and therefore highly portable. B. What do we mean when we say that the English language is ambiguous? Give two examples of English ambiguity (other than the example used in this chapter) and explain the ambiguity. Why is ambiguity a problem for programming languages? Answer: Something is ambiguous if it has two or more possible meanings. For example, the statement, "Mary is the nicest teaching assistant who has helped me all day long" might mean 1) of all the teaching assistants who have helped me today, Mary is the nicest, or 2) of those teaching assistants who have helped me for an entire day, Mary is the nicest. As another example, the statement, "Bananas help those who help themselves" might mean 1) bananas are good for those who attend to their own welfare or 2) bananas are good for those who eat as many bananas as they please. If a programming language statement could be interpreted in two or more ways, it would be impossible to predict with certainty how it would be interpreted and what result would be produced. M/C answers below:

A. Both A. and B are true

Which of the following statements are equivalent? Which ones are correctly indented? (a) if (i > 0) if (j > 0) x = 0; else if (k > 0) y = 0; else z = 0; (b) if (i > 0) { if (j > 0) x = 0; else if (k > 0) y = 0; } else z = 0; (c) if (i > 0) if (j > 0) x = 0; else if (k > 0) y = 0; else z = 0; (d) if (i > 0) if (j > 0) x = 0; else if (k > 0) y = 0; else z = 0;

ACD are equivalent B and C are correctly indented

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.

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.

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.

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.

You cannot assign a constant value as what?

As a default value to a reference parameter.

_____, such as variable faceValue are called _____ because new memory space is reserved for that _____ every time _____. Example: Each Die _____ has its own faceValue _____ with its own data space. That's how each Die object can have its own _____. May be _____ types or _____. Declared in the _____.

Attributes; instance data; variable; an instance of that class is created; object; variable; state; primitive; objects; class.

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

The final println command will output

B) "But notin Texas"

Suppose that String name = "Frank Zappa". What will the instruction name.toUpperCase( ).replace('A', 'I'); return?

B) "FRINK ZIPPI"

The Random class has a method nextFloat( ) which returns a random float value between

B) 0 and 1

Consider the following statement: System.out.println("1 big bad wolf\t8 the 3 little pigs\n4 dinner\r2night"); This statement will output ________ lines of text

B) 2

How many lines of output are provided by this program?

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

Explain why you cannot convert the following if/else if statement into a switch statement. if (temp == 100) x = 0; else if (population > 1000) x = 1; else if (rate < .1) x = −1;

Because the if /else if statement tests several different conditions, consisting of different variables.

when comparing any promotive type of variable == should always be see to test to see if two values are equal

F

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

Use the following class definition to answer the questions below. public class Questions1_4 { public static void main(String[ ] args) { System.out.print("Here"); System.out.println("There " + "Everywhere"); System.out.println("But not" + "in Texas"); } } The program will print the word "Here" and then print

C) "There Everywhere" on the same line as "Here"

Given the following assignment statement, which of the following answers is true regarding the order that the operators will be applied based on operator precedence? a = (b + c) * d / e - f;

C) +, *, /, -

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.

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

F

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' || d !='A')

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

What are the possible values of default values?

Constants, global values, or function calls.

The Dog method is known as a(n) ___________.

Constructor

An order to preserve encapsulation of an object, what would we not do

Make the class final

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

Using getCurrencyInstance( ) formats a variable, automatically inserting

E) A and B but not C

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.

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

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

E) 11 times

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

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

Which of the following are true statements about check boxes?

E) all of the above

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

E) flow of control

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

E) it prints s out backwards

Which library package would you import to use the class Random?

E) java.util

Which of the following reserved words in Java is used to create an instance of a class?

E) new

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

E) none of the above

What value will z have if we execute the following assignment statement? int z = 50 / 10.00;

E) none of the above, a run-time error arises because z is an int and 50 / 10.00 is not

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

Which identifier would be most appropriate for a class dealing with eagles?

Eagle

software design is the first step in program development

F

the relational operates < and > can be used

F

the symbol = and == are used interchangeably

F

What are actual parameters?

Expressions, Variables, or constant values.

A constructor must always return an int.

F

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

F

Every class definition must include a constructor.

F

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

F

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

F

The expression (done || s.compareTo(t)<0) is true

F

The expression (s.concat(t).length()<y) is true

F

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

F

if the integer variable answer is 5

F

in java it is possible to create an infinite loop out of while loops but not for loops

F

in order to compare int and double variables you can use < > == != <= >= but to compare char and string variables you must use compareTo(), equals() and equalsIgnoreCare()

F

only difficult programming problems require a psuedocode solution before the programmer creates the implement ion itself

F

What is put before every function definition? Including what?

Function prototypes including the definition of the function main.

A class' constructor usually defines

How an object is initialized

If a function has more than one default parameter what must you do?

IF a value to a default parameter is not specified, then you must omit all arguments to its right.

List four phases

Implementation Requirements Design Testing

What happens if a function is overloaded?

In a call to a function, the signature, that is, the formal parameter list of the function, determines which function to execute.

A listener is an object that uses the _____.

InputStreamReader class.

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

Instance data or Instance variable

What is the purpose of a constructor?

It is used to create a new object and initialize instance data

What purpose does a constructor have?

It is used to create a new object and initialize instance data

If a method does not have a return statement, then

It must be a void method

What does a reference parameter receive?

It receives the address of its corresponding actual parameter.

What does a value returning function do? Where is it found? How is it found?

It returns a value. It is used in either an expression or an output statement or a parameter in a function call.

How does a value returning function return values?

It returns values via the return statement.

What does a call to a function do?

It transfers control from the caller to the called function.

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 not need to ____________.

Make the class final

The public interface of a class is based on _____ that are declared public.

Methods

______ determines the behavior of an object

Methods

An _____ has a state. It is defined by ______.

Object; the values of the attributes associated with that object.

What is the relationship between objects and classes?

Objects are instance of classes. A particular object created from a class has its own set of instance data ( or instance variable), that's why the expression "objects are instances of classes" is used.

The relationship between a class & an object is best described as?

Objects are instances of classes

How many values does a return value have?

One

The following code segment is syntactically correct, but it appears to contain a logic error. Can you find the error? if (interestRate > .07) cout << "This account earns a $10 bonus.\n"; balance += 10.0;

Only the first statement after the if statement is conditionally executed. Both of the statements after the if statement should be enclosed in a set of braces.

A void function may or may not have what?

Parameters`

Volatility is a property of ________.

RAM

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

Random access

Static methods cannot ____________.

Reference non-static instance data

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

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

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

T

A constructor must have the same name as its class.

T

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

T

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

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

T

Any for loop can be written as a while loop

T

Defining formal parameters requires including each parameter type.

T

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

T

The expression (!done&& x<= y) is true

T

The following for loop is an infinite loop

T

The following loop is syntactically valid

T

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

T

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

T

The statement num-=num will have the same result as the statement num=0

T

The statements X++ and ++X

T

in java if and if else are selection statements

T

the expression Z < a is true

T

T or F: 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).

T newGradeLevel below is the formal parameter while 10 is the actual parameter. public void setGradeLevel(String newGradeLevel) gradeLevel=newGradeLevel; sammy.setGradeLevel(10);

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

T. All loop statements have equivalent expressive power.

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; } -The instruction Die d = new Die (10); results in? -The instruction Die d = new Die (10,0); results in?

The Die d having numFaces= 10 and faceValue = 1. Syntax error. The die class has 2 constructors, one that receives no parameters and one that receives a single int parameter. The instructor above calls the Die constructor with 2 int parameters. Since no constructor matches this number of parameters exist, a syntax error occurs.

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

What do you specify in a function call statement?

The actual parameters,

What are statements enclosed in brackets { } called?

The body of the function.

Who does the control go back to after the function exits,

The caller.

What is wrong with the following switch statement? switch (temp) { case temp < 0 : cout << "Temp is negative.\n"; break; case temp == 0: cout << "Temp is zero.\n"; break; case temp > 0 : cout << "Temp is positive.\n"; break; }

The case statements must be followed by an integer constant, not a relational expression.

Assume you re defining a class and you want to implement an Action Listener. You state: addActionListener(this) in your class' constructor. -What does this mean?

The class must define the method action performed.

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;

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.

The do loop differs from the while loop in that

The do loop will always execute the body of the loop at least once

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

When a program executes, what always begins first?

The first statement in the function main.

What is the definition of the function?

The function heading and the body of the function.

What is in the signature of a function?

The function name and its formal parameter list.

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?

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

Consider a method defined with the header: public void myMethod(int a, int b). Is the following method call legal: myMethod(5+2, 0.2+0.1)

The method call is no legal because the only legal method call is one that passes two int parameters. The method call contains two parameters, but the second parameter is a double.

Consider a method defined with the header: public void herMethod(double x). Is the following method call legal: herMethod(0.1+0.2);

The method is legal because the method asks for a double value. This double value is then passed tot he method header that accepts a double parameter.

What are the optional things in a function prototype?

The names of the variables in the formal parameter.

What must happen in a function call?

The number of actual parameters and their types must match with the formal parameters in the order given.

What is the scope of an identifier?

The parts of the program where the identifier is accessible.

List the precedence order of the Boolean operators. Evaluate the following expressions: true || true && false true && true || false

The precedence order for boolean operators is !, ^, &&, and || true true

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

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

The variable being tested might equal one of only a few int values

The following code segment is intended to compute the product of the first 5 even integers, starting with 2. product = 0; for(int k = 1; k <= 5; k++) { product *= 2*k; } Which of the following best describes the error, if any, in this code Answer choices: -The variable product is incorrectly initialized. The segment would work as intended if product were initialized to 1. -The loop bounds are incorrect, "k <= 5" should be replaced with "k < 5" -The segment computes the product of the first ten even integers -The segment works as intended. -The segment computes the product of the first four even integers

The variable product is incorrectly initialized. The segment would work as intended if product were initialized to 1.

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

What do functions allow you to do?

They allow you to divide a program into manageable tasks.

What are functions like?

They are like miniature programs and are called modules.

What are local variables?

They are variables declared within a function.

What is the purpose of function prototypes?

They help the compiler correctly translate each function call.

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.

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

Consider a method defined with the header: public void hisMethod(int val). Is the following method call legal: hisMethod(.223);

This method doesn't work because the passed parameter is a double but the method header is looking for a integer parameter.

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

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;

What are the two types of used defined functions?

Value returning functions and void functions.

What are global variables?

Variables declared outside of every function definition.

What are formal parameters?

Variables defined in a function.

_____ control access to the members of a class. The reserved words public & private are visibility modifiers that can be _____. If a member of a _____ has public visibility, it can be directly referenced from outside of that _____. If a member of a _____ has private visibility, it can be used anywhere inside the _____, but not referenced externally. Protected visibility is relevant only in the context of _____. _____ violate encapsulation because they allow code external to the class in which the data is defined to reach in and access or modify the _____. Therefore, _____ should be defined with _____. Data that is declared _____ can be accessed only by the methods of the _____. The visibility we apply to methods depends on the purpose of that method. Methods that provide services to the client must be declared with _____ so that they can be invoked by the client. These methods are sometimes referred to as _____. A _____ method cannot be invoked from outside the class. The only purpose of this method is to help the other _____ do their job. Therefore, they are sometimes referred to as _____. It is generally acceptable to give _____ public visibility because, although their values can be accessed directly, they cannot be changed because they were declared using the _____ modifier. _____ issue is largely moot. UML class diagrams show the visibility of a _____ by preceding it with a _____ for public and _____ for private.

Visibility modifiers; variables and methods of a class; class; object. class; class definition; inheritance. Public variables; value of data; instance data; private visibility; class; public visibility; service methods. private; methods of the class; support methods. constants; final; encapsulation. class; (+); (-);

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

When do used defined functions execute?

When they are called.

Which of the following represents a class and which represents a object: RangeRover, Car Julie, Female Rapper, JayZ

Which of the following represents a class and which represents a object: RangeRover, Car Julie, Female Rapper, JayZ

if (5 > 4 + 3) println("Hello"); println("World"); What is the output of the code above?

World

If you executed the following code, what would it display if the user enters 5? What if the user enters 15? What if the user enters 30? What if the user enters −1? int number; cout << "Enter a number: "; cin >> number; if (number > 0) { cout << "Zero\n"; if (number > 10) { cout << "Ten\n"; if (number > 20) { cout << "Twenty\n"; } } }

Zero Zero Ten Zero Ten Twenty No Output

The Color class constant, Color.RED is:

a Color object that is defined inside the Color class

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

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

Write a Boolean expression that evaluates to true if age is greater than 13 and less than 18.

age > 13 && age < 18

precondition

a condition that must be true before a use case begins

What cant have any return type even void

a constructor

void

a method does not return a value

calling method

a method that calls another method.

setAge() is an example of ________

a mutator method

Which of the following would not be considered an algorithm? a recipe a computer program pseudocode a shopping list travel directions

a shopping list

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.

Categorize the following as a compile-time error, run-time error, or logical error. Q6.Multiplying two numbers when you meant to add them

a. logical error

Producing inaccurate results

a.logical error

Spelling a word wrong in the output

a.logical error

When x>0

add one to x

Which one of the following is NOT true about the for loop shown below? for (int j = 1; j <= numtimes; j++) System.out.println(j); Answer choices: -j is called the index or loop variable -j can be of type int or double or char -j receives a starting value of 1 -all of them are true -numtimes can be of type int or double or char

all of them are true

*Considering the (incomplete) code below, x is probably while (x.hasNext()) { ... x.next() ... ... }

an iterator

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

an object is instance of a class

aggregate object

any object that is made up of other objects

int num = 87, max = 25; if (num > max * 2) System.out.println ("apple"); System.out.println ("orange"); System.out.println ("pear");

apple orange pear

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

Rewrite the following statement using a Boolean expression: if (count % 10 == 0) newLine = true; else newLine = false;

boolean newLine = (count % 10 == 0);

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

Typing a { when you should have typed (

c. compile-time error

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

Which of the following is not valid Java identifier?

c. hook&ladder

Which of the following is not a selection control structure in Java? if case if...else switch

case

Which of these cannot be used as a case label in a switch statement : case 10: case x: // assume x is a final int variable case 10..20: case 'C':

case 10..20:

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

Logical operators :

can be used to combine two boolean expressions

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.

If a language uses 240 unique letters and symbols, how many bits would be needed to store each character of a document?

d. 8

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.

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 initialized

class constructor

how an object is initialized

A class' constructor usually defines _____.

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

Write an if statement that performs the following logic: if the variable price is greater than 500, then assign 0.2 to the variable discountRate .

if (price > 500) discountRate = 0.2;

Write an if statement that performs the following logic: if the variable sales is greater than 50,000, then assign 0.25 to the commissionRate variable, and assign 250 to the bonus variable.

if (sales > 50000) { commissionRate = 0.25; bonus = 250; }

Write an if/else statement that assigns 0.10 to commissionRate unless sales is greater than or equal to 50000.00, in which case it assigns 0.20 to commissionRate .

if (sales >= 50000.00) commissionRate = 0.20; else commissionRate = 0.10;

Write an if statement that increases pay by 3% if score is greater than 90.

if (score > 90) pay *= 1.03;

Write an if statement that increases pay by 3% if score is greater than 90, otherwise increases pay by 1%.

if (score > 90) pay *= 1.03; else pay *=1.01;

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

Define a class that will represent a car. Explain

public class Car public allows them to be accessed by other classes.

private String name; private String position; private int numAtBats; private int numSingles; private int numDoubles; private int numTriples; private int numHomeRuns; private double battingAverage; Write a constructor, which is passed the player's name and position.

public BaseballPlayer(String aName, String aPosition) { name = aName; position = aPosition; numAtBats = 0; numSingles= 0; numDoubles = 0; numTriples = 0; numHomeRuns = 0; num battingAverage = 0.0; }

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 toString method that returns the player's name, position and batting average

public String toString( ) { battingAverage; }

private String name; private String position; private int numAtBats; private int numSingles; private int numDoubles; private int numTriples; private int numHomeRuns; private double battingAverage; Write a toString method that returns the player's name, position and batting average

public String toString() { return "Name: " + name + "\t Position: " + position +Batting Average: \t" + battingAverage; }

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

syntax to define a class

public class

define a class that will represent a boat

public class Boat

To define a class that will represent a car, which of the following definitions is most appropriate?

public class Car

What is wrong in the following code? if (score >= 60.0) System.out.println("D"); else if (score >= 70.0) System.out.println("C"); else if (score >= 80.0) System.out.println("B"); else if (score >= 90.0) System.out.println("A"); else System.out.println("F");

since score is assessed against the lowest number first, as long as score is greater than the lowest number the grade will always be a d and no other conditional will be evaluated. It's a logic error.

A java program is best classified as ________.

software

Which phrase development would you expect programmers to determine the classes and objects needed?

software design

Suppose that, when you run the following program, you enter the input 2 3 6 from the console. What is the output? public class Test { public static void main(String[] args) { java.util.Scanner input = new java.util.Scanner(System.in); double x = input.nextDouble(); double y = input.nextDouble(); double z = input.nextDouble(); System.out.println((x < y && y < z) ? "sorted" : "not sorted"); } }

sorted

What method is a static method? The class in which the method is defined is given in parentheses following the method name.

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 true and condition2 is false

Are the following statements correct? Which one is better? (a) if (age < 16) System.out.println ("Cannot get a driver's license"); if (age >= 16) System.out.println ("Can get a driver's license"); (b) if (age < 16) System.out.println ("Cannot get a driver's license"); else System.out.println ("Can get a driver's license");

statements are correct. B is better

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

Rewrite the following program. Use a switch statement instead of the if/else if statement. #include <iostream> using namespace std; int main() { int selection; cout << "Which formula do you want to see?\n\n"; cout << "1. Area of a circle\n"; cout << "2. Area of a rectangle\n"; cout << "3. Area of a cylinder\n" cout << "4. None of them!\n"; cin >> selection; if (selection == 1) cout << "Pi times radius squared\n"; else if (selection == 2) cout << "Length times width\n"; else if (selection == 3) cout << "Pi times radius squared times height\n"; else if (selection == 4) cout << "Well okay then, good bye!\n"; else cout << "Not good with numbers, eh?\n"; return 0; }

switch (selection) { case 1 : cout << "Pi times radius squared\n"; break; case 2 : cout << "Length times width\n"; break; case 3 : cout << "Pi times radius squared times height\n"; break; case 4 : cout << "Well okay then, good bye!\n"; break; default : cout << "Not good with numbers, eh?\n"; }

Complete the following program skeleton by writing a switch statement that displays "one" if the user has entered 1, "two" if the user has entered 2, and "three" if the user has entered 3. If a number other than 1, 2, or 3 is entered, the program should display an error message. #include <iostream> using namespace std; int main() { int userNum; cout << "Enter one of the numbers 1, 2, or 3: "; cin >> userNum; // // Write the switch statement here. // return 0; }

switch (userNum) { case 1 : cout << "One"; break; case 2 : cout << "Two"; break; case 3 : cout << "Three"; break; default: cout << "Enter 1, 2, or 3 please.\n"; }

Write a switch statement that displays Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, if day is 0, 1, 2, 3, 4, 5, 6, accordingly.

switch(day) { case 0: System.out.println("Sunday"); break; case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; }

An example of an aggregation relationship is

teacher and computer

What is wrong with the following while loop statement? int j = 0; while j < 5 { j = j + 1; System.out.print(j); }

the () are missing

What is wrong with the following for loop statement? for (int j = 1; j<=10 , j++) System.out.println(j);

the comma after j<=10 should be a semicolon

when a method is terminated, where does the execution resume?

the flow of control returns to the place where the method was called and continues

What is wrong with the following for loop statement? for (int j = -3; j <= 8; j++) System.out.println(j);

the for loop is correct

What is wrong with the following while loop statement? int j = 5; while (j > 0) { j-1 = j; System.out.print(j); }

the j-1 = j; should be j = j-1;

What is wrong with the following while loop statement? int j = 0; while ( j < 3 ) System.out.print(j); Answer choices: -the symbol < is not a valid boolean operator -there is nothing wrong -j should always be initialized to 1, not 0 -j should always be of type double -the loop is an infinite loop, since j is not changed

the loop is an infinite loop, since j is not changed

where is a local variables scope restricted to

the method where it as declared

scope of a variable

the region of a program in which the variable can be accessed

What is wrong with the following for loop statement? for (int j = 1; j <= 10; j++); System.out.print("*"); Answer choices: •there should not be a semicolon after the parentheses •there is no error •the for should be FOR •System.out.print is not a command •the * should be enclosed with single quotes

there should not be a semicolon after the parentheses

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

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

Rewrite the following if statements using the conditional operator. if (ages >= 16) ticketPrice = 20; else ticketPrice = 10;

ticketPrice = (ages >= 16) ? 20: 10;

The break statement does which of the following?

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

True or false? All the binary operators except = are left associative.

true

Assuming that x is 1, show the result of the following Boolean expressions: x > 0 x < 0 x != 0 x >= 0 x != 1

true false true true false

The parameters passed to the Graphics drawLine() method represent:

two end-points

Suppose x = 2 and y = 3. Show the output, if any, of the following code. What is the output if x = 3 and y = 2? What is the output if x = 3 and y = 3? if (x > 2) if (y > 2) { int z = x + y; System.out.println("z is " + z); } else System.out.println("x is " + x);

x = 2 and y = 3 no output x = 3 and y = 2 x is 3 x = 3 and y = 3 z is 6 No output if x = 2 and y = 3. Output is “x is 3†if x = 3 and y = 2. Output is “z is 6†if x = 3 and y = 3.

Suppose x = 3 and y = 2; show the output, if any, of the following code. What is the output if x = 3 and y = 4? What is the output if x = 2 and y = 2? Draw a flowchart of the code. if (x > 2) { if (y > 2) { z = x + y; System.out.println("z is " + z); } } else System.out.println("x is " + x);

x = 3 and y =2 no output x = 3 and y =4 z is 7 x = 2 and y = 2 x is 2

What is the value of the expression x >= 50 && x <= 100 if x is 45, 67, or 101?

x = 45 false x = 67 true x = 101 false

Assume that x and y are int type. Which of the following are legal Java expressions? x > y > 0 x = y && y x /= y x or y x and y (x != 0) || (x = 0)

x > y > 0 incorrect because x > y is evaluated to a boolean value, which cannot be compared to 0 x = y && y -> cannot conver boolean types x /= y correct x or y incorrect x and y incorrect (x != 0) || (x = 0) incorrect x = 0 is wrong it should be x == 0

What is y after the following switch statement is executed? Rewrite the code using an if-else statement. x = 3; y = 3; switch (x + 3) { case 6: y = 1; default: y += 1; }

y is 2 if (x + 3 == 6) { y = 1; { else y +=1;

Are the following two expressions the same? (a) x % 2 == 0 && x % 3 == 0 (b) x % 6 == 0

yes

Are the following two statements equivalent? (a) if (income <= 10000) tax = income * 0.1; else if (income <= 20000) tax = 1000 + (income - 10000) * 0.15; (b) if (income <= 10000) tax = income * 0.1; else if (income > 10000 && income <= 20000) tax = 1000 + (income - 10000) * 0.15;

yes

Is x > 0 && x < 10 the same as x > 0 && x < 10? Is x > 0 || x < 10 the same as x > 0 || x < 10? Is (x > 0 || x < 10) && y < 0 the same as (x > 0 || (x < 10 && y < 0))?

yes yes yes

43) Rewrite the following if-else statement using a conditional operator. if (x > y) z = x; else z = y;

z = (x > y) ? x : y;

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


Ensembles d'études connexes

Medicine in America Final Multiple Choice

View Set

Chapter 6 Section 3 Reading Guide

View Set

B.Arab = Terjemahan surat Al-fatihah

View Set

end of section review questions 13

View Set

Ch.18 Sec.4 Questions (Only 2 and 3)

View Set

Davis Review Questions - Exam 1

View Set

Гинекология Экзамен

View Set