Exam 2 (2015) Flashcards
When is the code associated with a finally block executed?
a. Only when the exception occurs.
b. Always
c. Only if no exception occurs.
d. None of the above.
a. Always
Which of the following takes care of an object that is no longer referenced by any variables?
a. The stack
b. The heap
c. The garbage collector
d. The constructor
c. The garbage collector
How many objects exist in the following code fragment?
String a, b;
int c;
0
What is the output of the following code fragment?
for (int i = 1; i <= 8; i += 3) { if (i == 4) { continue; } System.out.println(i); }
1
7
What is the output of this code fragment if we replace continue; with break; ?
What is the output of the following code fragment?
for (int i = 1; i <= 8; i += 3) { if (i == 4) { continue; } System.out.println(i); }
1
The following code compiles. Do you see any problems with the code? Write NONE if no problems or invalid operations are present. You can assume the method is in a class that compiles.
public void check(double val, int x) { if (x > 0) { if (val == 4.5) { System.out.println("expected"); } } }
We should not be comparing floating point values.
How many default constructors do we have in the following class?
public class Apple { private String flavor; }
a. 0
b. 1
c. The above class does not compile.
d. None of the above
b. 1
What is the output of the following program? If an exception is thrown indicate why. public class Values { public int a; public boolean b; public String c; public Values() { String d = c; System.out.println(a + ", " + b + ", " + d); } public static void main(String[] args) { Values v = new Values(); } }
0, false, null
Rewrite the body of the following method so it uses a single statement and the ternary operator(? :).
public String original(double m) { String a = null; if (m > 4.5) { a = "valid"; } return a; }
return m > 4.5 ? “valid” : null;
Rewrite the following code using a switch statement. String p; if (x == 'a' || x == 'A') { p = "Al"; } else if (x == 'f') { p = "Fan"; } else { p = "Bob"; }
switch(x) { case 'a': case 'A': p = "Al"; break; case 'f': p = "Fal"; break; default: p = "Bob"; }