15.25.2
Compound Assignment Operators
EXPRESSIONS
doubles[throw]+=12345 => IndexThrow
Strings[1]+=throw => RightHandSideThrow
doubles[1]+=throw => RightHandSideThrow
Strings[1]+="heh" => Okay!
doubles[1]+=12345 => Okay!
Strings[throw]+=throw => IndexThrow
doubles[throw]+=throw => IndexThrow
Strings[throw]+="heh" => IndexThrow
doubles[throw]+=12345 => IndexThrow
Strings[9]+=throw => IndexOutOfBoundsException
doubles[9]+=throw => IndexOutOfBoundsException
Strings[9]+="heh" => IndexOutOfBoundsException
doubles[9]+=12345 => IndexOutOfBoundsException
The most interesting cases of the lot are tenth and eleventh from the end:
Strings[1]+=throw => RightHandSideThrow
doubles[1]+=throw => RightHandSideThrow
They are the cases where a right hand side that throws an exception actually gets
to throw the exception; moreover, they are the only such cases in the lot. This
demonstrates that the evaluation of the right hand operand indeed occurs after the
checks for a null array reference value and an out of bounds index value.
The following program illustrates the fact that the value of the left hand side
of a compound assignment is saved before the right hand side is evaluated:
class Test {
public static void main(String[] args) {
int k = 1;
int[] a = { 1 };
k += (k = 4) * (k + 2);
a[0] += (a[0] = 4) * (a[0] + 2);
System.out.println("k==" + k + " and a[0]==" + a[0]);
}
}
This program prints:
k==25 and a[0]==25
The value
1
of
k
is saved by the compound assignment operator
+=
before its
right hand operand
(k = 4) * (k + 2)
is evaluated. Evaluation of this right hand
operand then assigns
4
to
k
, calculates the value
6
for
k + 2
, and then multiplies
4
by
6
to get
24
. This is added to the saved value
1
to get
25
, which is then stored
into
k
by the
+=
operator. An identical analysis applies to the case that uses
a[0]
.
In short, the statements
k += (k = 4) * (k + 2);
a[0] += (a[0] = 4) * (a[0] + 2);
380
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved