The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated. For example, if the left-hand operand contains an assignment to a variable and the right-hand operand contains a reference to that same variable, then the value produced by the reference will reflect the fact that the assignment occurred first.
class Test { public static void main(String[] args) { int i = 2; int j = (i=3) * i; System.out.println(j); } }
9
It is not permitted for it to print 6
instead of 9
.
If the operator is a compound-assignment operator (§15.25.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied combining operation. So, for example, the test program:
class Test { public static void main(String[] args) { int a = 9; a += (a = 3); // first example System.out.println(a); int b = 9; b = b + (b = 3); // second example System.out.println(b); } }
12 12
because the two assignment statements both fetch and remember the value of the
left-hand operand, which is 9
, before the right-hand operand of the addition is
evaluated, thereby setting the variable to 3
. It is not permitted for either example
to produce the result 6
. Note that both of these examples have unspecified behavior in C, according to the ANSI/ISO standard.
If evaluation of the left-hand operand of a binary operator completes abruptly, no part of the right-hand operand appears to have been evaluated.
class Test { public static void main(String[] args) { int j = 1; try { int i = forgetIt() / (j = 2); } catch (Exception e) { System.out.println(e); System.out.println("Now j = " + j); } } static int forgetIt() throws Exception { throw new Exception("I'm outta here!"); } }
java.lang.Exception: I'm outta here! Now j = 1
because the left-hand operand forgetIt()
of the operator /
throws an exception
before the right-hand operand and its embedded assignment of 2
to j
occurs.