Exam 2 (2015) Flashcards

1
Q

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

a. Always

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

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

A

c. The garbage collector

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How many objects exist in the following code fragment?
String a, b;
int c;

A

0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

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

1

7

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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

1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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

We should not be comparing floating point values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

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

A

b. 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
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();
}
}
A

0, false, null

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

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

return m > 4.5 ? “valid” : null;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q
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";
}
A
switch(x) {
case 'a':
case 'A':
p = "Al";
break;
case 'f':
p = "Fal";
break;
default:
p = "Bob";
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly