java - SCJP 断言语句

标签 java scjp

这个问题来自 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.

如果禁用断言,则跳过 assertassertsOntrue,因此 if block 是执行。

如果启用断言,则执行assertassertsOntrue,因此断言通过。 assertsOntrue,因此执行 if block 。

答案就是你所说的那样。

assert is on ; assert is on

您可能没有告诉/向我们展示某些内容,或者那里提供的答案缺少正确的答案。

关于java - SCJP 断言语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22232232/

相关文章:

java - 在 weblogic 中使用 log4j 日志记录 9/10

java - 如何使用 ImageIO 保存通过 Graphics 创建的 Java 图像

java - 过滤延迟初始化的 Hibernate 集合

java - Java中的契约是什么

java - 在线程对象上同步

java - 如何删除 JPanel 中由 ArrayList 指定的项目

java相当于php "fnum"unpack函数将十六进制转换为java中的float IEEE 754

java - 符合 Sun 认证 Java 程序员 (SCJP) 准备的项目理念?

java - SCJP-- 数字格式

java - 观察垃圾收集器 bin 一个对象