Array Fundamentals
An array is a collection of multiple values of the same data type, organized in a specific order under a single identifier. Elements are accessed through numerical indices, starting from zero.
Key Characteristics:
- Arrays store data in contiguous memory blocks
- Arrays are reference data types
- Element values can be primitive types or other reference types
- Array length is fixed once created and cannot be modified
Classification:
| Classification Type | Categories |
|---|---|
| By Dimension | One-dimensional, Two-dimensional |
| By Element Type | Primitive element arays, Reference element arrays |
One-Dimensional Arrays
Declaration and Initialization
Arrays support two initialization patterns:
// Static initialization: declaration and assignment occur simultaneously
int[] numbers = new int[]{10, 20, 30};
// Dynamic initialization: allocate space first, assign values later
String[] names = new String[5];
Accessing Elements
Array indices begin at zero. The valid index range is 0 to length - 1.
String[] names = new String[5];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";
names[3] = "David";
names[4] = "Eve";
// names[5] would throw ArrayIndexOutOfBoundsException
Length and Traversal
int[] data = new int[4];
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
Default Initialization Values
When an array is created, elements receive default values based on their data type:
| Data Type | Default Value |
|---|---|
| byte, short, int, long | 0 |
| float, double | 0.0 |
| char | '\u0000' (null character, not '0') |
| boolean | false |
| Reference types | null |
int[] intArray = new int[5]; // all elements: 0
double[] doubleArray = new double[5]; // all elements: 0.0
char[] charArray = new char[5]; // all elements: '\u0000'
boolean[] boolArray = new boolean[5]; // all elements: false
String[] strArray = new String[5]; // all elements: null
Array Memory Model
The JVM allocates arrays using several memory regions:
int[] values = new int[]{1, 2, 3};
Stack: Contains the local variable reference (values)
Heap: Stores the actual array object with its elements
Method Area: Contains class metadata, constants, and static fields
The reference variable in the stack points to the array object in the heap. Heap address are displayed in hexadecimal format (e.g., 0x12ab).
Practical Example: Student Score Processing
import java.util.Scanner;
public class ScoreProcessor {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int studentCount = input.nextInt();
int[] grades = new int[studentCount];
System.out.println("Enter " + studentCount + " scores:");
for (int i = 0; i < grades.length; i++) {
grades[i] = input.nextInt();
}
int highestScore = 0;
for (int score : grades) {
if (score > highestScore) {
highestScore = score;
}
}
for (int i = 0; i < grades.length; i++) {
char letterGrade;
int difference = highestScore - grades[i];
if (difference <= 10) {
letterGrade = 'A';
} else if (difference <= 20) {
letterGrade = 'B';
} else if (difference <= 30) {
letterGrade = 'C';
} else {
letterGrade = 'D';
}
System.out.println("Student " + i + ": Score = " + grades[i]
+ ", Grade = " + letterGrade);
}
}
}
Two-Dimensional Arrays
Concept
A two-dimensional array can be visualized as an array of arrays. From the JVM's perspective, there is no true multi-dimensional array—only nested arrays.
Declaration and Initialization
// Static initialization
int[][] matrix1 = new int[][]{
{1, 2, 3},
{4, 5},
{6, 7, 8}
};
// Dynamic initialization with fixed dimensions
String[][] matrix2 = new String[3][2];
// Dynamic initialization with variable inner arrays
int[][] matrix3 = new int[4][];
matrix3[0] = new int[3];
matrix3[1] = new int[5];
Accessing Elements and Length
int[][] grid = new int[][]{
{1, 2, 3},
{4, 5},
{6, 7, 8}
};
System.out.println(grid.length); // 3 (outer array length)
System.out.println(grid[0].length); // 3 (first inner array length)
System.out.println(grid[1].length); // 2 (second inner array length)
System.out.println(grid[0][1]); // 2
Default Initialization Values for Two-Dimensional Arrays
Fixed inner dimensions (e.g., new int[4][3]):
- Outer array elements: contain addresses to inner arrays
- Inner array elements: follow one-dimensional default rules (0, 0.0, false)
Variable inner dimensions (e.g., new int[4][]):
- Outer array elements: null
- Inner array elements: cannot be accessed without first creating the inner arrays
int[][] arr1 = new int[4][3];
System.out.println(arr1[0]); // memory address (e.g., [I@15db9742)
System.out.println(arr1[0][0]); // 0
float[][] arr2 = new float[4][3];
System.out.println(arr2[0]); // memory address
System.out.println(arr2[0][0]); // 0.0
Common Array Declaration Patterns
// Standard declaration
int[] arrayA;
// Alternative syntax (less common)
int arrayB[];
// Combining declaration and initialization
int[] arrayC = {1, 2, 3, 4, 5};
// Two-dimensional alternatives
int[][] matrixA = new int[3][4];
int[] matrixB[] = new int[3][4];
int[][] matrixC = {{1, 2}, {3, 4}};
Invalid Array Declarations
// Error: Neither values nor length specified
// int[] a = new int[];
// Error: Array size cannot appear before variable name
// int[5] b = new int[5];
// Error: Cannot mix dynamic size with static values
// int[] c = new int[3]{1, 2, 3};
// Error: Both dimensions must be specified or variable inner dimension
// String[][] d = new String[][4];