I'd like to know how Java would handle the following scenario:
Suppose I have a class called Debug, which looks like this:
public class Debug
{
private static final boolean isAssertEnabled = true;
public static void assertTrue(boolean b, String errorMessage) {
if (isAssertEnabled) {
if (!b) {
throw new RuntimeException(errorMessage);
}
}
}
}
and suppose my code has a call that looks something like this:
...
Debug.assertTrue((x + y != z) && (v - u > w), "Some error message");
....
I have a few questions:
Thanks for you help!
The evaluation of the boolean expression should not be compiled away - at least by javac.
Even if the Debug
class file currently do nothing with the value, who's to say that that will be the case at execution time?
After making the Debug class compile (by making isAssertEnabled
static), javac still includes the code - but I would expect the JIT compiler to remove it (although you should see the question Peter referenced). Whether it could then inline the method to nothing, I'm not sure. Again, if the JIT compiler could do that, and if it realized that evaluating the arguments couldn't have any side-effects, it could potentially avoid the evaluation. I wouldn't personally write code depending on that though.