Help with Java assert statement
Hi all ,
The following is the discussion given in "JAVA LANGUAGE SPECIFICATION " at the section The assert statement(14.10)
It says about the circularity to be treated as special condition in assert.
Tried to execute the code , encountering a compile time error
at// assert enabled =true;
following is the code :-
DISCUSSION
There is one case that demands special treatment. 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:
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;// COMPILATION ERROR
System.out.println("Asserts " +
(enabled ? "enabled" : "disabled"));
}
}
Invoking Baz.testAsserts() causes Baz to get initialized. Before this can happen, Bar
must get initialized. Bar抯 static initializer again invokes Baz.testAsserts(). Because initialization
of Baz is already in progress by the current thread, the second invocation executes
immediately, though Baz is not initialized (JLS 12.4.2).
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.
DISCUSSION
In other words, if the program above is executed without enabling assertions, it must print:
Asserts enabled
Asserts disabled
So please let me go through the right course so as to execute the aforementioned program.
Regards
Mukul Sharma

