Objects and Arrays are the two basic kinds of Reference Types.

Objects

Creating an Object

  • Two stages:
    • Declare the variable to hold the reference to an object
    • Use new to create an object and associate it with the reference variable:
Grommet g;
Grommet h = new Grommet();
g = new Grommet();
h = new Grommet();	// What does this do?

Accessing an Object

  • Use the dot (.) operator to access fields of an object:
ComplexNumber c = new ComplexNumber();
c.x = 1.0;
c.y = -1.414;
double m = c.magnitude();

Destroying an Object

  • There is no operator in Java to do the opposite of new (i.e. no equivalent of delete in C++)
  • Java detects when an object is no longer being used (has no references)
  • Java automatically deletes such objects

Arrays

Creating an Array

There are two ways of creating an array:

  • Use new and specify the size of the array:
char buffer[] = new char[1024];
Grommet[] grommets = new Grommet[10];

Note where you can place the [] ! (Unlike in C or C++)

  • Use an initializer:
int ages[] = { 10, 35, 16, 92, 53 };

Each initializer value may be an arbitrary expression (unlike C).

Notes:

  1. You cannot say int ages[5] because it is a declaration of a reference to an array.
  2. What it refers to dynamically keeps track of its own length (number of elements)
  3. So, the right-hand side must define the number of elements.
  4. The reference variable ages can refer to arrays of different sizes during its lifetime.

Here’s the result of creating the array of primitive types:

int ages[] = { 10, 35, 16, 92, 53 };

On the other hand, here’s the result of creating an array of reference types:

Grommet[] grommets = new Grommet[10];

Accessing an Array

  • Indexes are 0-based, like C/C++
  • An index is either of type int, or be convertible to int
  • Index values are bounds-checked!
    • If bounds-checking fails at run time, throws ArrayIndexOutOfBoundsException.
  • The number of elements in the array may be determined from the length field.
  • Example:
int a[] = new int[100];
a[0] = 0;
for (int i = 1; i < a.length; i++)
    a[i] = i + a[i-1];

Destroying an Array

  • Arrays are automatically garbage collected, as are objects.