Learn about array declaration, initialization, manipulation techniques, and implementing common array algorithms in Java.
Arrays store multiple values of the same data type with a fixed size determined at creation.
// Method 1: Declaration and initialization in two steps
int[] numbers; // Declaration
numbers = new int[5]; // Initialization with size 5
// Method 2: Declaration and initialization in one step
int[] scores = new int[10];
// Method 3: Declaration with initialization and values
int[] primes = {2, 3, 5, 7, 11};
When you create an array, elements are automatically initialized with default values:
// Primitive type arrays are initialized with zeros/false
int[] numbers = new int[3]; // {0, 0, 0}
boolean[] flags = new boolean[2]; // {false, false}
// Object arrays are initialized with null
String[] names = new String[3]; // {null, null, null}
Array elements are accessed using zero-based indexing.
int[] scores = {85, 92, 78, 95, 88};
// Accessing elements
int firstScore = scores[0]; // 85
int thirdScore = scores[2]; // 78
// Modifying elements
scores[1] = 94; // Array becomes {85, 94, 78, 95, 88}
The length of an array is fixed at creation time and can be accessed using the length property.
int[] numbers = {10, 20, 30, 40, 50};
int arrayLength = numbers.length; // 5
// Common pattern: Looping through array elements
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
The enhanced for loop (for-each) provides a simpler way to iterate through arrays.
int[] scores = {85, 92, 78, 95, 88};
// Using for-each loop
for (int score : scores) {
System.out.println("Score: " + score);
}
Java supports multi-dimensional arrays, which are essentially arrays of arrays.
// 2D array declaration and initialization
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing elements in a 2D array
int element = matrix[1][2]; // Row 1, Column 2: value is 6
// Looping through a 2D array
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}