Page: 3
3. Operators
13. Given:
1. class Maybe {
2. public static void main(String[] args) {
3. boolean b1 = true;
4. boolean b2 = false;
5. System.out.print(!false ^ false);
6. System.out.print(" " + (!b1 & (b2 = true)));
7. System.out.println(" " + (b2 ^ b1));
8. }
9. }
Which are true?
A. Line 5 produces true.
B. Line 5 produces false.
C. Line 6 produces true.
D. Line 6 produces false.
E. Line 7 produces true.
F. Line 7 produces false.
Answer:
-> A , D, and F is correct. The ^ (xor) returns true if exactly one operand is true. The ! inverts the operand’s boolean value. On line 6 b2 = true is an assignment not a comparison, and it’s evaluated because & does not short-circuit it.
-> B, C, and E are incorrect based on the above.
14. Given:
class Sixties {
public static void main(String[] args) {
int x = 5;
int y = 7;
System.out.print(((y * 2) % x));
System.out.print(" " + (y % x));
}
}
What is the result?
A. 1 1
B. 1 2
C. 2 1
D. 2 2
E. 4 1
F. 4 2
G. Compilation fails.
H. An exception is thrown at runtime.
Answer:
->F is correct. The % (remainder a.k.a. modulus) operator returns the remainder of a
division operation.
->A, B, C, D, E, G, and H are incorrect based on the above.
15. Given:
class Scoop {
static int thrower() throws Exception { return 42; }
public static void main(String [] args) {
try {
int x = thrower();
} catch (Exception e) {
x++;
} finally {
System.out.println("x = " + ++x);
} } }
What is the result?
A. x = 42
B. x = 43
C. x = 44
D. Compilation fails.
E. The code runs with no output.
Answer:
->D is correct, the variable x is only in scope within the try code block, it’s not in scope inthe catch or finally blocks.
->A, B, C, and E is are incorrect based on the above.
16. Given:
class Alien {
String invade(short ships) { return "a few"; }
String invade(short... ships) { return "many"; }
}
class Defender {
public static void main(String [] args) {
System.out.println(new Alien().invade(7));
} }
What is the result?
A. many
B. a few
C. Compilation fails.
D. The output is not predictable.
E. An exception is thrown at runtime.
Answer:
->C is correct, compilation fails. The var-args declaration is fine, but invade takes a short,so the argument 7 needs to be cast to a short. With the cast, the answer is B, 'a few'.
->A, B, D, and E are incorrect based on the above. (Objective 1.3)
Page: 3
1
2
3
4
5