Java Reference
In-Depth Information
It is a common mistake to refer to the elements of an array of reference type just after creating the array and
before assigning a valid object reference to each element. The following code illustrates this common mistake:
// Create an array of String
String[] name = new String[5];
// A runtime error as name[0] is null
int len = name[0].length();
// Assign a valid string object to all elements of the array
for (int i = 0; i < name.length; i++){
name[i] = "name" + ( i + 1 );
}
// Now you can get the length of the first element
int len2 = name[0].length(); // Correct. len2 has value 5
The concept of initialization of the String reference type array is depicted in Figure 15-1 . This concept applies to
all reference types.
null
null
null
name [2]
name [0]
name [1]
Memory state after the following statement is executed.
String[ ] name = new String[3];
hello2
hello1
hello3
name [2]
name [0]
name [1]
Memory state after the following statement is executed.
for (int i = 0; i < name.length; i++) {
name[ i ] = "hello"+ ( i + 1 );
}
Figure 15-1. Reference type array initialization
Search WWH ::




Custom Search