Java Reference
In-Depth Information
In addition, arrays in Java are objects and therefore have a reference type. The Java
language implicitly defi nes a reference type for each possible array type: one for each of the
eight primitive types and also an Object array. This allows for references of the following type:
int [] grades;
String [] args;
Runnable [] targets;
The null Type
There is a special data type in Java for null . The null type does not have a name, so it is
not possible to declare a variable to be the null type. However, you can assign any refer-
ence to the null type:
String firstName = null;
Runnable [] targets = null;
Primitive types cannot be assigned to null , only references. The following statement is
not valid:
int x= null; //does not compile
We can also assign a reference to another reference as long as their data types are
compatible. For example, the following code assigns two ArrayList references to each other:
java.util.ArrayList<Integer> a1 =
new java.util.ArrayList<Integer>();
java.util.ArrayList<Integer> a2 = a1;
The references a1 and a2 both point to the same object, an ArrayList that contains
Integer objects. (Two references pointing to the same object is a common occurrence in
Java.) The ArrayList object can be accessed using either reference. Examine the following
code and determine if it compiles successfully and, if so, what its output is:
a1.add(new Integer(12345));
a2.add(new Integer(54321));
for(int i = 0; i < a1.size(); i++) {
System.out.println(a2.get(i));
}
The code adds an Integer to the ArrayList using a1 , and then adds another Integer
using a2 . Because they point to the same ArrayList , the list now has two Integer objects
in it, as shown in Figure 1.7.
Search WWH ::




Custom Search