Monday, 10 September 2007

Assertion Special Case in Java

Contiuning Reading Java Language Specification turned to section Blocks And Statements

Well talking about Assertions can we predict the output of this program? :

public class AssertionsExample {
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"));
}
}

It prints:
Asserts enabled
Asserts disabled

If we read specification carefully it states:

"Recall that the assertion status of a class is set at the time it is initialized. It is possible, though generally not desirable,to execute methods or constructors prior to initialization.This can happen when a class hierarchy contains a circularity in its static initialization,as in the following example.as in the following example:
Invoking Baz.testAsserts() causes Baz to get initialized. Before this can happen,
Bar must get initialized. Bar's static initializer again invokes Baz.testAssert().
Because initialization of Baz is already in progress by the current thread,
the second invocation executes immediately, though Baz is not initialized.If an assert statement executes before its class is initialized,as in the above example, the execution must behave as if assertions were enabled in the class."

Hope it helps and please let me know if any further explanation required.

No comments: