benf.org :  other :  cfr :  How is 'assert' implemented?

Aside - Assert

Again, nothing secret here - the documentation for desired assertion status is here, and there is a proposal for assertions here.

And there's a sun/oracle tutorial here.

A little history

Assertions were introduced in java 1.4. As with many things in Java, they're implemented as changes to the language and syntactic sugar rather than underlying JVM changes

C programmers might expect asserting code not to get compiled at all, but that's because C has differing release and debug versions - that's a runtime decision for java - the oracle tutorial page has a good section on design considerations.

Original code

public class AssertTest {

    public void test1(String s) {
        assert (!s.equals("Fred"));
        System.out.println(s);
    }
}

Decompiled with CFR 0_14 (assert sugaring disabled with '--sugarasserts false')

public class AssertTest {
    static final /* synthetic */ boolean $assertionsDisabled;

    public void test1(String s) {
        if ((!(AssertTest.$assertionsDisabled)) && (s.equals("Fred"))) {
            throw new AssertionError();
        }
        System.out.println(s);
    }

    static {
        AssertTest.$assertionsDisabled = !(AssertTest.class.desiredAssertionStatus());
    }

}

You can see that 'is an enum on for this class' is a static, which is initialised in the static initialiser block, and 'assert' gets compiled down to if statements which check this condition.

One thing that's interesting - the original proposal called for $assertionsEnabled, but we have ended up with $assertionsDisabled. I have no idea why!

Decompiled with CFR 0_14, default options

public class AssertTest {

    public void test1(String s) {
        assert (!(s.equals("Fred")));
        System.out.println(s);
    }

}

Last updated 02/2013