Gili Gili - 1 month ago 7
Java Question

Why does an assert statement that executes before its class is initialized behave as if assertions were enabled in the class?

The last question listed at http://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html reads:


Why does an assert statement that executes before its class is initialized behave as if assertions were enabled in the class?

Few programmers are aware of the fact that a class's constructors and methods can run prior to its initialization. When this happens, it is quite likely that the class's invariants have not yet been established, which can cause serious and subtle bugs. Any assertion that executes in this state is likely to fail, alerting the programmer to the problem. Thus, it is generally helpful to the programmer to execute all assertions encountered while in this state.


However, when I ran:

public class Main {

static {
boolean assertionsEnabled = false;
assert (assertionsEnabled = true);
System.out.println("static initializer: " + assertionsEnabled);
}

public Main() {
boolean assertionsEnabled = false;
assert (assertionsEnabled = true);
System.out.println("constructor: " + assertionsEnabled);
}

public static void main(String[] args) {
new Main();
}
}


with assertions disabled, I got an output of:

static initializer: false
constructor: false


What was Oracle referring to in the above text? When are assertions enabled unexpectedly?

UPDATE: I am not asking why I am getting a value of
false
with assertions disabled. This is expected. I am asking why Oracle is implying that assertions will sometimes behave as if they were enabled in spite of the fact that I did not run with
-ea
.

Answer

One just needs to open the Java Language Specification.

Quote:

public class Foo {
    public static void main(String[] args) {
        Baz.testAsserts();
        // Will execute after Baz is initialized.
    }
}
class Bar {
    static {
        Baz.testAsserts();
        // Will execute before Baz is initialized!
    }
}
class Baz extends Bar {
    static void testAsserts() {
        boolean enabled = false;
        assert  enabled = true;
        System.out.println("Asserts " +
                (enabled ? "enabled" : "disabled"));
    }
}

Output:

Asserts enabled
Asserts disabled
Comments