Skip to main content

Section 8.3 Reference Types

The container of a variable with a reference type always contains the reference to an object or the value null. In contrast to C, Java has no references to already freed objects that would cause undefined behavior if dereferenced. This is a result of Java's memory management strategy: Manually freeing memory like in C is not possible. As long as an object is accessible via a reference in the current program state (transitively), it is alive. No longer used memory is deallocated in Java via garbage collection. The Java runtime environment therefore regularly checks for objects that are no longer reachable via available references and frees their memory.

In contrast to C, it is impossible to declare variables with the type of a class or an array without indirection. Variables that are declared with such a type always implicitly contain reference types. The actual objects and arrays are always allocated on the heap with a new expression (see next section).

Subsection 8.3.1 Arrays

A variable with an array type contains a reference to a container with the length of the array and its elements. An array of values of the type T can be allocated with the expression new T[e], where e is an expression describing the length of the array. The new operator provides a reference to the newly create array. The length of an array is immutable: After being passed to the new operator, the length cannot change during the array's life time.

Consider the following example:

int[] a = new int[10];
int[] b = a;
a[2] = 42;
// print 42
System.out.println(b[2]);

Here, an array for 10 int elements is created. In line 2, the array is not copied, only a reference to it. The length of an array a can be determined with a.length:

// print 10
System.out.println(a.length);

Java also supports multi-dimensional arrays, for example:

int[][] arr    = new int[4][4];
int[]   subarr = arr[2];

In contrast to C, a multi-dimensional array is however not just a single container with space for all elements of the multi-dimensional array. Instead, it is an array of arrays. Since array types are reference types, every element of a multi-dimensional array is a reference to another (lower-dimensional) array. In the above example, arr[2] has the type int[]. The array arr contains references to arrays of the type int. Figure 8.3.1 shows the containers resulting from the above lines of code.

Figure 8.3.1. Multi-dimensional arrays in Java