Question 16
Back to Exercise
What is the output of the following Java program?
class Percentage {
static int created = 0;
final int value;
Percentage(int v) {
if (v < 0 || v > 100) throw new IllegalArgumentException("out of range: " + v);
value = v;
created++;
}
}
public class Main {
public static void main(String[] args) {
Percentage p = new Percentage(40);
try {
p = new Percentage(140);
} catch (IllegalArgumentException e) {
System.out.print(e.getMessage() + " | ");
}
System.out.println(p.value + " " + Percentage.created);
}
}
- A out of range: 140 | 40 1 Correct
- B out of range: 140 | 140 2
- C out of range: 140 | 0 1
- D 40 1
Correct Answer: Option A
The failing new never returns, so p keeps the old object and created was not incremented.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!