Arrays
- A Java array behaves like a class.
- Every array has an instance variable called length that specifies
how big the array is.
- Note that this is the maximum size of the array, not the number of elements
being used.
- To use an array, you must:
-
declare a variable to hold the array
-
create the array
(allocate the space for the slots in the array with new).
-
create the elements in the array and store values in the array (allocate
the space for the elements with new).
- When you declare an array, you use brackets, and they may be after the class
or after the identifier name:
String array1[];
String[] array2;
- Next, you must create the slots with new:
array1 = new String[99]; // 99 slots, 99 references, each set to null
- Next, you must allocated each object in the array with new again:
array1[0] = new String("Cathy");
array1[1] = new String("Pippi");
array1[2] = new String("Lenny");
- Note:
null
means an null reference (and does not evaluate to 0 or '\0'.)
Like C and C++, arrays start at index 0.
An array stores references to objects, it does not
store the objects themselves.
The C equivalent is that arrays in Java are arrays of pointers.
Since primitives don't have constructors, you don't use the new in the
third step - just assign the values.
Again, Strings are special, so you don't necessarily have to do the 3
steps, but it's a good idea to practice it so you
do it correctly for other classes.
You may want to draw the memory involved with your array programming
assignment.