Java Reference
In-Depth Information
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"));
}
}
Invoking Baz.testAsserts() causes Baz to be initialized. Before this can happen, Bar must
be initialized. Bar 's static initializer again invokes Baz.testAsserts() . Because initializa-
tion of Baz is already in progress by the current thread, the second invocation executes
immediately, though Baz is not initialized (§ 12.4.2 ).
Because of the rule above, if the program above is executed without enabling asser-
tions, it must print:
Asserts enabled
Asserts disabled
A disabled assert statement does nothing. In particular, neither Expression1 nor Expression2
(if it is present) are evaluated. Execution of a disabled assert statement always completes
normally.
An enabled assert statement is executed by first evaluating Expression1 . If the result is of
type Boolean , it is subject to unboxing conversion (§ 5.1.8 ) .
If evaluation of Expression1 or the subsequent unboxing conversion (if any) completes ab-
ruptly for some reason, the assert statement completes abruptly for the same reason.
Otherwise, execution continues by making a choice based on the value of Expression1 :
• If the value is true , no further action is taken and the assert statement completes nor-
mally.
Search WWH ::




Custom Search