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

If evaluation of a class instance creation expression finds there is insufficient memory to perform the creation operation, then an OutOfMemoryError is thrown. This check occurs before any argument expressions are evaluated.

So, for example, the test program:


class List {
	int value;
	List next;
	static List head = new List(0);
	List(int n) { value = n; next = head; head = this; }
}

class Test {
	public static void main(String[] args) {
		int id = 0, oldid = 0;
		try {
			for (;;) {
				++id;
				new List(oldid = id);
			}
		} catch (Error e) {
			System.out.println(e + ", " + (oldid==id));
		}
	}
}

prints:

java.lang.OutOfMemoryError: List, false

because the out-or-memory condition is detected before the argument expression oldid = id is evaluated.

Compare this to the treatment of array creation expressions (§15.9), for which the out-of-memory condition is detected after evaluation of the dimension expressions (§15.9.3).