15.9.3 Example: Evaluation Order and Out-of-Memory Detection

If evaluation of an array creation expression finds there is insufficient memory to perform the creation operation, then an OutOfMemoryError is thrown. This check occurs only after evaluation of all dimension expressions has completed normally.

So, for example, the test program:


class Test {
	public static void main(String[] args) {
		int len = 0, oldlen = 0;
		Object[] a = new Object[0];
		try {
			for (;;) {
				++len;
				Object[] temp = new Object[oldlen = len];
				temp[0] = a;
				a = temp;
			}
		} catch (Error e) {
			System.out.println(e + ", " + (oldlen==len));
		}
	}
}

prints:

java.lang.OutOfMemoryError, true

because the out-of-memory condition is detected after the argument expression oldlen = len is evaluated.

Compare this to class instance creation expressions (§15.8), which detect the out-of-memory condition before evaluating argument expressions (§15.8.2).