Fundamental Properties of Arrays
Arrays serve as a foundational data structure designed to hold a predetermined number of elements. These elements are strictly homogeneous, meaning an array defined for integers cannot store strings or floating-point numbers. This type safety ensures consistency in data handling.
A defining characteristic of arrays is their immutable length. Upon instantiation, the capacity is set. Attempting to add items beyond this limit results in an error, unlike dynamic collections such as Lists. Internally, arrays occupy contiguous blocks of memory, which allows for efficient random access using numerical indices.
Indexing Mechanism
Access to individual elements is managed via zero-based indexing. For a sequence of length N, the valid indices range from 0 to N-1. Consequently, the first item is located at index zero, while the last resides at index length - 1.
Declaration and Instantiation
Creating an array involves two primary steps: declaring the reference variable and allocating memory for the elements. In practice, these can be combined into a single statement.
// Declaring an array reference
int[] numericSequence;
// Allocating space for 5 integers
numericSequence = new int[5];
// Combined approach
double[] decimalValues = new double[10];
Element Assignment and Defaults
When a new array is allocated in memory, the runtime automatically assigns default values based on the data type. Numeric primitives default to zero (or 0.0 for floating points), booleans default to false, and object references default to null.
Explicit values are assigned by targeting the specific index:
numericSequence[0] = 42; // First element
numericSequence[1] = 15; // Second element
// ...
numericSequence[4] = 99; // Last element
Traversal and Iteration
To process the contents of an array, iteration is typically performed using standard loops. The array object exposes a public length field indicating the total capacity.
int total = 0;
for (int index = 0; index < numericSequence.length; index++) {
System.out.println("Value at index " + index + ": " + numericSequence[index]);
total += numericSequence[index];
}
System.out.println("Sum of elements: " + total);
Multidimensional Structures
Arrays can be nested to create complex data grids. A two-dimensional array is essentially an array of arrays, often visualized as a matrix with rows and columns.
// Initializing a 4x3 matrix (4 rows, 3 columns)
int[][] matrixGrid = new int[4][3];
matrixGrid[0][1] = 5;
matrixGrid[2][2] = 10;