这个问题来自 SCJP 转储。可能看起来很愚蠢,但我对选项有点困惑。请帮帮我
public class Donkey2 {
public static void main(String[] args) { boolean assertsOn = true; assert (assertsOn) : assertsOn = true; if(assertsOn) { System.out.println("assert is on"); } }
}
如果 Donkey 类被调用两次,第一次没有启用断言,第二次有 启用断言,结果如何?
一个。无输出
B.无输出;断言开启
C.断言开启
D.无输出;抛出 AssertionError。
E.断言开启;抛出 AssertionError
Answer ) 如果我调用它两次我会得到 断言是 断言开启
这是真的吗?
书上说答案是 C) 但我想它应该是两次,即断言已打开;断言在这两种情况下都是打开的
最佳答案
到Java Language Specification我们走
If the value is true, no further action is taken and the assert statement completes normally.
If the value is false, the execution behavior depends on whether Expression2 is present:
If Expression2 is present, it is evaluated.
If the evaluation completes abruptly for some reason, the assert statement completes abruptly for the same reason.
If the evaluation completes normally, an AssertionError instance whose "detail message" is the resulting value of Expression2 is created.
If the instance creation completes abruptly for some reason, the assert statement completes abruptly for the same reason.
If the instance creation completes normally, the assert statement completes abruptly by throwing the newly created AssertionError object.
如果禁用断言,则跳过 assert
,assertsOn
为 true
,因此 if
block 是执行。
如果启用断言,则执行assert
,assertsOn
为true
,因此断言通过。 assertsOn
为 true
,因此执行 if
block 。
答案就是你所说的那样。
assert is on ; assert is on
您可能没有告诉/向我们展示某些内容,或者那里提供的答案缺少正确的答案。
关于java - SCJP 断言语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22232232/