|
All objects in Java, including arrays, are created by using the operator new. This operator constructs an object of a given class and returns a reference to it. For example, if we first define a User class by
class User { private String name; private int age; public User( String nam, int a ) { name = nam; age = a; } }
we could then a create an object of type User by
User u = new User( "Zygot", 38 );
An array of, say, 100 Users would be created by[5]
User[] uAarr = new User[ 100 ];
and an array of a primitive type, say ints, would be created by
int[] arr = new int[ 100 ];
As was the case with C++, memory allocated for new objects created in this manner comes from a part of the system memory known as the heap.
Because of automatic garbage collection, Java does not need a delete-like operator to free up the memory occupied by objects that are no longer referenced. So in the following code fragment
User u = new User( "Zygot", 38 ); //(A) u = null; //(B) User[] uAarr = new User[ 100 ]; //(C) //code for assigning User references //to the individual elements of the //array uArr uArr = new User[500]; //(D)
after the reference held by u is changed to null in line (B), there would not exist a variable holding a reference to the object created in (A). Similarly, after the assignment in line (D), there would not exist a variable holding a reference to the array object created in line (C). (We are assuming in both cases that no other variables in the rest of the program are holding references to the objects created in (A) and (C).) Such objects are automatically scooped up by the garbage collector and the memory occupied by them freed up.[6]
Garbage collection in Java was introduced briefly in Chapter 3; the topic is presented more fully in Chapter 11.
[5]Array in Java are discussed in greater detail in Chapter 7.
[6]Additionally, all of the User objects to which the array elements brought into existence in line (C) are holding references to will also become eligible for garbage collection, assuming that no other variables are holding references to those objects.
|