review test 2 chapters 4,5,7. question for which type of operands does the == operator always work...

Post on 18-Jan-2016

212 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

ReviewTEST 2

Chapters 4,5,7

QUESTION

• For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?

ANSWER

• int

QUESTION

• What will be printed when the following statements are executed?

Account acct1 = new Account(1000.00); Account acct2 = new Account(1000.00); if (acct1 == acct2)

System.out.println("Equal"); else

System.out.println("Not equal");

ANSWER

• Not equal

QUESTION

• What will be printed when the following statements are executed?

int n = 1;

System.out.print(n + " donut"); if (n >= 2);

System.out.print("s");

ANSWER

• 1 donuts

QUESTION

• Write a cascaded if statement that tests the value of the variable temperature. If temperature is less than or equal to 32, the message "Freezing" should be displayed (without the quotes). If temperature is greater than or equal to 212, "Boiling" should be displayed. Otherwise, "Normal" should be displayed

ANSWER

if (temperature <= 32) System.out.println("Freezing"); else if (temperature >= 212) System.out.println("Boiling"); else

System.out.println("Normal");

QUESTION

• Show the values of the variables i and j after statements have been executed.

i = 7; j = i-- * 2 + 1;

ANSWER

• Value of i: 6. Value of j: 15

QUESTION• Assume that a is an array of integers. The following

statements are supposed to search a for the number 7. Unfortunately, there is an error that prevents the statements from working. Describe the error and show how to fix it.

boolean found = false; for (int i = 0; i < a.length && !found; i++)

if (a[i] == 7) found = true;

if (found) System.out.println("Found 7 at position: " +

i);

ANSWER

• The variable i cannot be used after the loop terminates. It should be declared prior to the for statement.

QUESTION

• Use a conditional expression to combine the following statements into a single return statement:

if (i >= 0) return i;

return -i;

ANSWER

return i >= 0 ? i : -i;

QUESTION• Show the output of the following program.

public class Problem54 { public static void main(String[] args) {

g(62.781); g(0.08736);

} private static double f(double x) {

while (x >= 10.0) x /= 10;

while (x < 1.0) x *= 10;

return x; } private static void g(double x) {

System.out.println("f(" + x + ") = " + f(x)); }

}

ANSWER

f(62.781) = 6.2781 f(0.08736) = 8.736

top related