Matt said:
Someone told me in Java, we can execute the statements inside an
if-statement without evaluating the if expression.
i.e. if (expr)
{
stmt
}
I think about that, it seems doesn't make sense. I think in all
programming languages, it must execute the if expression. What do u
think? Please advise.
The Java Language Specification (Sections 14.9.1 and 14.9.2)
unconditionally says that the expression is evaluated as part of the
execution of the if statement. In some cases, however, the Java or JIT
compiler might eliminate the if statement altogether if there is only
one possible result AND if evaluation of the expression cannot have any
side effects. As an example, some in this forum advocate simulating
conditional compilation in Java like this:
[...]
final static boolean DEBUG = <true or false>;
[...]
if (DEBUG) {
[conditionally compiled code here]
}
[...]
If DEBUG is assigned the value false then in principle the compiler
could omit the if statement and [conditionally compiled code] from the
bytecode altogether; otherwise it could omit the if statement itself but
include [conditionally compiled code] in the bytecode for the
immediately containing block. Note that DEBUG is final and static.
This optimization amounts to the compiler evaluating the expression
instead of making the VM do it at runtime. Neither Java nor JIT
compiler may omit the if statement if doing so can change any of the
results of executing the program.
It is also the case that Java provides short-circuit boolean operators
(&& and ||), which in some well-defined cases cause only part of a
boolean expression (the conditional expression of an if, for example) to
be evaluated. In this case potential side effects of the unevaluated
portion(s) are irrelevant, because the language spec (Sections 15.23 and
15.24) is explicit about which parts of the expression are evaluated in
which circumstances.
John Bollinger
(e-mail address removed)