Given:
class RateOfInterest {
public static void main(String[] args) {
int rateOfInterest = 0;
String accountType = "LOAN";
switch (accountType) {
case "RD":
rateOfInterest = 5;
break;
case "FD":
rateOfInterest = 10;
break;
default:
assert false : "No interest for this account"; //line n1
}
System.out.println("Rate of interest:" + rateOfInterest);
}
}
and the command:
java -ea RateOfInterest
What is the result?
A.
Rate of interest: 0
B. An AssertionError is thrown.
C.
No interest for this account
D. A compilation error occurs at line n1.
题解
Java 的 assertion 叙述通常用于 private 方法内,确保传入方法的参数范围。当 assertion 叙述的判断式为 false 的时候,就会抛出 AssertionError。在运行 Java 程序的时候,若要激活 assertion 叙述的功能,必须要在「java」指令后加上「-ea」或是「-enableassertions」参数来激活 assertion。
在这题的程序中,accountType 所参考到的字符串均不符合 switch 结构中的 case 项目,因此会运行第 22 行 default 的程序。所以第 23 行的 assertion 叙述运行的时候,就会抛出 AssertionError。
