Java Reference
In-Depth Information
9.3. Expressions
An expression consists of operators and their operands, which are eval-
uated to yield a result. This result may be a variable or a value, or even
nothing if the expression was the invocation of a method declared void .
An expression may be as simple as a single variable name, or it may be a
complex sequence of method invocations, variable accesses, object cre-
ations, and the combination of the results of those subexpressions using
other operators, further method invocations, and variable accesses.
9.3.1. Order of Evaluation
Regardless of their complexity, the meanings of expressions are always
well-defined. Operands to operators will be evaluated left-to-right. For
example, given x+y+z , the compiler evaluates x, evaluates y , adds the
values together, evaluates z , and adds that to the previous result. The
compiler does not evaluate, say, y before x , or z before either y or x . Sim-
ilarly, argument expressions for method, or constructor, invocations are
evaluated from left to right, as are array index expressions for multidi-
mensional arrays.
Order of evaluation matters if x , y , or z has side effects of any kind. If,
for instance, x , y , or z are invocations of methods that affect the state of
the object or print something, you would notice if they were evaluated in
any other order. The language guarantees that this will not happen.
Except for the operators && , || , and ?: , every operand of an operator will
be evaluated before the operation is performed. This is true even for op-
erations that throw exceptions. For example, an integer division by zero
results in an ArithmeticException , but it will do so only after both oper-
ands have been fully evaluated. Similarly, all arguments for a method or
constructor invocation are evaluated before the invocation occurs.
If evaluation of the left operand of a binary operator causes an exception,
no part of the right-hand operand is evaluated. Similarly, if an expression
being evaluated for a method, or constructor, argument causes an ex-
 
Search WWH ::




Custom Search