Wednesday, April 27, 2011

Compiler Error

Name the error in the following code:

public void foo() {
int x;
System.out.println(x);
}



ANSWER:

Compiler error. x is not initialized.

Thursday, September 30, 2010

Array memory footprint

What actually happens in memory (stack & heap) when you make the following declaration, and instantiation?

int[][] array2d = new int[15][5];





ANSWER:

STACK - 4 bytes, for the 4-byte reference pointer that is array2d.

HEAP - 15x4 bytes, for the first 'dimension' of the 2d array. 1 array of length 15, hosting 4-byte reference pointers.

HEAP - 15x5x4 bytes, for the second 'dimension' of the 2d array. 15 arrays of length 5, hosting 4-byte ints.

STACK TOTAL: 4 bytes
HEAP TOTAL: 360 bytes

To go above and beyond~ Java arrays are actually Objects (which is why they have the 'length' property). This means you also have to account for the memory created for the 'array' itself, as well as the array's super, or the Object class.