Java Reference
In-Depth Information
Array Objects
Because a Java array is an object, it should be no surprise that you use the
new
keyword to
instantiate an array. The
new
keyword requires the type of array being instantiated along
with the size of the array. For example, the following code instantiates three array objects:
5. int [] finishTimes = new int[20];
6. String lastNames [] = new String[100];
7. GregorianCalendar [] july;
8. july = new GregorianCalendar[31];
The
finishTimes
reference now points to an array of 20
ints
. Because this array of
ints
is a new object, its memory is zeroed on the heap, so all 20
ints
are initially
0
. The
lastNames
reference points to an array of 100
String
references (not
String
objects!).
Each of the 100
String
references is
null
. Similarly,
july
points to an array of 31
null
GregorianCalendar
references. Arrays in Java are zero-based indexed, meaning the fi rst
element in the array is index 0, the second element is index 1, and so on. For example, the
following code is valid and initializes some of the values in the arrays:
10. finishTimes[0] = 1002892;
11. finishTimes[1] = 1004830;
12. lastNames[99] = “Washington”;
13. july[0] = new GregorianCalendar(2010, 7, 1);
Figure 2.3 shows what the
finishTimes
and
lastNames
arrays look like in memory;
Figure 2.4 shows what the
july
array looks like in memory.
FIGURE 2.3
Examples of array references pointing to array objects.
0
1
2
3
.
.
19
1002892
0
0
0
.
.
0
array object of
20 ints
finishTimes
array references
null
null
null
null
0
1
2
3
.
.
99
lastNames
array object of 100
String references
“Washington”
A String Object
Search WWH ::
Custom Search