QUESTIONS AND CORRECT ANSWERS
In the code segment below, assume that the int variable n has been properly declared and initialized.
The code segment is intended to print a value that is 1 more than twice the value of n.
/* missing code */ System.out.print(result);
Which of the following can be used to replace /* missing code */ so that the code segment works as
intended?
I. Int result = 2 * n;
Result = result + 1;
II. Int result = n + 1;
Result = result * 2;
III. Int result = (n + 1) * 2; - CORRECT ANSWER (A) I only
Consider the following code segment.
Int a = 5;
Int b = 8;
Int c = 3;
System.out.println(a + b / c * 2);
What is printed as a result of executing this code? - CORRECT ANSWER (D) 9
In the code segment below, assume that the int variables a and b have been properly declared and
initialized.
Int c = a;
Int d = b;
C += 3; d--; double num = c;
Num /= d;
Which of the following best describes the behavior of the code segment? - CORRECT
ANSWER (B) The code segment stores the value of (a + 3) / (b - 1) in the variable num.
, Consider the following code segment, which is intended to find the average of two positive integers, x
and y.
Int x;
Int y;
Int sum = x + y; double average = (double) (sum / 2);
Which of the following best describes the error, if any, in the code segment? - CORRECT
ANSWER (D) In the expression (double) (sum / 2), the cast to double is applied too late, so the
average will be less than the expected result for odd values of sum.
Consider the following static method.
Public static int calculate(int x)
{
X = x + x;
X = x + x;
X = x + x;
Return x;
}
Which of the following can be used to replace the body of calculate so that the modified version of
calculate will return the same result as the original version for all x ? - CORRECT
ANSWER (E) return 8 * x;
Consider the following code segment.
Double num = ; System.out.print(num); System.out.print(" "); System.out.print((int) num);
What is printed as a result of executing the code segment? - CORRECT ANSWER (B) 2.0 2
Which of the following expressions evaluate to 3.5 ?