EXPRESSIONS
Examples: Array Access Evaluation Order
15.12.2
If the array reference expression produces
null
instead of a reference to an
array, then a
NullPointerException
is thrown at run time, but only after all
parts of the array reference expression have been evaluated and only if these eval
uations completed normally. Thus, the example:
class Test {
public static void main(String[] args) {
int index = 1;
try {
nada()[index=2]++;
} catch (Exception e) {
System.out.println(e + ", index=" + index);
}
}
static int[] nada() { return null; }
}
prints:
java.lang.NullPointerException, index=2
because the embedded assignment of
2
to
index
occurs before the check for a null
pointer. As a related example, the program:
class Test {
public static void main(String[] args) {
int[] a = null;
try {
int i = a[vamoose()];
System.out.println(i);
} catch (Exception e) {
System.out.println(e);
}
}
static int vamoose() throws Exception {
throw new Exception("Twenty three skidoo!");
}
}
always prints:
java.lang.Exception: Twenty three skidoo!
A
NullPointerException
never occurs, because the index expression must be
completely evaluated before any part of the indexing operation occurs, and that
includes the check as to whether the value of the left hand operand is
null
.
343
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