Following is from topic exam for assertion:
class C {
String m1(int i) {
switch (i) {
case 0: return "A";
case 1: return "B";
case 2: return "C";
default:
throw new AssertionError();
}
}
public static void main(String[] args) {
C c = new C();
for (int i = 0; i < 4; i++) {
System.out.print(c.m1(i));
}
}
}
Which statements are true?
a. With assertions enabled it prints "ABC" followed by an AssertionError message.
b. With assertions disabled it prints "ABC" followed by an AssertionError message.
c. Assertions should not be used within the default case of a switch statement.
d. In this code example an "assert" statement could not be used in place of the "throw" statement.
e. A compiler error is generated.
f. None of the above.
The given answer is a, b and d. I am not sure about d. The explaination is:
The throw statement is used rather than an assert because the compiler knows that the assert statement is not functional when assertions are disabled.
There is no mentioned assumption that assertions will be enabled or disabled. Therefore, an assert (false) ; could have done the job as well.
Thanks
Barkat